Skip to content

feat(tx): verify API and SaaS writes by resource read-back and the system's own log - #2437

Merged
abrichr merged 18 commits into
mainfrom
claude/api-scoped-verify
Nov 22, 2026
Merged

abrichr merged 18 commits into
mainfrom
claude/api-scoped-verify

Conversation

@abrichr

@abrichr abrichr commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Hosted systems such as Epic, Salesforce, Stripe or Linear give OpenAdapt no database to diff, so "nothing else changed" can't be proven there. This PR adds a narrower check, and every result states its scope:

  • The record reads back as intended. The target record is read back and judged with the tx codecs (including null_empty from fix(tx): learn NULL versus empty string per field as a codec #2402). On an update, every other field of the record must be unchanged.
  • The system's own log shows no other change by the same credentials. The write's own event must appear in the system's event or audit log, and no other resource may have been changed by the same credentials in the window.

Stacked on claude/ext-tx-safety (openadapt proxy and txplan, not yet in a PR), with #2402 merged in. The base is that branch, so this diff shows only this work. Coordination is in openadapt-internal#211.

What changes

Area Change
txplan/audit.py One log reader, configured as data in the tx file: a FHIR AuditEvent search, an event stream and a REST activity feed. The window is placed by event ids, not by time alone. An empty page, or a read that ends before the cursor, is read again and never taken as "no events".
txplan/scoped.py scoped_write: pre-read, send once, read-back, log cross-check, verdict, and a record/run/v1 receipt for every outcome. ApiTools provides the api_read and api_write MCP tools.
Idempotency The key comes from the task and the record (identity fields, or a slot), never the payload, and it is written to the ledger before the send. A retry returns the first result. A regenerated payload is refused (replay_mismatch). A crash between the send and the ledger is recovered by a marker search or the log, not by sending again. The key goes out as Idempotency-Key where the API honors one, or as a FHIR If-None-Exist.
openadapt proxy --api FILE Serves the API tools on the same MCP endpoint as the SQL tools. The agent's environment has the API credentials removed, along with any copy of them. There are small hooks in proxy.py (Proxy.tools(), extra).
Verdicts Hard failure (FAILED): wrong value, partial write, a clobbered field, a missing resource, a duplicate, or another resource changed by the same actor. Logged only: unknown event types. Retried, then COMPLETED_UNVERIFIED: a trailing log, or a log that can't be read.
Docs docs/API_VERIFICATION.md, a section in TRANSACTIONS.md, a CAPABILITIES row, the proxy command line, and llms-full.txt.

Measured

Medplum 5.2.8 (AuditEvent) and Gitea 1.24.6 (activity feed) ran in Docker on the zenbook lab, with synthetic data. Details are in benchmark/api_scoped/RESULTS.md.

Medplum Gitea
Clean writes stopped 0 of 400 0 of 400
Planted faults the log exposes: wrong value, duplicate, partial write, same-actor collateral change all stopped, 10 of 10 per class all stopped, 10 of 10 per class
Collateral title edit (Gitea's feed doesn't record edits) not applicable 0 of 10 stopped, as expected
Another actor's change (outside the scope) 0 of 10 stopped 0 of 10 stopped
Regenerated-payload retry (ACRFence) 10 of 10 refused 10 of 10 refused

Kill criterion: any missed fault the log exposes, or more than 1% clean stops. It was not met on either system.

The first full runs did meet it, in two ways:

  • Medplum stopped 4 of 300 clean writes. In two traces, the write's own AuditEvent was stamped about 1.5 seconds before an event read before the write, so the cursor, placed on time alone, dropped it.
  • One Medplum partial-write plant was not stopped. The likely cause is that the field the plant left unwritten already held the intended value, but that was not confirmed.

Both are fixed and the second is tested. The Gitea development stops were not reproduced. Summaries of those runs are in results/development/.

Stripe was not run. No test-mode key exists (.env.local holds a placeholder), and live keys weren't used. The event-stream reader is unit-tested against pages in Stripe's shape only.

Limits

  • Scope: the resource and the actor. Changes by other callers, and kinds of change the log doesn't record, aren't checked.
  • Idempotency: the guard is only as good as the declared identity fields.
  • Sample size: 10 plants per fault class bounds the miss rate only at about 26%.
  • FHIR _history: not used. Medplum has no system-level history, so collateral changes come from AuditEvent.
  • Updates in one task: a second write to the same record needs a new slot; without one it is refused as a replay.
  • Ledger: the begun event keeps the pre-write record, in the owner-only state folder.
  • CI: the base isn't main, so most CI hasn't run. Locally, test_txplan_scoped, test_txplan, test_tx_null_empty and test_capabilities_map pass, and mypy and ruff are clean on the new files.

…n log

Adds resource-scoped verification for API and SaaS systems with no database
to diff: txplan/audit.py reads a system's event or audit log as data (FHIR
AuditEvent, event streams, REST activity feeds), and txplan/scoped.py sends a
write once under a key derived from the task and the record, reads the record
back with the tx judge's codecs, and checks the log for other changes by the
same actor. The proxy serves the API tools on the same MCP endpoint.
… Gitea

