Skip to content

feat(flow): row versions held from the baseline count who saved the target - #2457

Open
abrichr wants to merge 21 commits into
mainfrom
fix/version-source
Open

abrichr wants to merge 21 commits into
mainfrom
fix/version-source

Conversation

@abrichr

@abrichr abrichr commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

#2413 learns per-request bookkeeping from read-only requests, but it holds back the excuse from updates and "already there" (found) checks that have no version source. In those contracts, the bookkeeping refutation was the only thing that stopped a lost update: another user saves the record, then the agent's stale save puts it back, and the before and after states look like one correct save. The false-stop review (openadapt-internal#278, option D1) counted 40 stops held back for this reason: 23 on Kimai (MariaDB) and 17 on InvenTree (PostgreSQL).

This PR adds a version source that can count saves, and lets the probe's excuse apply where that source exists.

What a version source has to show

A "last saved" marker can't catch a lost update on an update. PostgreSQL xmin, an updated_at column and an ON UPDATE CURRENT_TIMESTAMP column all read the same after one save as after two. A marker can only show that nobody saved. So this PR doesn't use markers.

PostgreSQL keeps more than the marker. A read-only REPEATABLE READ transaction opened at the baseline keeps seeing the row version that was current then. That old version's xmax names the transaction that replaced it, and the current row's xmin names the last writer:

  • xmin unchanged: nobody wrote the row in the window.
  • old xmax equals current xmin: one transaction did.
  • anything else: two or more did, which is refuted as a lost update.

Changes

  • frame.row_versions (runtime/effects/row_versions.py, a new field in frame.py): a table and key column, PostgreSQL only.

    • capture_baseline opens the held read before it reads the baseline records.
    • The judge counts the writers of every target, then closes the held read.
    • Fails closed (not checked) when:
      • the held read is missing, for example when the judge runs in another process;
      • the read fails;
      • a target row is missing;
      • a target was created in the window;
      • the old xmax could be a shared-lock multixact that names another updater.
  • learn probe --apply (learn_probe.detect_row_versions): writes frame.row_versions beside the excuse on an update or found contract, but only when all of these hold:

    • every write effect reads one surface;
    • that surface's read is one SELECT ... FROM <table> t with no other FROM, over the frame's own connection;
    • the identity field comes straight from one column.

    Otherwise the contract still gets no excuse. MySQL and MariaDB targets get no source.

  • verify_run.py: _judge_versions' target collection is now the shared _version_targets, so both version checks judge the same targets.

No app name appears in engine code.

Measured

Replay of the first-contact retest's graded InvenTree cases (PostgreSQL), in openadapt-internal evidence/false-stops-2026-11/version-source (branch claude/version-source-evidence-2026-11). No model calls. Each case was judged by three verifiers on the same write:

The trees, the patch and the harness were hashed before the first scored case (FREEZE.sha256). The new setup is the frozen setup plus learn_probe.apply of the fix setup's own probe proposal, so both variants carry the same excuses from the same probe rounds. Rebuilding the fix setup the same way reproduces it exactly, apart from approval times.

