Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e6f9439
feat(flow): learn per-request bookkeeping from read-only requests
abrichr Nov 21, 2026
53910b3
fix(flow): no probe excuse for an update that can't see a lost update…
abrichr Nov 21, 2026
e413273
feat(flow): row versions held from the baseline count who saved the t…
abrichr Nov 21, 2026
8fb9a79
fix(flow): row versions: a shared-lock xmax is not one writer; probe …
abrichr Nov 21, 2026
efad0ee
fix(flow): row versions never vouch for a target created in the windo…
abrichr Nov 21, 2026
165a094
docs: capability row for row versions; refresh llms-full
abrichr Nov 21, 2026
c39bd6e
Merge remote-tracking branch 'origin/main' into HEAD
abrichr Nov 21, 2026
f1d7a65
fix(flow): a probe excuses only a move every round shows; no excuse b…
abrichr Nov 21, 2026
9397a64
docs(flow): learn probe excuses only moves every round shows
abrichr Nov 21, 2026
9a0976e
fix(flow): row versions bound to the target's own table; only no-such…
abrichr Nov 21, 2026
50c1f58
Merge #2413's review fixes into fix/version-source
abrichr Nov 21, 2026
bb2285c
Merge remote-tracking branch 'origin/main' into HEAD
abrichr Nov 22, 2026
83138c0
fix(learn): attribute probe excuses with control windows; one surface…
abrichr Nov 22, 2026
60ca91d
Merge commit '83138c03a184693760694410b702e8af0ac4786d' into HEAD
abrichr Nov 22, 2026
b076917
fix(row-versions): bind the key projection exactly; refuse duplicate …
abrichr Nov 22, 2026
c274d55
fix(learn): an unreadable control window is no evidence of no backgro…
abrichr Nov 22, 2026
021037a
Merge commit 'c274d556aad313eab70ebdcba45c3699656e5e65' into HEAD
abrichr Nov 22, 2026
1930cc3
Merge commit '24034b59d72ea4c05960b4e729d9aea72a771b06' into HEAD
abrichr Nov 22, 2026
9117e38
test(flow): regenerate cli_surface.json for learn probe
abrichr Nov 22, 2026
2144dc5
docs: refresh command map and llms-full.txt for learn probe
abrichr Nov 23, 2026
f798799
Merge commit '2144dc5f4da9d07b09ec082228a4a10f0c7f8741' into HEAD
abrichr Nov 23, 2026
0d902b1
Merge remote-tracking branch 'origin/main' into HEAD
abrichr Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
| Count who saved an update's target on PostgreSQL, so learned bookkeeping can be excused on updates and found checks too: `frame.row_versions` holds a read-only REPEATABLE READ snapshot from the baseline to the judge; the replaced row version's `xmax` against the current row's `xmin` says whether one transaction or more wrote the target. Two or more refute the frame as a lost update; a judge in another process, a failed read, a target created in the window, an `xmax` that could be a shared lock naming another updater, or a `frame.row_versions` table and key that aren't the ones the target surface reads the target from stop it as not checked. `learn probe --apply` writes the source beside the excuse when the contract's read is one `SELECT` over one table (no join, `UNION`, subquery or second statement). Not yet: MySQL and MariaDB targets (a last-saved marker can't count saves; they need a history read or the change log), rows a window adds and removes on a composite key | (this PR) | Real app replay (InvenTree on PostgreSQL, first-contact retest, frozen vs fix vs this branch on identical writes): correct writes stopped 65, 48 and 27 of 65; the 21 released were all bookkeeping stops on updates and found checks, and none newly stopped; 0 of 31 planted and agent harms passed in any variant, and the row-version check itself refuted the planted lost updates (the pack's 2 plus a no-gap PATCH, a no-gap PUT, a found-check revert and a child-row revert); 9 of 9 excuse attacks stopped. No change on MariaDB apps (no source is derived) | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) |
27 changes: 26 additions & 1 deletion packages/flow/docs/LEARNED_EXCUSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,32 @@ effect (its `target_surface`; with none set, every other effect must be
on one surface, since an unscoped read tells records apart by id alone). In an update with no
version source, another user's edit that the agent's stale save reverts
leaves nothing changed, and only the bookkeeping move stopped it, so such
contracts keep stopping. No person approves them: the
contracts keep stopping unless the probe can give them a version source.

On PostgreSQL it can, for a contract whose write effects all read one
surface, and whose read is one `SELECT ... FROM <table> t` (no other
`FROM`, no join, `UNION`, `WITH`, subquery or second statement) over the
frame's own connection with the identity field taken from one column. The
probe then writes `frame.row_versions` (table, key column and target
surface) beside the excuse. At check time the verifier derives the table
and key again from the target surface's read and refuses a
`frame.row_versions` that names another table or key (not checked), so a
hand-written source can't point at a table nobody edits. At check time the verifier opens a read-only
REPEATABLE READ transaction before it reads the baseline and keeps it open
until the judge. That transaction still sees the target row's version from
the baseline, and that version's `xmax` names the transaction that replaced
it. If it equals the current row's `xmin`, one transaction saved the
target. Anything else means two or more did, and the frame is refuted as a
lost update. A judge in another process, a failed read, or a replaced
version whose `xmax` could be a shared lock naming another updater makes the
frame not checked. Only PostgreSQL's "has not been created yet" or "does no
longer exist" answer means that `xmax` is a plain transaction id; any other
error reading the lock leaves the frame not checked. A last-saved marker (`xmin` alone, `updated_at`,
`ON UPDATE CURRENT_TIMESTAMP`) is not used: it reads the same after one
save as after two. MySQL and MariaDB updates get no automatic source; they
need `frame.versions` over a history table, or the database's change log.

No person approves them: the
rows were read, the relation is derived from the schema, and the requests
are checked to be read-only. A contract that already has `frame.learned`
is refused, so a person reconciles the two. Receipts name the source.
Expand Down
123 changes: 106 additions & 17 deletions packages/flow/openadapt_flow/learn_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,12 +336,16 @@ def apply(
names |= _learn._names(n)
except VerifierError as exc:
raise ProbeError(f"{path}: {exc}") from exc
row_versions = None
if not _sees_its_own_harm(loaded):
# An update (or a found check) with no version source: another
# user's edit that the agent's stale save reverts leaves nothing
# changed, so before learning only the bookkeeping move stopped
# it. Such a contract gets no automatic excuse.
continue
# it. Such a contract gets an excuse only with a version source
# derived here, written beside it.
row_versions = detect_row_versions(data)
if row_versions is None:
continue
excuses = [
e
for e in block["excuses"]
Expand All @@ -354,10 +358,14 @@ def apply(
**frame,
"learned": {**block, "excuses": excuses, "source": "read_only_probe"},
}
if row_versions is not None:
new["frame"]["row_versions"] = row_versions
try:
Contract.from_dict(new, name=Path(path).stem)
checked = Contract.from_dict(new, name=Path(path).stem)
except VerifierError as exc:
raise ProbeError(f"{path}: {exc}") from exc
if row_versions is not None and not _sees_its_own_harm(checked):
continue # the derived source doesn't cover every effect
plan.append((Path(path), new, len(excuses)))
_learn._write_all(
[
Expand All @@ -374,11 +382,14 @@ def _sees_its_own_harm(contract: Any) -> bool:

Either every declared effect creates new records (``record_written``
with ``count_new_only``; a zero-count guard writes nothing), or the
contract reads the target's versions (``frame.versions``) and those
versions cover every other effect: with a ``target_surface``, each
effect that isn't a create must be read on that surface. Anything else,
such as a create plus a ``field_equals`` update, gets no excuse."""

contract reads the target's versions and they cover every other effect:
``frame.versions`` (with a ``target_surface``, each effect that isn't a
create must be read on that surface), or ``frame.row_versions`` bound to
the target surface's own table (:func:`row_versions.binding_problem`)
with every other effect on that surface. Anything else, such as a create
plus a ``field_equals`` update, gets no excuse."""

from openadapt_flow.runtime.effects.row_versions import binding_problem
from openadapt_flow.runtime.effects.surfaces import surface_of

config = getattr(contract, "config", None)
Expand All @@ -405,16 +416,94 @@ def guard(effect: Any) -> bool:
others = [e for e in effects if not creates(e) and not guard(e)]
if not others:
return any(creates(e) for e in effects)
versions = getattr(frame, "versions", None) if frame is not None else None
if versions is None:
if frame is None:
return False
versions = getattr(frame, "versions", None)
if versions is not None:
surface = getattr(versions, "target_surface", None)
if surface is None:
# fail-open class: ambiguous-subject-binding. An unscoped version
# read judges targets by their local id alone, so two records
# with one id on two surfaces would share one version check.
if len({surface_of(e) for e in others}) == 1:
return True
elif all(surface_of(e) == surface for e in others):
return True
rows = getattr(frame, "row_versions", None)
database = getattr(frame, "database", None)
verifier = getattr(config, "verifier", None)
if rows is None or database is None or verifier is None:
return False
if binding_problem(
rows,
getattr(verifier, "surfaces", None) or {},
getattr(database, "read", None) or {},
getattr(frame, "identity_field", None),
):
return False
surface = getattr(versions, "target_surface", None)
if surface is None:
# fail-open class: ambiguous-subject-binding. An unscoped version
# read judges targets by their local id alone, so two records with
# one id on two surfaces would share one version check.
return len({surface_of(e) for e in others}) == 1
return all(surface_of(e) == surface for e in others)
return all(surface_of(e) == rows.target_surface for e in others)


def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]:
"""A version source for an update or found check, from the contract
alone: on PostgreSQL, the target's own row versions
(``frame.row_versions``). Found only when every write effect reads one
surface, that surface's read is a plain ``SELECT ... FROM <table> t``
with no other ``FROM`` over the frame's own connection, and it selects the identity field
straight from one column. Anything else: None (no excuse).

A MySQL or MariaDB target has no such source: ``updated_at`` and
``ON UPDATE`` columns read the same after one save as after two, so they
can't count saves. Those need a history read (``frame.versions``) or the
database's change log."""

frame = data.get("frame") if isinstance(data, Mapping) else None
if not isinstance(frame, Mapping):
return None
database = frame.get("database")
if not isinstance(database, Mapping) or database.get("dialect") != "postgresql":
return None
names: set[str] = set()
for effect in data.get("effects") or []:
if not isinstance(effect, Mapping):
return None
if effect.get("kind") not in ("record_written", "field_equals"):
continue
if effect.get("kind") == "record_written" and effect.get("expected_count") == 0:
continue # a guard reads; it has no target
probe = str(effect.get("probe") or "")
if not probe.startswith("surface="):
return None
names.add(probe[len("surface=") :].split("|", 1)[0].strip())
if len(names) != 1:
return None
(surface,) = names
verifier = data.get("verifier")
surfaces = verifier.get("surfaces") if isinstance(verifier, Mapping) else None
source = surfaces.get(surface) if isinstance(surfaces, Mapping) else None
if not isinstance(source, Mapping) or source.get("kind") != "sql":
return None
read = database.get("read") or {}
if any(source.get(k) != read.get(k) for k in ("sql_driver", "sql_connect_args")):
return None # another database: its rows aren't the frame's
from openadapt_flow.runtime.effects.row_versions import single_table_read

# One SELECT over one table: the declared record is one row, so the
# row's versions are the record's. A read that also looks into other
# tables (a list of tags, a child row, a UNION) declares rows this
# source doesn't count.
found = single_table_read(
str(source.get("sql_query") or ""), str(frame.get("identity_field") or "id")
)
if found is None:
return None
table, key_column = found
return {
"source": "postgresql_xmin",
"table": table,
"key_column": key_column,
"target_surface": surface,
}


def http_sender(
Expand Down
13 changes: 13 additions & 0 deletions packages/flow/openadapt_flow/runtime/effects/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
covers,
set_columns,
)
from openadapt_flow.runtime.effects.row_versions import FrameRowVersions
from openadapt_flow.runtime.effects.versions import FrameVersions, VersionVerdict

FrameStatus = Literal["held", "refuted", "not_checked"]
Expand Down Expand Up @@ -516,6 +517,10 @@ class FrameSpec(BaseModel):
#: (``versions.FrameVersions``): a version in the window that isn't the
#: agent's own is a lost update.
versions: Optional[FrameVersions] = None
#: The target's own row versions, held from the baseline
#: (``row_versions.FrameRowVersions``, PostgreSQL): two transactions
#: writing the target in the window are a lost update.
row_versions: Optional[FrameRowVersions] = None
#: Complete type/table change feeds for a provisional then final verdict.
history: Optional[FrameHistory] = None
#: Moves a person approved from ``openadapt-flow learn``
Expand All @@ -534,6 +539,8 @@ def _compact(self, handler: Any) -> dict[str, Any]:
data.pop("identities", None)
if data.get("versions") is None:
data.pop("versions", None)
if data.get("row_versions") is None:
data.pop("row_versions", None)
if data.get("learned") is None:
data.pop("learned", None)
if data.get("target_fields_by_surface") is None:
Expand All @@ -543,6 +550,12 @@ def _compact(self, handler: Any) -> dict[str, Any]:
@model_validator(mode="after")
def _database_attribution(self) -> "FrameSpec":
a = self.attribution
if self.row_versions is not None:
if self.database is None or self.database.dialect != "postgresql":
raise ValueError(
"frame.row_versions reads through frame.database, PostgreSQL only"
)
self.row_versions.names()
if (
self.history is not None
and self.database is not None
Expand Down
Loading
Loading