Medplum's AuditEvent times run up to about 2 s out of request order, so a
cursor on server time alone dropped the write's own event in about 1 write in
100. The cursor now keeps the ids of every event within skew_s of the newest,
and an empty page or a read that ends before the cursor is read again instead
of taken as no events. An update that changes nothing needs no log event.

Bench: 0 of 400 clean writes stopped on each system; every planted fault the
log exposes stopped (10 of 10 per class); regenerated-payload retries refused.
Adds API_VERIFICATION.md, RESULTS.md and the CAPABILITIES row.
… record, and the limits

A not-yet-settled API check no longer marks its receipt line as an approved
write. An update or delete can name a slot for a deliberate second write to
the same record in one task; without one it stays a refused replay. Tests
verify each outcome's receipt and the two-write MCP path. RESULTS.md now
reports every development-run stop, including the missed partial-write
plant, and the _history and ledger limits.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Review of the hooks this PR adds to txplan/proxy.py, proxy_cli.py and spec.py, at edc200631, from the #2428 owner. This is not a merge decision.

The interface is fine. The extra toolset with tools() and call(), McpServer listing proxy.tools(), hiding the SQL tools when no database is given, and hiding the API credentials from the child are all good. #2428 now has the same extra, tools() and fall-through, as of c88d728c, so most of this diff is now on the base.

Please merge claude/ext-tx-safety at 33ee1032 before review. The two branches conflict in these places:

  1. proxy_cli._run calls default_task() with no argument. On the base, the default task is one per database and project folder, stable across proxy restarts: default_task(database). Calling it with no argument raises TypeError there. For --api-only mode, pass the tx file's resolved path.
  2. Proxy.call routes to extra before the SQL tools. On the base, extra comes last, so an extra tool named sql_* can't shadow the SQL path. Please keep that order.
  3. Proxy.__init__ and run(...) signatures: take the base's versions, then add api_spec.

One question. spec.py now imports openadapt_flow.txplan.audit at module load. Please keep audit.py free of heavy imports: tests/test_verifier_import_boundary.py and openadapt plan load spec.py.

Resolves the proxy conflicts on #2428's version: its Proxy.extra and
tools(), one dispatch path for the extra toolset, and its run() signature
with api_spec added. The CLI now calls default_task() with the database or,
for --api alone, the tx file, so an API-only proxy keeps one stable task per
project folder.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 2b9a14c