InvenTree, paired frozen fix new
Correct writes that would block (claude and codex replays plus fault-pack controls) 65/65 48/65 27/65
Planted and agent harms that passed (31) 0 0 0
Caught by frozen, passed by new none
  • Released: 21. These are 14 update_part and 7 ensure_company writes, each stopped in fix by the held bookkeeping. No correct write that passed in fix stops in new.
  • Lost updates. Each one stops in new, and the row-version check itself gives the reason ("the target moved more than one version"):
    • the pack's F19 and F20;
    • four tighter plants: V01, F20 with no gap; V02, F19 with no gap; V03, an edit and a stale revert against a found check; V04, a tag added and removed by the stale PUT.
  • The agent's duplicate (ollama T10, a new part made instead of the update) stops with "the record ... was created in the window". This rule was added after a pilot of that one case showed the excuse would otherwise leave only an unrelated settings row stopping it. It is recorded as a deviation.
  • Excuse attacks. All 9 stop on new (another user's token row, three other columns of the agent's token row, on three released update_part cases), and the 3 controls confirm.
  • Still stopped in new on InvenTree (27):
  • Other apps. The detector derives no frame.row_versions on Kimai, Snipe-IT or OpenMRS (MariaDB or MySQL), or on Firefly and Gitea, so their contracts are byte-identical between fix and new. Two Gitea contracts read frame.versions, which goes through the refactored target collection, so Gitea's 30 planted-fault cases were replayed against all three verifiers. All 30 have the same outcome in fix and new. The same 6 of 23 harms pass silently in frozen, fix and new (F08, F13, F14, F15, F17, F19), so this change neither adds to nor removes from the 9 of 46 held-out misses the review reported. On Gitea's 31 correct claude writes, the same 8 would block in all three verifiers. Firefly runs none of the changed code paths, so it was not rerun. Snipe-IT was not rerun either: its 268 contracts read frame.versions, but its fixture doesn't run on the zen lab, so for Snipe-IT the claim rests on the refactor being a pure extraction, on test_frame_versions, and on Gitea's add_comment cases, which use frame.versions.

Against the review's kill criteria (openadapt-internal#278, D1):

  • "Any planted lost update passes": not met. None of the 6 planted lost updates passed (F19, F20, V01–V04). The agent's duplicate create (ollama T10) also stops, on the created-target rule.
  • "Fewer than half of the 40 are released": met by its letter. Every held InvenTree stop in this run is released (21; the review counted 17 there). None of Kimai's 23 are, because MariaDB has no source. That is at most 21 of the review's 40, so the criterion fires. The Kimai share needs change capture from the database log.

Not covered

  • Kimai's 23 held stops (MariaDB) stay held. It has no history table, log_bin=0, and only an app-set modified_at, so nothing here can count its saves. Those need the database's change log, which the round-2 false-stop work owns.
  • A child row that the window adds and then removes leaves no row version. V04 is refuted because the stale PUT also writes the part row a second time; this run doesn't show a child-only change being caught. The frame's counter check should catch an added-then-removed row whose key comes from a sequence, but that wasn't measured here. A composite-key link table would not be caught. The detector refuses reads that look into other tables, but the source still can't see such rows.
  • The held read must stay in one process. It lives in this process from begin to judge, as in the replay harness. A caller that begins and judges in separate processes (separate verify-run invocations) gets not checked, so it gets no release from this, but no lost update passes either.
  • The held read holds back vacuum for the length of the window, up to max_execution_window_s. The server's idle_in_transaction_session_timeout is set to one hour on that session.

openadapt-flow learn probe reads the whole-database frame, sends only GET
and HEAD requests as the agent, and reads again. A changed row of the
acting user that moved (a last-login or token-use time) becomes a
frame.learned excuse with source read_only_probe, with no approval. Added
rows, rows of other users and rows no user owns are not admitted.
…arget

On PostgreSQL, a read-only REPEATABLE READ snapshot opened at the baseline
still sees the row version that was current then. Its xmax names the
transaction that replaced it; the current row's xmin names the last
writer. Equal: one transaction wrote the target in the window. Different:
two or more, which is a lost update. frame.row_versions turns this on per
contract, and learn probe now writes it beside a bookkeeping excuse on an
update or found check whose generated read it can trace to one table.
MySQL and MariaDB targets get no source: a last-saved marker reads the same
after one save as after two.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 165a094

The unique work is a PostgreSQL-only count of who saved the target, using a read-only REPEATABLE READ snapshot opened before the baseline records and closed in the judge. The arithmetic is sound for the cases it claims: xmin unchanged is zero writers; old xmax equal to current xmin is one; anything else is two or more and refutes as a lost update. A missing held read (including a judge in another process), a failed read, a target created in the window, a missing row, an unknown target_surface, and a changed target whose version did not move all stop as not checked, never a pass. Shared-lock xmax is treated as a stop unless the id equals the later xmin and pg_get_multixact_members shows no other updater, in which case it is not checked rather than held. _version_targets is a behavior-preserving extract of the frame.versions target list (same confirmed write effects, same “existed” rule). learn_probe.detect_row_versions refuses MySQL/MariaDB, a different connection, a second FROM, a join, a computed identity, and a subquery that declares child rows. The CAPABILITIES row states the fail-closed cases and the composite-key add/remove limit. I did not merge.