First review of this PR, at the current head (the later #211 request is the merge of #2428 a23dfeda onto edc200631). Author is GitHub abrichr, not Grok. Review only; I am not merging.

The unique scoped-verify work is mostly aimed correctly. A cursor is placed by event ids within skew_s of the newest server time, not by time alone. An empty first page is retried and, unless may_be_empty, refuses to place a cursor (test_a_log_that_comes_back_empty_is_not_read_as_new). A read that runs out of pages without seeing those ids raises AuditError("the log ended before the cursor"). Crash recovery does not resend a create unless the write is proven absent (marker search, or a complete audit window with no matching create); otherwise it is recovery_unproven and COMPLETED_UNVERIFIED. A resolved retry returns the first result. Regenerated payloads are replay_mismatch. The #2428 merge keeps Proxy.__init__(extra=...) and a single dispatch path, lists SQL tools only when the proxy holds a database, and test_proxy_cli_api_only_gets_a_stable_default_task pins a stable --api task.

One path is not fail-closed. In AuditReader.after, a page that contains any event older than cursor.at - skew_s returns the window immediately:

if older:
    return win

That bypasses the reached check which otherwise raises "the log ended before the cursor". The list is documented as newest-first, but the same file says server times are not always in request order. A page that holds this write's own event and one stale-stamped row can end the read before any cursor id is seen, so a later duplicate or collateral on the next page is never considered and the write can still be VERIFIED. _recover can also count that short read as complete and set proven_absent, then resend a create that already landed. after() should only return on older when reached is true; otherwise it should raise the same incomplete-log error. Cover that in the same test family as the empty-page case.

This head is still stacked on #2428. The inherited _apply_sql fallback (commit on _shape when staged_after is missing from unsigned private.json) is unchanged; I am not re-litigating it here beyond noting it remains in the tree.

@abrichr

abrichr commented Nov 21, 2026 •

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Gemini
Reviewed-Head: 2b9a14c

This PR is protected and written by Claude, so it needs a reviewer from another vendor. Codex could not run (its local config failed to load), so this review is from Gemini (gemini-3.1-pro-preview). Gemini read the diff against claude/ext-tx-safety, without the two raw result files results/gitea.json and results/medplum.json. It checked the PR body's claims, looked for fail-open paths, and checked the earlier blockers. The orchestrating agent checked each finding against the code at this head.

Earlier blockers

  • Grok, AuditReader.after returns early on an older event: not fixed. packages/flow/openadapt_flow/txplan/audit.py, line 495, still has if older: return win, before the reached check.
  • Owner's hook comments at edc200631: fixed. proxy_cli._run calls default_task(target) with the resolved tx-file path, and test_proxy_cli_api_only_gets_a_stable_default_task covers it. Proxy.call tries the sql_* names first and extra last. audit.py imports only standard-library modules.

Blockers

  1. txplan/audit.py, AuditReader.after: a page that holds an event older than cursor.at - skew_s returns the window before any cursor id has been seen. Suppose the write's own event and one row with a stale timestamp are on the first page, and a duplicate or a same-actor collateral change is on the next page. _verify never sees the later events and can return VERIFIED. _recover counts the short read as complete, sets proven_absent, and can send again a create that already landed. Fix: when older is set, return only if reached is true; otherwise raise the same AuditError("the log ended before the cursor"), or break into the existing check. Add a test next to the empty-page test.

Raised but not counted as a blocker

  • Gemini said Proxy.tools lists the SQL tools in --api-only mode. In the code, Proxy.system defaults to "db", so the SQL tools appear only if an API system in the tx file is named db. In that case an sql_* call fails with an error and does not write anything. The PR could refuse that name or check the system's kind, but this does not block merging.

Gemini raised no other blockers.

AuditReader.after keeps reading past a page with an event older than the
window until it has seen one of the cursor's own events, so a stale
timestamp can't hide a duplicate or collateral change on a later page; a
log that ends first still raises. ruff format for the PR's flow files.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Re-review request for Gemini's and Grok's REQUEST CHANGES at 2b9a14cc. New head: 5911378579526d4e4d09b841ecce2b7c1232bc85.

What changed:

  • AuditReader.after (packages/flow/openadapt_flow/txplan/audit.py): a page holding an event older than cursor.at - skew_s ends the read only if one of the cursor's own events was already seen (if older and reached). Otherwise reading continues, and a log that ends before the cursor still raises AuditError("the log ended before the cursor"). Test: test_a_stale_stamped_event_does_not_end_the_read_before_the_cursor, where a duplicate on page 2 behind a stale-stamped event on page 1 is now seen, and a short log raises. It fails on the old code.
  • ruff 0.17.0 format for the PR's five flow files (audit.py, proxy.py, proxy_cli.py, scoped.py, test_txplan_scoped.py).
  • Merged the base claude/ext-tx-safety at 5e8f0c8f (feat(plan, proxy): dry-run diff, idempotent apply, verified undo and receipts for agent writes to external systems #2428's staged_after and no_undo fixes, launcher format).

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 5911378

The earlier cursor finding is fixed. An older timestamp can end the read only after a stored cursor ID is seen. A short log with no cursor ID now raises AuditError. The ordinary verification path retries that error and reports audit_unreadable if the log stays incomplete. Cursor reader · Verification

Create recovery can still authorize a second write without proving the first was absent. Two branches feed the same proven_absent decision.

  1. Log recovery increments complete on any successful read. If the first read reaches the cursor before the event becomes visible and subsequent reads fail, complete > 0 still permits a resend. An earlier snapshot cannot establish absence through the configured lag interval. Require a conclusive read at the end of that interval or an equivalent server guarantee. An unresolved recovery should return COMPLETED_UNVERIFIED without sending. Log recovery · Documented guarantee
  2. Marker recovery also treats an unreadable search result as an empty result. _request turns invalid JSON in a successful HTTP response into {}; _search can then return an empty list, which _recover treats as proof of absence. Preserve the distinction between a valid empty result in the configured API format and a response whose shape or contents cannot be interpreted. Cover both recovery branches with an assertion that an inconclusive read leaves the write count unchanged. Response parsing · Marker search · Resend decision

I ran six focused synthetic cases. Five passed on the first run, including the new two-page regression, short-log refusal, delayed readback, and crash recovery with a visible marker or audit event. The clean create/update receipt check initially loaded an older installed openadapt-types and passed when rerun against this branch’s Types source. The two remaining findings come from tracing the recovery decisions in source.

The fix belongs in the shared create-recovery decision. Both log and marker observations must distinguish found, proven absent, and unknown across all configured APIs. The PR records separate Medplum and Gitea measurements; those measurements did not cover the two recovery conditions above.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: 5911378

Codex run on 5911378. Scope: the delta since the earlier reviewed head 2b9a14cc (PR commit de5ee3db2 plus the merge of claude/ext-tx-safety). This is the third review round.

Earlier blockers

  1. AuditReader.after returned early on an older event before the cursor was reached (Grok and Gemini at 2b9a14cc): fixed. packages/flow/openadapt_flow/txplan/audit.py now returns on an old timestamp only when older and reached. Until it sees a cursor id it keeps paging, and if the log ends first it raises AuditError("the log ended before the cursor"). Recovery skips that failed read before it counts complete reads (scoped.py, around line 755). The regression test in packages/flow/tests/test_txplan_scoped.py (around line 821) checks that the second page's create is returned and that a truncated feed raises AuditError. Codex ran it directly and it passed.

Blockers

None. The merge kept the PR's changes and brought in the base changes intact.

Out of scope (follow-up)

None.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 5911378

Codex (codex exec --sandbox read-only) review of the PR diff at this head, posted as Codex returned it apart from shortening local file links to repo paths.

  1. audit.py:510 — The reported stale-first-page case is fixed. A page containing both a stale event and one cursor ID still ends the read, even with another page advertised. A duplicate or collateral event within the skew window on that next page is missed.
  2. scoped.py:774 — One successful poll before the log catches up suffices to authorize a resend even if every later poll fails. The shipped Gitea comment reference also contains only the parent issue ID, so recovery can see the create event and still resend the comment.
  3. scoped.py:749 — Recovery treats one empty marker search as proof of absence. Invalid JSON and responses missing the configured results field also become empty lists. A marker-only API can receive a duplicate create.
  4. scoped.py:416, scoped.py:746 — A committed delete followed by a crash is reported as HALTED before recovery runs. A committed update subsequently edited by another caller is resent from the old baseline, potentially overwriting that edit.
  5. audit.py:437 — The authenticated client follows an absolute pagination link without checking its origin. An off-origin next link receives the API credential and can supply audit evidence.
  6. scoped.py:185 — Caller-controlled IDs and route fields are interpolated verbatim into authenticated request URLs. Path separators, dot segments, and query delimiters can redirect a read or write outside the declared collection before verification.
  7. audit.py:431, audit.py:598 — A mutation with a missing ID or invalid timestamp is silently discarded. A mutation naming both the target and another resource counts solely as the target’s event. Either permits VERIFIED despite collateral activity.
  8. scoped.py:662 — Omitting audit allows a successful read-back alone to produce a signed VERIFIED. When an audit is configured but its pre-write cursor cannot be obtained, the write is still sent.
  9. proxy_cli.py:122 — API-only mode accepts SQL systems and drops the input spec’s anomaly rules. A mixed file with a SQL system named db exposes SQL tools and can auto-approve writes above the operator’s row limit.
  10. scoped.py:409 — Cached success is keyed by logical system name without binding the resolved API endpoint or account. Repointing the same spec from staging to production can return staging’s VERIFIED result without contacting production.
  11. scoped.py:170 — The Medplum marker replaces the entire caller-supplied identifier array. The patient is created without the intended identifiers before read-back reports the mismatch.
  12. scoped.py:181 — A full replacement sends the pre-read record without a version precondition. It can erase a concurrent edit and then pass frame verification because the verifier compares against that same stale baseline.
  13. scoped.py:576, scoped.py:596 — Irreversible deletes bypass the configured holdback and are recorded as reversible. Separately, a signing failure still allows VERIFIED to be returned and cached with receipt: false.
  14. induce.py:974 — Two successive GETs can teach null_empty from another caller’s edit. That grants a lasting equivalence without evidence that the server normalizes the field, allowing a later clobber to pass.
  15. run.py:255 — The Gitea collateral controls discard HTTP status and unconditionally record landed=True. A rejected side write therefore counts as planted in the published evidence.

All 47 focused tests passed at 59113785, including the regression for the previously reported cursor case.

…ites

Instance fixes, named by class until the shared fail-open harness lands:
- clock placement: the audit read is placed by cursor id, not time; it ends
  only after every cursor id is seen, and an event listed before them counts.
- missing evidence: unplaceable events, malformed pages and searches, and
  unreadable GET bodies raise; recovery needs every lag poll to succeed and
  every marker search to come back empty; a configured log with no cursor
  sends nothing.
- off-origin: an absolute next link must stay on the log's origin.
- hidden collateral: an event naming the target and another record is
  collateral too; an unmatched create blocks proof of absence.
- stale baseline: a crashed update resends only over the unchanged record;
  a crashed delete is recovered, not halted.
- skipped holdback: an irreversible delete is refused in scoped mode.
- wrong target: cached results are keyed by endpoint.
- dropped requirement: --api keeps the file's rules and refuses SQL systems.
- unproven equivalence: null_empty is learned only from this write.
- benchmark evidence: a planted side write counts only if accepted.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

How each item in Codex's round-3 review at 59113785 was handled. New head: a2e438f6f0c0b701d3350ee08b593c571cb54265. Fail-open items are fixed here as minimal instance fixes named by class. The rest are filed in #2474.

# Item Status
1 A page with a stale event and one cursor id ends the read Fixed: the read is placed by cursor id, not by clock. It ends only after every cursor id is seen. Events listed before them count as new whatever their time, and a log that ends first raises. Tests extend test_a_stale_stamped_event_does_not_end_the_read_before_the_cursor.
2 One good poll authorizes a resend; a comment create seen only by its parent Fixed: proof of absence needs every lag poll to read to the cursor, and any create by these credentials that can't be tied to a record blocks it.
3 One empty marker search is proof of absence; bad JSON and missing fields read as empty Fixed: every poll through the lag budget must come back empty, and there is no proof without a log. A search response of the wrong shape, or a GET body that isn't JSON, raises.
4 A crashed delete halts before recovery; a crashed update resends over another caller's edit Fixed: a missing record is recovered when a begun entry exists. An update resends only when the record still equals the pre-crash baseline.
5 Off-origin next link gets the credential Fixed: an absolute link must match the log's origin, checked before any request.
6 IDs interpolated into URLs Fixed through the base (#2428): every path value is one quoted segment.
7 Events with no id or time dropped; multi-resource events counted only as the target's Fixed: an unplaceable event or a malformed page raises. An event naming the target and another record is collateral too.
8 A configured log without a cursor still sends Fixed: nothing is sent (HALTED, audit_cursor_unreadable). Read-back-only VERIFIED without a log is by design, filed in #2474.
9 --api accepts SQL systems and drops anomaly rules Fixed: --api serves the file's own spec, rules included, and refuses SQL systems.
10 Cached result not bound to the endpoint Fixed: the key includes the system's resolved URL.
11 Medplum marker replaces identifier Not fail-open; filed in #2474.
12 Full replacement without a version precondition Other-actor class, a known miss; filed in #2474.
13 Irreversible delete skips holdback; unsigned VERIFIED cached Delete fixed: scoped mode refuses a delete unless delete_reversible (use a plan with holdback). The unsigned-cache half is filed in #2474.
14 null_empty learned from another caller's edit Fixed: learned only when this write sent one empty spelling and the server stored the other.
15 Benchmark plants recorded as landed regardless of status Fixed: a planted side write counts as landed only when the server accepted it. The published result files will be rerun after merge.

Also merged the base claude/ext-tx-safety at e1949ce9. Tests: test_txplan_scoped.py 32 passed, test_txplan.py 32 passed. Codex delta review requested in the review inbox.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: a2e438f

I checked the two requested commits against the recovery review and the round-three findings.

The reader now waits for all saved cursor IDs. Log-only recovery requires a successful read on every poll, and a missing configured pre-write cursor stops the write. The changes also preserve the API-only spec’s rules, refuse irreversible scoped deletes before dispatch, compare retry updates with their saved baseline, check absolute pagination links against the log origin, and count an event naming both the target and a bystander as collateral. I found the following remaining correctness issues in the changed paths.

  1. An unchanged feed can report a new mutation. Cursor acquisition saves only IDs within the timestamp window. The new reader counts any unseen ID while one saved ID is still pending. An older-stamped entry already present between two saved IDs on the baseline page is therefore counted as new on the identical next read. Preserve the IDs actually observed in the scanned portion of the baseline. An unchanged page should yield zero new events, including when its timestamps are out of order. Cursor acquisition · Window read
  2. Inconclusive create evidence can still authorize a resend. With a configured marker-results path, the new validation checks the outer object. A missing or malformed result collection still becomes an empty list, and entries without a record ID are filtered out. Repeating that response through the lag interval authorizes a resend merely because a log reader is configured. The log-only branch has a related hole: a same-actor create without an extracted resource never enters the resource loop that marks a create unresolved. Both cases should remain recovery_unproven. Validate each format’s legitimate empty-result shape, and require a resolvable resource before classifying a seen create as unrelated. Marker parsing · Recovery decision
  3. The cache now distinguishes endpoints but still reuses results across accounts on one endpoint. The key binds the resolved URL, task, collection, operation and slot. Authorization is supplied separately. Changing accounts behind a shared service URL can return the first account’s cached VERIFIED before any read of the second account. Bind a trusted account or tenant identity to the key, or forgo the cache hit when that identity is unavailable. Keep credential values out of receipts and logs. Cache key and early return · Shared-URL pack
  4. The benchmark records rejected plants but still counts them in its conclusion. The corrected Gitea sender records whether the server accepted a side write. The summary increments stopped on every non-verified outcome and calculates misses against all attempts, independently of landed. A rejected plant can therefore count as detected. Separate landed, rejected and unresolved attempts in the result and kill criterion. The checked-in measurements predate that change. Mark the affected Gitea claims provisional until accepted-plant evidence is available. Plant status · Summary · Published figures

I inspected the committed tests for stale pagination, missing timestamps, and multi-resource events. The author reports 32 scoped tests passing. I did not rerun the suite or contact a provider. The parent PR and the separately filed #2474 items were outside this delta review.

Keeps both sides in tx/induce.py (requested-value volatility from main, the
own-write null_empty rule here) and in CAPABILITIES.md; llms-full.txt rebuilt.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 6736d9a

The merge brings in 721da41c. I checked both conflict resolutions. The induction code retains the base’s route-role logic and the PR’s requirement for an observed write before learning a null/empty conversion. The capability table preserves the scoped API row. Induction · Capability rows

The four findings from the previous verdict remain open. I compared the Git objects for the audit reader, scoped writer, state key, scoped tests, API verification documentation, and full benchmark directory with a2e438f6. Each is byte-identical.

  • Audit cursor. An unchanged feed can classify a previously observed older-stamped entry as a new mutation.
  • Create recovery. A nested marker response missing its configured results, or a create event without an extracted resource, can still authorize a resend.
  • Cached verification. Different accounts using the same endpoint can share a cached VERIFIED result.
  • Benchmark evidence. A stopped trial can still count as a successful detection when its plant did not land. The published Gitea figures still predate the acceptance check.

I reused the earlier source and test evidence. This merge introduced no new scoped test results.

…rk scoring

- missing evidence: a marker search without its results field (and no
  total 0) raises; a create event naming no resource blocks proof of absence.
- wrong target: cached results are keyed by a digest of the credential too,
  so two accounts on one endpoint never share one.
- benchmark evidence: a stop counts as a detection only for a plant that
  landed.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

How each item in Codex's round-4 review at 6736d9ab was handled. New head: 8aa0b012cc6809fcef507da19b58dd6ced4d412f (includes a merge of the base at 1714660c). We are past the two-round cap, so only fail-open items are fixed.

Item Status
Audit cursor: an older-stamped entry listed before the cursor ids reads as new Fails closed (a false alarm on a clean write). Filed in #2482.
Create recovery: nested marker response without results; create event with no resource Fixed. A marker search with no results field raises unless it reports total: 0. A create naming no resource blocks proof of absence. Test: test_a_marker_search_without_its_results_is_not_empty.
Cached VERIFIED shared across accounts on one endpoint Fixed. The key includes a digest of the credential.
Benchmark: a stop counts when its plant didn't land Fixed: summarize counts a stop only for a plant that landed, and reports not_landed separately. The published Gitea figures will be rerun after merge (filed in #2482).

Tests: test_txplan_scoped.py and test_txplan.py, 67 passed. If nothing new fails open, please approve against the filed lists in #2474 and #2482.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 1b613a5

The corrective commit fixes the audit-only recovery case: a create event with no resource now prevents a conclusion of absence. The last commit only sorts imports. Three issues remain in the requested delta.

  1. A partial marker response can still authorize a second create. The shipped Medplum pack uses entry.*.resource. The new check validates only entry. An entry missing resource, or a returned resource missing its ID, disappears from the result. Recovery treats repeated empty results as proof of absence and allows another send. Validate the full results path and each returned identity before accepting an empty search. The new test covers a missing top-level key, an explicit zero, and a complete flat result. Pack · Search · Recovery · Test

  2. The stored operation ID follows the credential value instead of the account used by the client. Renewing a token for the same account changes both the ledger key and the create marker. A retry with a fresh client can therefore miss the original write and send again. Conversely, a reused context caches its HTTP client and authentication headers, while the key calculation reads the environment afresh. A changed account setting can then label a result with a different account from the one the HTTP client used. Bind the operation to a stable account identity and endpoint from the client that will send it. Preserve retries across credential renewal, or refuse to resend when account continuity is unknown. Client initialization · Context cache · Write key and marker · Pre-send lookup

  3. The benchmark can report a passing gate without a confirmed plant. Explicit False is now excluded. The producer also permits landed=None, which still increments the denominator and can count as a detection. An exposed class whose plants all returned False has zero trials and zero stops, so it also clears the missed-class test. Count only confirmed plants and mark classes with no confirmed trial as unmeasured when deciding the gate. This is a scoring change that can be checked with rows alone. Row construction · Scoring · Gate

I reviewed the immutable source and checked-in assertions. The author reports 67 tests passed. I did not rerun tests or use a live target. The audit-cursor false alarm and Gitea rerun remain with #2482. The dispositions in #2474 are unchanged.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 2ac3d51

Gemini run on 2ac3d51 (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it.

The implementation of resource-scoped verification for API and SaaS systems is thoroughly designed and robust against fail-open conditions. The handling of idempotency, crash recovery, and audit log lag is particularly well thought out.

A few highlights of the safety mechanisms verified during this review:

  1. Crash Recovery: The _recover logic correctly fails safe (returns COMPLETED_UNVERIFIED) if there is no audit log to definitively prove absence after a crash, preventing dangerous resends that could cause undetected duplicates. If an audit log is present, it relies on _verify to catch any duplicates that a resend might create, ensuring it fails closed.
  2. Idempotency and ACRFence: The idempotency key is strictly derived from the task and record identity, never the payload. Regenerated payloads for the same record are correctly refused (replay_mismatch), preventing semantic rollback attacks.
  3. Audit Log Integrity: The AuditReader correctly validates page shapes, refuses off-origin pagination links (preventing credential leakage and evidence spoofing), and strictly places the window by event IDs rather than time alone to handle server clock skew.
  4. null_empty Codec: The new codec safely resolves the NULL vs "" equivalence problem by scoping it strictly to the learned fields and only treating those two specific values as equivalent, preventing actual clobbers from slipping through.
  5. Proxy CLI: The CLI correctly isolates API credentials from the agent's environment and safely multiplexes SQL and API tools on the same MCP endpoint without cross-contamination.

No fail-open paths, signature bypasses, or injection vulnerabilities were found.

@abrichr
abrichr changed the base branch from claude/ext-tx-safety to main November 22, 2026 02:23
An error occurred while trying to automatically change base from claude/ext-tx-safety to main November 22, 2026 02:23
…ns, null_empty from the write's response

- public-artifacts.json lists the api_scoped benchmark packs, compose file
  and results (env-var names only, no credentials).
- the benchmark runner's ArgumentParser sets allow_abbrev=False.
- unproven-equivalence class: null_empty is learned from a write's own
  response (an untouched field the server re-spelled, or an empty value
  sent one way and stored the other), never between two reads; a test
  covers two GETs around another caller's edit.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 6c1a1c1

Gemini run on 6c1a1c1 (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a delta after #2428 merged and main was merged in. The prompt held the fix commit and this PR's txplan and induce diff against main for context.

The delta in this fix commit correctly addresses the remaining edge cases for the null_empty codec induction without introducing any fail-open paths.

By requiring that the null_empty equivalence is only learned from a write's own response (either an untouched field that the server re-spelled, or an empty value sent one way and stored as the other), it prevents the system from incorrectly learning the codec from a collateral edit made by another caller between two reads. The logic tightly enforces this by checking curr_ex.method in {"POST", "PUT", "PATCH"} and ensuring that if the field was explicitly sent, it was sent as one empty spelling but stored as the other (flat_req[path] != new_val).

The allow_abbrev=False addition to the benchmark runner's argument parser is a standard safety practice, and the test coverage accurately reflects the new constraints.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: fb8f6b9

Gemini run on fb8f6b9 (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a merge-only delta since 6c1a1c1, where CI had passed. The prompt held this PR's files as the main merge changed them. Gemini returned only its verdict line.

@abrichr
abrichr merged commit faf4cf7 into main Nov 22, 2026
56 of 57 checks passed
@abrichr
abrichr deleted the claude/api-scoped-verify branch November 22, 2026 06:46
yunusarda-sudo pushed a commit to yunusarda-sudo/OpenAdapt that referenced this pull request Nov 22, 2026
…plants per class

- missing-evidence class, kept: a marker search without its items field is
  still an error, unless it reports total 0 or matches the pack's new
  search_empty shape. Medplum's empty search Bundle leaves entry out, which
  made OpenAdaptAI#2437's rule fail closed on every create; its pack now declares
  search_empty: {path: resourceType, equals: Bundle}.
- the Medplum lab's compose raises the per-user FHIR quota and rate limit
  (loopback lab only); audit-log reads spent the default within seconds.
- rerun on Medplum 5.2.8 and Gitea 1.24.6 with 400 clean writes and 50
  plants per class: 0 clean stops on each; every log-exposed fault 50 of 50
  stopped; known misses reported as misses (Gitea title edits the feed
  doesn't record, 0 of 50; another caller's change, 0 of 50 on each);
  Stripe not run (no test-mode key).
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