frame.row_versions.table / key_column are not bound to the target surface

The judge trusts a hand-written (or later-edited) table and key_column without checking that they are the target surface's single-table read. open_held only checks that the named relation exists and is a table (relkind r or p). If that table happens to have a row for the target's key, the writer count is taken from the wrong relation.

That is fail-open for the exact lost-update this source exists to catch: another user saves the real target, the agent's stale save reverts it, and the before/after records look like one correct write. The whole-database frame does not see that either. If frame.row_versions points at some other table whose matching key had at most one writer, judge_row_versions holds and the run can confirm. A typo in target_surface already stops as unknown_surface; a typo in table or key_column does not.

The probe derives the right names from a one-table SELECT ... FROM <table> t, but the verifier never re-imposes that invariant, so a hand-written spec or an edit after --apply can detach the check from the records it is supposed to count.

What would flip this to APPROVE: bind table and key_column (and the key values) to the target surface's single-table read — at load, or as not_checked in the judge — whenever they do not match, including a hand-written spec. Do not hold on a relation the surface does not read.

Residuals that do not block once that is closed: a generated read whose identity column is last, or that ends with WHERE, is missed by the detector (no source, fail-closed); a truncated multixact whose id collides with the later xmin could theoretically read as one writer if members are gone; a hold leaks until MAX_HOLD_S if capture_baseline fails after open_held. The composite-key add-and-remove limit is already stated in CAPABILITIES.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 165a094

Codex (read-only, at the head above, against fix/learn-bookkeeping-read-probe) checked the PR body's claims, the fail-closed paths, the _version_targets refactor and the earlier Grok review. It looked at correctness and safety only.

Confirmed:

  • The _judge_versions extraction into _version_targets preserves behavior: target filtering, the existed/changed calculation, unknown-surface handling and result application are the same as on the base.
  • These paths are present: PostgreSQL-only validation, the held read opened before the record baseline, stops for missing and created targets, a stop when the held read is missing, and no automatic source on MySQL or MariaDB.

Blockers

  1. frame.row_versions is not bound to the target surface (runtime/effects/frame.py:550, runtime/effects/row_versions.py:188). Validation checks only the dialect and identifier syntax, and open_held checks only that the relation exists and is a table. table, key_column, target_field and target_surface are never checked against each other. Failure: a found check reads asset, but row_versions.table names an unchanged decoy table that has a row with the same key. Another user edits asset and the agent's stale save reverts it, so the surface shows no change. The decoy reports zero writers, which changed=False allows, the learned bookkeeping is excused, and the run can confirm despite two writes to the real target. Codex reproduced the judge returning held for this wrong-relation case. This is Grok's blocker from the earlier round. It is real and not fixed at this head.

  2. Every pg_get_multixact_members error is read as "plain xid" (runtime/effects/row_versions.py:229). The bare except Exception returns False, so the old xmax is counted as one writer. Failure: the old xmax is a multixact whose value equals the current writer's xmin and that names an earlier updater, but the lookup fails because of permissions, a connection problem or another server error. The error is swallowed, one writer is counted (lines 334-337), and the lost update passes. Only the specific "not a multixact" error should mean a plain xid. Any other failure should give not_checked.

  3. The detector doesn't enforce the single-SELECT, single-table shape the PR describes (learn_probe.py:378). It accepts SELECT 999 AS id, 'synthetic' AS name UNION ALL SELECT t.id AS id, t.name AS name FROM asset t and derives asset, because the query has only one FROM and ends with FROM asset t. A found check can match the synthetic branch. --apply then installs both the bookkeeping excuse and a row-version witness for a row the record doesn't come from, so an edit-and-revert on the real target can leave no net change while the unrelated key reports zero writers. The detector needs a structural check that every returned record comes from the named table, for example by rejecting UNION, INTERSECT, EXCEPT and WITH.

Earlier reviews

  • Grok, REQUEST CHANGES at this same head: table and key_column are not bound to the target surface. Not fixed (blocker 1). No commits have landed since that review.

CI

Both failing unit tests come from the base branch, not this diff:

  • test_cli_no_abbreviations::test_standalone_cli_constructor_inventory_also_disables_abbreviations: learn.py is identical in the base and the head. The test flags the existing learn_probe.add_parser(steps) call.
  • test_backend_parity::test_every_app_url_flag_has_a_backend_neutral_alternative: the gap is the existing learn probe --base-url.

protected-safety-review fails because the PR is stacked on a branch other than main.

…eside an update the versions don't cover

Review blockers on #2413:
- A move must show in every read-only round (at least two), so a one-off
  edit to the acting user's own row during one round is not excused.
- _sees_its_own_harm judged only record_written effects. Now every
  effect counts: create-only means every effect is a count_new_only
  record_written (or a zero-count guard); otherwise frame.versions must
  cover each other effect on its target_surface.
- Annotate the kept/held lists (mypy).
- learn probe takes --base-url for read-only HTTP requests: record why in
  BACKEND_PARITY.md's URL flags table.
- Rename learn_probe.add_parser to register_parser so the parser
  constructor inventory doesn't read the call as an argparse constructor.
…-multixact means a plain xid; one-table reads only

Review blockers on #2457:
- frame.row_versions is judged only when its table and key_column are the
  table and column the target_surface's read takes the target_field from,
  over the frame's own connection (row_versions.binding_problem). A decoy
  table with the same key now leaves the frame not checked
  (unbound_source) instead of vouching for a target it never held.
- _multixact_updater_other_than treats only PostgreSQL's "MultiXactId N
  has not been created yet" / "does no longer exist" as a plain xid. Any
  other error is raised, so the judge reports not checked.
- detect_row_versions (now row_versions.single_table_read) accepts one
  SELECT over one table and rejects UNION, INTERSECT, EXCEPT, JOIN,
  LATERAL, WITH, subqueries and a second statement.
learn_probe._sees_its_own_harm now takes both: every effect must create,
or frame.versions / a bound frame.row_versions must cover every other
effect's surface. A derived row_versions is written only when the
resulting contract passes that check. Docs describe the binding and the
one-table read.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

From: Claude
Reviewed-Head: 50c1f58

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 50c1f58

P1. The version read can still use a different physical row from the target. The new binding check rejects a mismatched table, named surface or column in the simple direct-projection case. It also rejects the earlier set-operation query. Two gaps remain in that same binding. First, the projection matcher searches for a column reference anywhere in the SELECT text. A computed identity whose expression ends with that column can qualify. The returned value then differs from the column used to look up the row. Second, the reader accepts a nonunique column as the key. The baseline and current reads each put all matching rows in a dictionary keyed by that value. When two rows share it, one version silently replaces the other. Require the entire key projection to be the supported direct column or cast, and return not_checked when a key maps to multiple physical rows in either read. Both the detector and the runtime judge use this binding. Projection and binding · Baseline rows · Current rows

P1. An expired MultiXact still counts as evidence of one writer. The new exception handling correctly sends permission failures and other unexpected errors to not_checked. It also recognizes PostgreSQL’s “does no longer exist” response and returns false from the ambiguity check. PostgreSQL raises that error for an ID older than its retained MultiXact range. The response supplies no historical membership information. Treat an expired lookup as not_checked unless independent tuple evidence establishes a plain transaction ID. Error classification · Writer count · PostgreSQL retention check

I reviewed the corrective commit and the merge against #2413. Eligibility now requires a derived row-version source to cover the other write effects’ surfaces. The request-attribution and unscoped version-history findings belong to the base PR. The fixes here apply across applications. The author reports 124 tests passed and 45 PostgreSQL tests skipped. I reviewed the source and test assertions. No new PostgreSQL run or held-out result was available for these cases. GitHub CI was queued at review time. Base review · CI

# Conflicts:
#	CAPABILITIES.md
#	llms-full.txt
… for unscoped versions

Codex review blockers on #2413.

fail-open class: correlation-as-attribution. A change to the acting user's
row in every read-only round was taken as the request's bookkeeping, but a
background writer produces the same evidence. Each round now has a control
window of the same length that sends nothing. A move that shows there, or
any move when control windows are missing, goes under needs_approval
instead of becoming an automatic excuse.

fail-open class: ambiguous-subject-binding. With frame.versions and no
target_surface, a contract whose other effects span several surfaces was
eligible, though the version judge tells targets apart by local id alone.
Such a contract now gets no automatic excuse.
# Conflicts:
#	packages/flow/openadapt_flow/learn_probe.py
…keys and expired multixacts

Codex review blockers on #2457.

fail-open class: ambiguous-subject-binding. The projection matcher found
the key column anywhere in the select list, so a computed identity ending
with that column qualified while returning a different value than the
lookup column. The select item must now be exactly t.<column> or
CAST(t.<column> AS TEXT). When a key maps to more than one physical row in
the baseline or current read, the target is not_checked instead of one
version silently replacing the other.

fail-open class: absent-evidence-as-success. PostgreSQL also says "does no
longer exist" for a multixact older than its retained range, whose members
are gone. Only "has not been created yet" now means a plain xid; an expired
lookup leaves the target not_checked.
…und move

Gemini review blocker on #2413 (fail-open class: absent-evidence-as-success).
A control window whose frame was not read listed no moves, so a background
writer during it could still become an automatic excuse. Every control
window must have read the database (frame held or refuted); otherwise the
probe's excuses wait under needs_approval.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 021037a

Gemini cross-vendor review covering:

Summary of Gemini's output; it reported no findings.

  1. Regex anchoring (ambiguous subject binding). single_table_read now anchors the select item to SELECT or , on the left and , or FROM on the right. An expression ending in the column (for example 1 + t.id AS "id") is rejected. Only t.<col> or CAST(t.<col> AS TEXT) is accepted.
  2. Duplicate keys. _unique_rows raises DuplicateKey when a key maps to more than one physical row in either the baseline or the current read. judge_row_versions catches it and returns not_checked, so one version can't silently replace another.
  3. Expired MultiXacts (absent evidence as success). _NO_SUCH_MULTIXACT now matches only "has not been created yet". An expired MultiXact ("does no longer exist") falls through to the generic handler, which leaves the target not_checked.
  4. Conflict resolution in _sees_its_own_harm. The one-surface rule from feat(flow): learn per-request bookkeeping from read-only requests #2413 is applied to the frame.versions branch. When frame.versions is absent or ambiguous, the check falls through to the frame.row_versions branch.
  5. Tests. test_a_computed_identity_is_not_the_key_column, test_a_key_naming_two_rows_is_not_checked and test_an_expired_multixact_is_not_checked enforce these fixes.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

From: Claude
Reviewed-Head: 021037a

@abrichr

abrichr commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

From: Claude
Reviewed-Head: f798799

@abrichr

abrichr commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: f798799

Verified clean merge with updated base #2413 (2144dc5f4da9d07b09ec082228a4a10f0c7f8741, including origin/main + refreshed cli_surface.json and CAPABILITIES.md command map) over the previously approved head 021037a9f217257a9b8d7e4b0c13e5d819100462:

  • Zero merge conflicts; all PR files (row_versions.py, versions.py, frame.py, verifier.py, verify_run.py, learn_probe.py, tests/test_row_versions.py) merged cleanly.
  • Targeted pytest (tests/test_row_versions.py, tests/test_capabilities_map.py, tests/test_cli_surface.py): 29 passed, 10 skipped (3.38s).
  • Generality & durability: general baseline-held row-version attribution across apps, no per-app engine code.

Base automatically changed from fix/learn-bookkeeping-read-probe to main November 23, 2026 02:45

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant