From 1a65ce5b296ed9bffa0d2d96e622cf2023852917 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:29:33 -0500 Subject: [PATCH 1/9] feat(verify): recheck an API read-back and the system's log after a window A write checked against an API and an activity log is checked again after a window the caller sets. The log checkpoint is taken before the first read, the state keeps only keyed MACs, and entry ids, not clocks, place the window. A change since the first read gives REFUTED or NOT_CHECKED, never VERIFIED; a first result that wasn't VERIFIED is never raised. --- CAPABILITIES.md | 1 + llms-full.txt | 1 + .../runtime/effects/api_recheck.py | 644 ++++++++++++++++++ packages/flow/tests/test_api_recheck.py | 419 ++++++++++++ 4 files changed, 1065 insertions(+) create mode 100644 packages/flow/openadapt_flow/runtime/effects/api_recheck.py create mode 100644 packages/flow/tests/test_api_recheck.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cad88c6b1c..7e79d72b71 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -182,6 +182,7 @@ improvising or retrying when something is off. | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | +| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main (PRLINK) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | diff --git a/llms-full.txt b/llms-full.txt index d67812cb9a..c132605cc8 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -616,6 +616,7 @@ improvising or retrying when something is off. | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | +| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | In review | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py new file mode 100644 index 0000000000..c90577667c --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -0,0 +1,644 @@ +"""Delayed recheck of an API read-back and the system's own activity log. + +Most systems give no database access. A write checked there has two sources +the system itself produces: a read of the record through its API, and, often, +a log of what each caller changed. A check made right after the write says +what those sources showed at that moment. A background job, a webhook +handler, a colleague's edit or a delayed duplicate can change things later. +This module repeats the check after a window the caller sets. + +``begin`` runs right after a verified first check. It takes a log checkpoint, +then reads the record, in that order, so nothing the log records can fall +between the two reads unseen. It keeps a private state: a salt, keyed MACs of +the declared fields and of the record's version (never the values), the +log's opaque checkpoint, and keyed MACs of the write's own events. The +receipt carries only ``state_sha256`` and the due time. + +``recheck`` runs at or after the due time. It reads the record again, reads +the log from the checkpoint and judges: + +- ``VERIFIED``: as of the recheck time, the read-back showed the same + declared values and version, and the log, read back to the checkpoint, + holds no mutation of the record and no mutation by this caller that no + later declared write accounts for. It never means "persisted": a change + after the recheck read is not seen. +- ``REFUTED``: the record no longer shows the declared values, is gone, or + this caller's log entries show a mutation nothing accounts for (late + collateral, or an extra write to the record). +- ``NOT_CHECKED``: anything else. The recheck was early; the state is + malformed or doesn't match the receipt; the first check wasn't verified; a + read failed; the log didn't reach the checkpoint; another actor or an + unattributed entry changed the record; the version moved while the values + stayed (A to B to A); the log returned entries it didn't let us inspect. + +The local clock only decides when the recheck is due. Which log entries are +in the window is decided by the log's own checkpoint and entry ids, never by +comparing clocks: Medplum's server clock ran about 1.5 s off the client's. + +The recheck can only keep or lower the first result. It never turns a first +result that wasn't verified into ``VERIFIED``. + +Sources are adapters. :class:`VerifierReadback` wraps any verifier adapter on +main (REST, FHIR, GraphQL, SQL), so the read-back half works with what exists +today. The log half is the :class:`ActivityLog` protocol; a reader of a +system's audit or event log implements it with a thin wrapper. This module +imports nothing from ``tx`` or ``txplan``. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import secrets +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any, Literal, Optional, Protocol + +from openadapt_flow.runtime.effects.late_write import ( + LateOutcome, + due_at, + format_time, + seconds_until, +) + +#: The private recheck state's schema. +SCHEMA = "openadapt.api-recheck/v1" +#: Exactly these keys: nothing rides along unbound. +STATE_KEYS: tuple[str, ...] = ( + "schema_version", + "salt", + "target", + "first_outcome", + "read_at", + "window_s", + "due_at", + "fields_mac", + "version_mac", + "log", + "own_events", +) + +Outcome = Literal["VERIFIED", "REFUTED", "NOT_CHECKED"] +#: Who made a log entry, as the log adapter attributes it. +By = Literal["self", "other", "unknown"] +#: What the entry did. ``read`` entries are ignored; ``unknown`` never +#: confirms anything. +Kind = Literal["create", "update", "delete", "read", "unknown"] +Op = Literal["create", "update", "delete"] +_ALL_OPS: tuple[Op, ...] = ("create", "update", "delete") + +#: The coordinator's basis names this module can produce. +BASIS_API = "system_api" +BASIS_LOG = "activity_log" +#: Always listed: a read of the record and the log can't see these. +ALWAYS_NOT_COVERED: tuple[str, ...] = ( + "server-side async and outbound effects not observed", + "changes after the recheck read", +) + +#: The recheck outcome in the older vocabularies. +TO_LATE: dict[Outcome, LateOutcome] = { + "VERIFIED": "CONFIRMED", + "REFUTED": "REFUTED", + "NOT_CHECKED": "UNCERTAIN", +} +#: The ``effect.Verdict`` value of each outcome. +TO_VERDICT: dict[Outcome, str] = { + "VERIFIED": "confirmed", + "REFUTED": "refuted", + "NOT_CHECKED": "indeterminate", +} + + +class ReadFailed(RuntimeError): + """A source could not be read. Nothing is known about it.""" + + +# -- sources ------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Readback: + """One read of the record through the system's API. + + ``fields``: the declared fields as read (judged: a change refutes). + ``version``: anything that moves whenever the record changes (an ETag, + FHIR ``meta.versionId``, a digest of the whole record). A moved version + with unchanged fields is a change the fields don't show: never VERIFIED. + ``found``: False when the system answered that the record is not there. + """ + + found: bool + fields: Mapping[str, Any] = field(default_factory=dict) + version: Optional[str] = None + + +class RecordSource(Protocol): + """Reads the one record a write made or changed.""" + + def read(self) -> Readback: + """The record now; raises :class:`ReadFailed` when it can't be read.""" + ... + + +@dataclass(frozen=True) +class LogEntry: + """One entry of the system's own log, as the adapter normalized it.""" + + id: str + kind: Kind + by: By + #: Whether the entry names the checked record. + on_target: bool + + +@dataclass(frozen=True) +class LogRead: + """The entries after a checkpoint. + + ``reached``: the read got back to the checkpoint. A read that stopped + short (a page limit, a failed page) leaves the window open. + ``hidden``: entries the reader saw but did not return (for example + another caller's entries a reader filters out). Any hidden entry may + have touched the record, so it blocks VERIFIED. + ``logs``: the operations this log records. A kind it doesn't record + can't be seen, and the result lists it as not covered. + """ + + entries: Sequence[LogEntry] + reached: bool + hidden: int = 0 + logs: tuple[Op, ...] = _ALL_OPS + + +class ActivityLog(Protocol): + """A system's audit or event log, read by its own positions.""" + + def checkpoint(self) -> Mapping[str, Any]: + """An opaque, JSON-safe position: the newest entry ids or a stream + cursor. Raises :class:`ReadFailed` when the log can't be placed.""" + ... + + def since(self, checkpoint: Mapping[str, Any]) -> LogRead: + """Every entry after ``checkpoint``, newest first or in log order. + Raises :class:`ReadFailed` when the log can't be read.""" + ... + + +# -- digests ------------------------------------------------------------------- + + +def _canonical(value: Any) -> bytes: + return json.dumps( + value, sort_keys=True, separators=(",", ":"), default=str + ).encode() + + +def _mac(salt: bytes, label: str, value: Any) -> str: + return hmac.new( + salt, label.encode() + b"\0" + _canonical(value), hashlib.sha256 + ).hexdigest() + + +def state_sha256(state: Mapping[str, Any]) -> str: + """The digest a receipt binds: the whole private state, salt included.""" + + return "sha256:" + hashlib.sha256(_canonical(dict(state))).hexdigest() + + +# -- result -------------------------------------------------------------------- + + +@dataclass +class RecheckResult: + outcome: Outcome + reason: str + #: Plain fields for a receipt's evidence-scope block. + basis: list[str] + read_back_at: Optional[str] + rechecked_at: Optional[str] + recheck_window_s: Optional[float] + not_covered: list[str] + entries_after_checkpoint: int = 0 + other_actor_entries: int = 0 + + @property + def late_outcome(self) -> LateOutcome: + return TO_LATE[self.outcome] + + def scope(self) -> dict[str, Any]: + """The evidence-scope fields this recheck can state. Wire scope is + not this module's to state; a receipt adds it.""" + + return { + "check_level": "system_of_record" if self.outcome == "VERIFIED" else None, + "basis": self.basis[0] if self.basis else None, + "bases": list(self.basis), + "read_back_at": self.read_back_at, + "rechecked_at": self.rechecked_at, + "recheck_window_s": self.recheck_window_s, + "not_covered": list(self.not_covered), + } + + def to_json(self) -> dict[str, Any]: + return { + "outcome": self.outcome, + "reason": self.reason, + "entries_after_checkpoint": self.entries_after_checkpoint, + "other_actor_entries": self.other_actor_entries, + "scope": self.scope(), + } + + +def _not_checked( + reason: str, state: Optional[Mapping[str, Any]] = None, *, at: Optional[str] = None +) -> RecheckResult: + basis: list[str] = [] + if isinstance(state, Mapping): + basis = [BASIS_API] + ([BASIS_LOG] if state.get("log") is not None else []) + window = state.get("window_s") if isinstance(state, Mapping) else None + return RecheckResult( + "NOT_CHECKED", + reason, + basis=basis, + read_back_at=str(state.get("read_at")) if isinstance(state, Mapping) else None, + rechecked_at=at, + recheck_window_s=window if isinstance(window, (int, float)) else None, + not_covered=list(ALWAYS_NOT_COVERED), + ) + + +# -- begin --------------------------------------------------------------------- + + +def begin( + record: RecordSource, + *, + target: str, + first_outcome: str, + window_s: float, + log: Optional[ActivityLog] = None, + own_event_ids: Sequence[str] = (), + now: Optional[datetime] = None, +) -> dict[str, Any]: + """The private recheck state, taken right after the first check. + + ``target``: the record's reference (``Patient/123``); bound, never + re-read from the state. ``first_outcome``: the first check's outcome; a + recheck of anything but ``VERIFIED`` stays ``NOT_CHECKED``. + ``own_event_ids``: the write's own log entries, which the first check + already judged; they may land after the checkpoint while the log lags. + + The log checkpoint is taken before the read, so an entry between the two + reads shows up in the window rather than in the baseline. Raises + :class:`ReadFailed` when either source can't be read, and ``ValueError`` + for a window that isn't a positive number of seconds. + """ + + if ( + isinstance(window_s, bool) + or not isinstance(window_s, (int, float)) + or not window_s > 0 + or window_s == float("inf") + ): + raise ValueError("the recheck window must be a positive number of seconds") + salt = secrets.token_bytes(32) + checkpoint = None if log is None else dict(log.checkpoint()) + seen = record.read() + if not isinstance(seen, Readback): + raise ReadFailed("the record source returned no read-back") + read_at = format_time(now or datetime.now(timezone.utc)) + return { + "schema_version": SCHEMA, + "salt": salt.hex(), + "target": _mac(salt, "target", target), + "first_outcome": str(first_outcome), + "read_at": read_at, + "window_s": float(window_s), + "due_at": due_at(read_at, float(window_s)), + "fields_mac": _mac(salt, "fields", [seen.found, dict(seen.fields)]), + "version_mac": None + if seen.version is None + else _mac(salt, "version", seen.version), + "log": checkpoint, + "own_events": sorted({_mac(salt, "event", i) for i in own_event_ids}), + } + + +def schedule(state: Mapping[str, Any]) -> dict[str, Any]: + """The block a receipt carries: when the recheck is due and the state it + binds. No salt, no values.""" + + return { + "compares": "api_readback_and_log_since_checkpoint" + if state.get("log") is not None + else "api_readback", + "read_back_at": state["read_at"], + "recheck_window_s": state["window_s"], + "due_at": state["due_at"], + "state_sha256": state_sha256(state), + } + + +def state_problem(state: Any) -> Optional[str]: + """A plain sentence when ``state`` is not a recheck state's shape.""" + + if not isinstance(state, Mapping): + return "the recheck state is not a JSON object" + if state.get("schema_version") != SCHEMA: + return f"the recheck state is not an {SCHEMA} document" + if set(state) != set(STATE_KEYS): + return "the recheck state must hold exactly " + ", ".join(STATE_KEYS) + try: + if len(bytes.fromhex(str(state["salt"]))) != 32: + return "the recheck state's salt is not 32 bytes" + except ValueError: + return "the recheck state's salt is not hex" + try: + expected_due = due_at(str(state["read_at"]), float(state["window_s"])) + except (TypeError, ValueError): + return "the recheck state's read time or window is malformed" + if state["due_at"] != expected_due: + return "the recheck state's due time doesn't follow from its window" + if state["log"] is not None and not isinstance(state["log"], Mapping): + return "the recheck state's log checkpoint is not an object" + if not isinstance(state["own_events"], list): + return "the recheck state's own events are not a list" + return None + + +# -- recheck ------------------------------------------------------------------- + + +def recheck( + state: Mapping[str, Any], + record: RecordSource, + *, + target: str, + expected_state_sha256: str, + log: Optional[ActivityLog] = None, + excused_event_ids: Sequence[str] = (), + now: Optional[datetime] = None, +) -> RecheckResult: + """Read the record and the log again and judge what changed. + + ``expected_state_sha256``: from the receipt (:func:`schedule`), so a + state that was edited or swapped doesn't match. ``excused_event_ids``: + log entries of later declared writes by this caller that their own + checks account for (any outcome); they don't refute this write. + """ + + current = now or datetime.now(timezone.utc) + at = format_time(current) + problem = state_problem(state) + if problem is not None: + return _not_checked(problem, at=at) + if not hmac.compare_digest(state_sha256(state), str(expected_state_sha256)): + return _not_checked("the recheck state doesn't match its receipt", at=at) + salt = bytes.fromhex(str(state["salt"])) + if not hmac.compare_digest(_mac(salt, "target", target), str(state["target"])): + return _not_checked( + "the recheck state was taken for another record", state, at=at + ) + if state["first_outcome"] != "VERIFIED": + return _not_checked( + "the first check was not VERIFIED; a recheck can't raise it", state, at=at + ) + if seconds_until(str(state["due_at"]), current) > 0: + return _not_checked("the recheck is not due yet", state, at=at) + if (state["log"] is None) != (log is None): + return _not_checked( + "the log given doesn't match the log the state was taken with", state, at=at + ) + + # The record first, then the log: an entry between the two reads is in + # the log read, so a change can't slip between them. + try: + seen = record.read() + if not isinstance(seen, Readback): + raise ReadFailed("the record source returned no read-back") + except ReadFailed as exc: + return _not_checked(f"the record could not be read again: {exc}", state, at=at) + window: Optional[LogRead] = None + if log is not None: + try: + window = log.since(dict(state["log"])) + except ReadFailed as exc: + return _not_checked(f"the log could not be read: {exc}", state, at=at) + + basis = [BASIS_API] + ([BASIS_LOG] if window is not None else []) + not_covered = list(ALWAYS_NOT_COVERED) + if window is None: + not_covered.append("changes reverted between the two reads (no log read)") + else: + missing = [op for op in _ALL_OPS if op not in window.logs] + if missing: + not_covered.append("log does not record: " + ", ".join(missing)) + + def result(outcome: Outcome, reason: str) -> RecheckResult: + return RecheckResult( + outcome, + reason, + basis=basis, + read_back_at=str(state["read_at"]), + rechecked_at=at, + recheck_window_s=float(state["window_s"]), + not_covered=not_covered, + entries_after_checkpoint=len(window.entries) if window else 0, + other_actor_entries=sum(1 for e in window.entries if e.by == "other") + if window + else 0, + ) + + # What the log says, when there is one. + other_on_target = unknown_on_target = self_on_target = False + self_elsewhere = unknown_elsewhere = False + if window is not None: + own = set(state["own_events"]) + excused = {_mac(salt, "event", i) for i in excused_event_ids} + for entry in window.entries: + if entry.kind == "read": + continue + h = _mac(salt, "event", entry.id) + if h in own: + continue # the write's own entry, judged by the first check + if entry.on_target: + if entry.by == "other": + other_on_target = True + elif ( + entry.by == "self" and entry.kind != "unknown" and h not in excused + ): + self_on_target = True + elif h not in excused: + unknown_on_target = True + elif entry.by == "self" and h not in excused: + if entry.kind == "unknown": + unknown_elsewhere = True + else: + self_elsewhere = True + elif entry.by == "unknown" and h not in excused: + unknown_elsewhere = True + + fields_now = _mac(salt, "fields", [seen.found, dict(seen.fields)]) + fields_held = hmac.compare_digest(fields_now, str(state["fields_mac"])) + if not fields_held: + if other_on_target: + return result( + "NOT_CHECKED", + "the record changed since the first read, and the log attributes " + "a change to another actor", + ) + if not seen.found: + return result("REFUTED", "the record is gone since the first read") + return result( + "REFUTED", "the record no longer shows the values the first read showed" + ) + if self_on_target: + return result( + "REFUTED", + "the log shows another write to the record by this caller that " + "nothing declared accounts for", + ) + if self_elsewhere: + return result( + "REFUTED", + "the log shows a change by this caller to another record that " + "nothing declared accounts for", + ) + if window is not None and not window.reached: + return result("NOT_CHECKED", "the log read did not reach the checkpoint") + if window is not None and window.hidden: + return result( + "NOT_CHECKED", + f"the log returned {window.hidden} entries that could not be inspected", + ) + if other_on_target: + return result( + "NOT_CHECKED", + "another actor changed the record since the first read; the values " + "match, but the change was not this write's", + ) + if unknown_on_target or unknown_elsewhere: + return result( + "NOT_CHECKED", "the log holds entries whose author or kind is unknown" + ) + version_now = None if seen.version is None else _mac(salt, "version", seen.version) + if version_now != state["version_mac"]: + return result( + "NOT_CHECKED", + "the record's version moved while its declared values stayed the same", + ) + return result( + "VERIFIED", + f"as of {at}, the read-back showed the values the first read showed" + + ( + ", and the log since the checkpoint shows no unexplained change" + if window is not None + else "" + ), + ) + + +# -- adapters ------------------------------------------------------------------ + + +def _dotted(record: Any, path: str) -> Any: + current = record + for part in path.split("."): + if not isinstance(current, Mapping) or part not in current: + return None + current = current[part] + return current + + +class VerifierReadback: + """A :class:`RecordSource` over any verifier adapter on main. + + Each read runs ``verifier.verify(effect, before)`` against the pre-write + baseline, as the first check did. CONFIRMED with exactly one matched + record gives that record's ``fields`` (default: the effect's match + keys); REFUTED gives ``found=False``; anything else fails the read. + + ``version_path`` names a server version (``meta.versionId``); without + it, the version is a digest of the whole matched record minus + ``ignore`` (volatile fields such as ``meta.lastUpdated`` belong there + only when the server rewrites them without a change). + """ + + def __init__( + self, + verifier: Any, + effect: Any, + before: Any, + *, + fields: Optional[Sequence[str]] = None, + version_path: Optional[str] = None, + ignore: Sequence[str] = (), + context: Any = None, + ) -> None: + self.verifier = verifier + self.effect = effect + self.before = before + self.fields = tuple(fields) if fields is not None else tuple(effect.match) + self.version_path = version_path + self.ignore = tuple(ignore) + self.context = context + + def read(self) -> Readback: + try: + verdict = self.verifier.verify(self.effect, self.before, self.context) + except Exception as exc: # noqa: BLE001 - any failure is an unread record + raise ReadFailed(type(exc).__name__) from exc + status = getattr(getattr(verdict, "verdict", None), "value", None) + if status == "refuted": + return Readback(found=False) + records = list(getattr(verdict, "matched_records", []) or []) + if status != "confirmed" or len(records) != 1: + raise ReadFailed( + getattr(verdict, "reason", "") or "the read was not conclusive" + ) + rec = records[0] + if self.version_path: + raw = _dotted(rec, self.version_path) + version = None if raw is None else str(raw) + else: + trimmed = json.loads(_canonical(rec)) + for path in self.ignore: + parts = path.split(".") + holder = ( + _dotted(trimmed, ".".join(parts[:-1])) if parts[:-1] else trimmed + ) + if isinstance(holder, dict): + holder.pop(parts[-1], None) + version = hashlib.sha256(_canonical(trimmed)).hexdigest() + return Readback( + found=True, + fields={f: _dotted(rec, f) for f in self.fields}, + version=version, + ) + + +__all__ = [ + "ALWAYS_NOT_COVERED", + "ActivityLog", + "BASIS_API", + "BASIS_LOG", + "LogEntry", + "LogRead", + "Outcome", + "ReadFailed", + "Readback", + "RecheckResult", + "RecordSource", + "SCHEMA", + "TO_LATE", + "TO_VERDICT", + "VerifierReadback", + "begin", + "recheck", + "schedule", + "state_problem", + "state_sha256", +] diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py new file mode 100644 index 0000000000..d0aa9d3a16 --- /dev/null +++ b/packages/flow/tests/test_api_recheck.py @@ -0,0 +1,419 @@ +"""The delayed recheck of an API read-back and the system's own log. + +Each test states the change that happened between the first read and the +recheck, and the outcome a receipt may carry for it. A change never yields +VERIFIED. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from datetime import datetime, timedelta, timezone +from typing import Any, Optional + +import pytest + +from openadapt_flow.runtime.effects.api_recheck import ( + ALWAYS_NOT_COVERED, + LogEntry, + LogRead, + Readback, + ReadFailed, + VerifierReadback, + begin, + recheck, + schedule, + state_problem, +) + +T0 = datetime(2026, 11, 21, 12, 0, 0, tzinfo=timezone.utc) +TARGET = "Patient/7" + + +class Record: + """A record the tests change between the two reads.""" + + def __init__(self, fields: Mapping[str, Any], version: Optional[str] = "1") -> None: + self.fields = dict(fields) + self.version = version + self.found = True + self.fail = False + + def read(self) -> Readback: + if self.fail: + raise ReadFailed("503") + if not self.found: + return Readback(found=False) + return Readback(found=True, fields=dict(self.fields), version=self.version) + + +class Log: + """A log placed by entry ids. ``stamp`` is the server's time, kept to + show that the window never depends on it.""" + + def __init__(self) -> None: + self.entries: list[dict[str, Any]] = [ + {"id": "e1", "kind": "create", "by": "self", "on": True, "stamp": 0.0} + ] + self.reach = True + self.hidden = 0 + self.logs: tuple[Any, ...] = ("create", "update", "delete") + self.fail = False + + def add(self, id: str, kind: str, by: str, on: bool, stamp: float = 0.0) -> None: + self.entries.append( + {"id": id, "kind": kind, "by": by, "on": on, "stamp": stamp} + ) + + def checkpoint(self) -> Mapping[str, Any]: + if self.fail: + raise ReadFailed("log down") + return {"ids": [e["id"] for e in self.entries]} + + def since(self, checkpoint: Mapping[str, Any]) -> LogRead: + if self.fail: + raise ReadFailed("log down") + old = set(checkpoint["ids"]) + new = [ + LogEntry(e["id"], e["kind"], e["by"], e["on"]) + for e in self.entries + if e["id"] not in old + ] + return LogRead(new, reached=self.reach, hidden=self.hidden, logs=self.logs) + + +def _setup(log: Optional[Log] = None, **kw: Any): + rec = Record({"name.family": "Lovelace", "birthDate": "1815-12-10"}) + state = begin( + rec, + target=TARGET, + first_outcome=kw.pop("first_outcome", "VERIFIED"), + window_s=kw.pop("window_s", 120), + log=log, + now=T0, + **kw, + ) + return rec, state, schedule(state) + + +def _run(state, rec, sched, log=None, *, after_s: float = 200, **kw: Any): + return recheck( + state, + rec, + target=kw.pop("target", TARGET), + expected_state_sha256=kw.pop("sha", sched["state_sha256"]), + log=log, + now=T0 + timedelta(seconds=after_s), + **kw, + ) + + +def test_unchanged_record_and_quiet_log_verify_as_of_the_recheck() -> None: + log = Log() + rec, state, sched = _setup(log) + log.add("x1", "update", "other", False) # someone else's record: ignored + log.add("r1", "read", "self", True) # reads change nothing + out = _run(state, rec, sched, log) + assert out.outcome == "VERIFIED" + assert out.late_outcome == "CONFIRMED" + scope = out.scope() + assert scope["basis"] == "system_api" and scope["bases"] == [ + "system_api", + "activity_log", + ] + assert scope["check_level"] == "system_of_record" + assert scope["read_back_at"] == "2026-11-21T12:00:00Z" + assert scope["rechecked_at"] == "2026-11-21T12:03:20Z" + assert scope["recheck_window_s"] == 120.0 + for line in ALWAYS_NOT_COVERED: + assert line in scope["not_covered"] + assert "persist" not in out.reason + + +def test_state_and_schedule_hold_no_values() -> None: + _, state, sched = _setup(Log()) + text = json.dumps(state) + json.dumps(sched) + assert "Lovelace" not in text and "1815" not in text and TARGET not in text + assert "salt" not in sched and state_problem(state) is None + + +def test_recheck_before_the_due_time_is_not_checked() -> None: + rec, state, sched = _setup(Log()) + assert sched["due_at"] == "2026-11-21T12:02:01Z" + out = _run(state, rec, sched, Log(), after_s=120) + assert out.outcome == "NOT_CHECKED" and "not due" in out.reason + + +def test_changed_value_refutes() -> None: + log = Log() + rec, state, sched = _setup(log) + rec.fields["birthDate"] = "1815-12-11" + rec.version = "2" + assert _run(state, rec, sched, log).outcome == "REFUTED" + + +def test_record_gone_refutes() -> None: + rec, state, sched = _setup() + rec.found = False + out = _run(state, rec, sched) + assert out.outcome == "REFUTED" and "gone" in out.reason + + +def test_changed_value_by_another_actor_is_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + rec.fields["birthDate"] = "1815-12-11" + log.add("c1", "update", "other", True) + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + +def test_a_to_b_to_a_is_never_verified() -> None: + """Values back where they were, but the version moved.""" + + rec, state, sched = _setup() + rec.version = "3" + out = _run(state, rec, sched) + assert out.outcome == "NOT_CHECKED" and "version" in out.reason + + +def test_a_to_b_to_a_with_no_version_is_caught_by_the_log() -> None: + log = Log() + rec = Record({"birthDate": "1815-12-10"}, version=None) + state = begin( + rec, target=TARGET, first_outcome="VERIFIED", window_s=60, log=log, now=T0 + ) + log.add("u2", "update", "other", True) + log.add("u3", "update", "other", True) + out = recheck( + state, + rec, + target=TARGET, + expected_state_sha256=schedule(state)["state_sha256"], + log=log, + now=T0 + timedelta(seconds=90), + ) + assert out.outcome == "NOT_CHECKED" + + +def test_own_extra_write_to_the_record_refutes() -> None: + log = Log() + rec, state, sched = _setup(log) + log.add("u9", "update", "self", True) + assert _run(state, rec, sched, log).outcome == "REFUTED" + + +def test_own_late_collateral_refutes_unless_a_later_write_accounts_for_it() -> None: + log = Log() + rec, state, sched = _setup(log) + log.add("d1", "delete", "self", False) + assert _run(state, rec, sched, log).outcome == "REFUTED" + assert _run(state, rec, sched, log, excused_event_ids=["d1"]).outcome == "VERIFIED" + + +def test_the_writes_own_lagging_entry_is_not_a_change() -> None: + log = Log() + log.entries = [] + rec, state, sched = _setup(log, own_event_ids=["mine"]) + log.add("mine", "create", "self", True) + assert _run(state, rec, sched, log).outcome == "VERIFIED" + + +def test_entry_stamped_before_the_checkpoint_is_still_in_the_window() -> None: + """A server clock 1.5 s behind stamps a new entry before the checkpoint's + newest entry. Its id is new, so it is in the window.""" + + log = Log() + log.entries[0]["stamp"] = 1000.0 + rec, state, sched = _setup(log) + log.add("late", "update", "self", False, stamp=998.5) + assert _run(state, rec, sched, log).outcome == "REFUTED" + + +def test_out_of_order_stamps_do_not_hide_an_entry() -> None: + log = Log() + rec, state, sched = _setup(log) + log.add("b", "update", "other", False, stamp=50.0) + log.add("a", "update", "unknown", True, stamp=10.0) + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + +def test_log_that_did_not_reach_the_checkpoint_is_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + log.reach = False + out = _run(state, rec, sched, log) + assert out.outcome == "NOT_CHECKED" and "checkpoint" in out.reason + + +def test_hidden_entries_are_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + log.hidden = 3 + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + +def test_unknown_kind_on_the_record_is_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + log.add("q", "unknown", "self", True) + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + +def test_read_failures_are_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + rec.fail = True + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + rec.fail = False + log.fail = True + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + +def test_missing_log_when_state_has_one_is_not_checked() -> None: + rec, state, sched = _setup(Log()) + assert _run(state, rec, sched, None).outcome == "NOT_CHECKED" + + +def test_no_log_still_verifies_but_says_what_it_did_not_cover() -> None: + rec, state, sched = _setup() + out = _run(state, rec, sched) + assert out.outcome == "VERIFIED" and out.scope()["bases"] == ["system_api"] + assert any("no log read" in line for line in out.not_covered) + + +def test_log_that_does_not_record_updates_says_so() -> None: + log = Log() + rec, state, sched = _setup(log) + log.logs = ("create", "delete") + out = _run(state, rec, sched, log) + assert any("update" in line for line in out.not_covered) + + +def test_first_result_that_was_not_verified_is_never_raised() -> None: + rec, state, sched = _setup(first_outcome="SHOWN") + out = _run(state, rec, sched) + assert out.outcome == "NOT_CHECKED" + + +@pytest.mark.parametrize( + "edit", + [ + lambda s: s.update(first_outcome="VERIFIED", window_s=1.0), + lambda s: s.update(due_at="2026-11-21T12:00:01Z"), + lambda s: s.update(fields_mac="0" * 64), + lambda s: s.update(extra=1), + lambda s: s.pop("log"), + ], +) +def test_tampered_state_is_not_checked(edit: Any) -> None: + rec, state, sched = _setup(first_outcome="VERIFIED") + edit(state) + assert _run(state, rec, sched).outcome == "NOT_CHECKED" + + +def test_tampered_first_outcome_does_not_match_the_receipt() -> None: + rec, state, sched = _setup(first_outcome="SHOWN") + state["first_outcome"] = "VERIFIED" + out = _run(state, rec, sched) + assert out.outcome == "NOT_CHECKED" and "receipt" in out.reason + + +def test_state_for_another_record_is_not_checked() -> None: + rec, state, sched = _setup() + assert _run(state, rec, sched, target="Patient/8").outcome == "NOT_CHECKED" + + +@pytest.mark.parametrize("window", [0, -1, float("nan"), float("inf"), True]) +def test_window_must_be_positive_seconds(window: Any) -> None: + with pytest.raises(ValueError): + begin(Record({}), target=TARGET, first_outcome="VERIFIED", window_s=window) + + +def test_begin_fails_loud_when_a_source_cannot_be_read() -> None: + log = Log() + log.fail = True + with pytest.raises(ReadFailed): + begin(Record({}), target=TARGET, first_outcome="VERIFIED", window_s=5, log=log) + + +# -- over real HTTP: the REST verifier on main against MockMed ------------------ + + +def test_rest_readback_over_http_verifies_then_refutes_a_late_edit() -> None: + from openadapt_flow.mockmed.fault_server import serve + from openadapt_flow.runtime.effects.effect import Effect, EffectKind + from openadapt_flow.runtime.effects.rest import RestRecordVerifier + from tests._rest_read_contract_fixtures import mockmed_rest_read_kwargs + + base_url, db, stop = serve() + try: + verifier = RestRecordVerifier(base_url, **mockmed_rest_read_kwargs()) + before = verifier.capture_pre_state() + written = db.add("p1", "Triage", "BP 120/80", key="k1") + effect = Effect( + kind=EffectKind.RECORD_WRITTEN, + match={"patient_id": "p1", "type": "Triage", "note": "BP 120/80"}, + expected_count=1, + timeout_s=1.0, + ) + source = VerifierReadback( + verifier, effect, before, fields=["patient_id", "note"] + ) + state = begin( + source, target="encounter/1", first_outcome="VERIFIED", window_s=1, now=T0 + ) + sha = schedule(state)["state_sha256"] + later = T0 + timedelta(seconds=5) + ok = recheck( + state, source, target="encounter/1", expected_state_sha256=sha, now=later + ) + assert ok.outcome == "VERIFIED", ok.reason + + # A background job rewrites the note after the first check. + with db._lock: + written["note"] = "BP 180/110" + bad = recheck( + state, source, target="encounter/1", expected_state_sha256=sha, now=later + ) + assert bad.outcome == "REFUTED", bad.reason + finally: + stop() + + +def test_rest_readback_over_http_catches_an_undeclared_field_change() -> None: + """A field the check doesn't declare moved: the whole-record version + moved, so the recheck is not VERIFIED.""" + + from openadapt_flow.mockmed.fault_server import serve + from openadapt_flow.runtime.effects.effect import Effect, EffectKind + from openadapt_flow.runtime.effects.rest import RestRecordVerifier + from tests._rest_read_contract_fixtures import mockmed_rest_read_kwargs + + base_url, db, stop = serve() + try: + verifier = RestRecordVerifier(base_url, **mockmed_rest_read_kwargs()) + before = verifier.capture_pre_state() + written = db.add("p1", "Triage", "BP 120/80", key="k1") + effect = Effect( + kind=EffectKind.RECORD_WRITTEN, + match={"patient_id": "p1", "note": "BP 120/80"}, + expected_count=1, + timeout_s=1.0, + ) + source = VerifierReadback(verifier, effect, before) + state = begin( + source, target="encounter/1", first_outcome="VERIFIED", window_s=1, now=T0 + ) + with db._lock: + written["type"] = "Consult" + out = recheck( + state, + source, + target="encounter/1", + expected_state_sha256=schedule(state)["state_sha256"], + now=T0 + timedelta(seconds=5), + ) + assert out.outcome == "NOT_CHECKED", out.reason + finally: + stop() From e74e09a0404b9a8c878bd9881041c9f140f30b5d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:30:03 -0500 Subject: [PATCH 2/9] docs(capabilities): link the API recheck row to its PR --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7e79d72b71..3f257da00b 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -182,7 +182,7 @@ improvising or retrying when something is off. | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | -| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main (PRLINK) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | +| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main ([#2472](https://github.com/OpenAdaptAI/OpenAdapt/pull/2472)) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | diff --git a/llms-full.txt b/llms-full.txt index c132605cc8..080610a929 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -616,7 +616,7 @@ improvising or retrying when something is off. | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | -| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | In review | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | +| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main ([#2472](https://github.com/OpenAdaptAI/OpenAdapt/pull/2472)) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | From 46b92745061865f19edc766ba4edf9128781a904 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:55:26 -0500 Subject: [PATCH 3/9] fix(verify): accept only independent API verifiers for the recheck read-back A screen read-back or a database verifier can't carry the system_api basis, and a named version path that resolves to nothing now fails the read instead of silently dropping the A to B to A check. --- .../runtime/effects/api_recheck.py | 38 +++++++++-- packages/flow/tests/test_api_recheck.py | 65 ++++++++++++++++++- 2 files changed, 97 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index c90577667c..7d05f4289d 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -38,8 +38,8 @@ The recheck can only keep or lower the first result. It never turns a first result that wasn't verified into ``VERIFIED``. -Sources are adapters. :class:`VerifierReadback` wraps any verifier adapter on -main (REST, FHIR, GraphQL, SQL), so the read-back half works with what exists +Sources are adapters. :class:`VerifierReadback` wraps a REST, FHIR or GraphQL +verifier on main, so the read-back half works with what exists today. The log half is the :class:`ActivityLog` protocol; a reader of a system's audit or event log implements it with a thin wrapper. This module imports nothing from ``tx`` or ``txplan``. @@ -91,6 +91,8 @@ #: The coordinator's basis names this module can produce. BASIS_API = "system_api" +#: The verifier substrates whose read goes through the system's API. +API_SUBSTRATES = frozenset({"rest", "fhir", "graphql"}) BASIS_LOG = "activity_log" #: Always listed: a read of the record and the log can't see these. ALWAYS_NOT_COVERED: tuple[str, ...] = ( @@ -491,7 +493,10 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: "a change to another actor", ) if not seen.found: - return result("REFUTED", "the record is gone since the first read") + return result( + "REFUTED", + "no single record shows the declared values since the first read", + ) return result( "REFUTED", "the record no longer shows the values the first read showed" ) @@ -554,7 +559,13 @@ def _dotted(record: Any, path: str) -> Any: class VerifierReadback: - """A :class:`RecordSource` over any verifier adapter on main. + """A :class:`RecordSource` over a REST, FHIR or GraphQL verifier on main. + + Only an independent, system-of-record verifier is accepted: a screen + read-back or a database read is not an API read-back, so it can't carry + the ``system_api`` basis. Rebuilding this source at recheck time needs + the pre-write ``EffectState``, which holds the records as read; only the + recheck state is free of values. Each read runs ``verifier.verify(effect, before)`` against the pre-write baseline, as the first check did. CONFIRMED with exactly one matched @@ -585,6 +596,18 @@ def __init__( self.version_path = version_path self.ignore = tuple(ignore) self.context = context + substrate = str(getattr(verifier, "substrate", "")) + if substrate not in API_SUBSTRATES: + raise ValueError( + f"a {substrate or 'unnamed'} verifier is not an API read-back" + ) + tier_of = getattr(verifier, "verification_tier_for", None) + tier = tier_of(effect) if callable(tier_of) else verifier.verification_tier + if ( + getattr(verifier, "independent_system_of_record", False) is not True + or int(tier) != 1 + ): + raise ValueError("the verifier does not read the system of record") def read(self) -> Readback: try: @@ -602,7 +625,11 @@ def read(self) -> Readback: rec = records[0] if self.version_path: raw = _dotted(rec, self.version_path) - version = None if raw is None else str(raw) + if raw is None: + # A named version that isn't there would silently drop the + # check that catches A to B to A. + raise ReadFailed(f"the record has no {self.version_path}") + version = str(raw) else: trimmed = json.loads(_canonical(rec)) for path in self.ignore: @@ -623,6 +650,7 @@ def read(self) -> Readback: __all__ = [ "ALWAYS_NOT_COVERED", "ActivityLog", + "API_SUBSTRATES", "BASIS_API", "BASIS_LOG", "LogEntry", diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index d0aa9d3a16..78aad2259b 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -157,7 +157,7 @@ def test_record_gone_refutes() -> None: rec, state, sched = _setup() rec.found = False out = _run(state, rec, sched) - assert out.outcome == "REFUTED" and "gone" in out.reason + assert out.outcome == "REFUTED" and "no single record" in out.reason def test_changed_value_by_another_actor_is_not_checked() -> None: @@ -417,3 +417,66 @@ def test_rest_readback_over_http_catches_an_undeclared_field_change() -> None: assert out.outcome == "NOT_CHECKED", out.reason finally: stop() + + +def test_state_survives_a_json_round_trip() -> None: + log = Log() + rec, state, sched = _setup(log) + stored = json.loads(json.dumps(state)) + assert _run(stored, rec, sched, log).outcome == "VERIFIED" + + +class _Verdict: + def __init__(self, status: str, records: list[dict[str, Any]]) -> None: + self.verdict = type("V", (), {"value": status})() + self.matched_records = records + self.reason = "" + + +class _Verifier: + substrate = "fhir" + verification_tier = 1 + independent_system_of_record = True + + def __init__(self) -> None: + self.record: dict[str, Any] = {"id": "7", "meta": {"versionId": "1"}} + + def verify(self, effect: Any, before: Any, context: Any = None) -> _Verdict: + return _Verdict("confirmed", [dict(self.record)]) + + +class _Effect: + match = {"id": "7"} + + +@pytest.mark.parametrize( + "change", + [ + {"independent_system_of_record": False}, + {"verification_tier": 2}, + {"substrate": "sql"}, + {"substrate": "onscreen"}, + ], +) +def test_only_an_independent_api_verifier_is_a_readback(change: dict[str, Any]) -> None: + verifier = _Verifier() + for name, value in change.items(): + setattr(verifier, name, value) + with pytest.raises(ValueError): + VerifierReadback(verifier, _Effect(), None) + + +def test_screen_tier_for_this_effect_is_refused() -> None: + verifier = _Verifier() + verifier.verification_tier_for = lambda effect: 4 # type: ignore[attr-defined] + with pytest.raises(ValueError): + VerifierReadback(verifier, _Effect(), None) + + +def test_missing_named_version_fails_the_read() -> None: + verifier = _Verifier() + source = VerifierReadback(verifier, _Effect(), None, version_path="meta.versionId") + assert source.read().version == "1" + verifier.record = {"id": "7"} + with pytest.raises(ReadFailed): + source.read() From 5cd4111110aa19636e5924884ad824ae958c47bc Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:21:49 -0500 Subject: [PATCH 4/9] fix(verify): close the recheck's fail-open paths from the Codex review - begin refuses an absent record or one with no identity; the state binds a MAC of the record's identity, so a selector that moves to another record is NOT_CHECKED. - MACs are keyed by the salt and the host frame secret (db_snapshot mac_key), with a key check, so the state alone can't be tested against guessed values. - Values are compared as exact JSON: a missing field fails the read, 1 and "1" differ, and a type with no JSON form fails the read. - VerifierReadback refuses redacting verifiers and FHIR/GraphQL without a named version; an ambiguous or record-naming refutation fails the read; read-failure reasons are fixed sentences. - Exemptions are {id: operation} maps and apply only to entries the log attributes to this caller with that operation; a contradiction is NOT_CHECKED. - Proven caller mutations are judged first; a changed value with an unknown, hidden or other actor on the record is NOT_CHECKED. - A log that records nothing gives no activity_log basis; without a log the result lists this caller's other changes as not covered. - state_problem validates types, bounds and digests; schedule refuses a malformed state; the result reports the observation interval. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../runtime/effects/api_recheck.py | 554 +++++++++++++----- packages/flow/tests/test_api_recheck.py | 259 +++++++- 4 files changed, 664 insertions(+), 153 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 3f257da00b..eb165198c8 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -182,7 +182,7 @@ improvising or retrying when something is off. | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | -| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main ([#2472](https://github.com/OpenAdaptAI/OpenAdapt/pull/2472)) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | +| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (a REST, FHIR or GraphQL verifier, through `VerifierReadback`; FHIR and GraphQL need a named server version, and a redacting verifier is refused), keeping only MACs of the record's identity, declared fields and version, keyed by the salt and this host's frame secret. At or after the due time it reads both again. `VERIFIED` means only that, between the start and end of the recheck, the read-back showed the same record and values and, when a log was read, the log since the checkpoint showed no unexplained change. Without a log the basis is the API read-back alone, and the result lists this caller's changes to other records as not covered. This caller's own unexplained entry in the log is `REFUTED`, and so is a changed or deleted record that the log doesn't attribute to another or an unknown actor. These are `NOT_CHECKED`: another actor's or an unknown entry's change; a read-back that lands on a different record or matches more than one; an exempted entry whose author or operation disagrees; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main ([#2472](https://github.com/OpenAdaptAI/OpenAdapt/pull/2472)) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | diff --git a/llms-full.txt b/llms-full.txt index 080610a929..102d73c399 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -616,7 +616,7 @@ improvising or retrying when something is off. | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | -| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (any verifier adapter, through `VerifierReadback`), keeping only keyed MACs of the declared fields and the record's version. At or after the due time it reads both again. `VERIFIED` means only that, as of the recheck time, the read-back showed the same values and the log since the checkpoint showed no unexplained change. A changed or deleted record, or this caller's own unexplained entry in the log, is `REFUTED`. These are `NOT_CHECKED`: another actor's change; an unknown entry; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main ([#2472](https://github.com/OpenAdaptAI/OpenAdapt/pull/2472)) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | +| Recheck a write to a system with no database access, after a window the caller sets: `runtime/effects/api_recheck.py` takes the system's log checkpoint, then reads the record through its API (a REST, FHIR or GraphQL verifier, through `VerifierReadback`; FHIR and GraphQL need a named server version, and a redacting verifier is refused), keeping only MACs of the record's identity, declared fields and version, keyed by the salt and this host's frame secret. At or after the due time it reads both again. `VERIFIED` means only that, between the start and end of the recheck, the read-back showed the same record and values and, when a log was read, the log since the checkpoint showed no unexplained change. Without a log the basis is the API read-back alone, and the result lists this caller's changes to other records as not covered. This caller's own unexplained entry in the log is `REFUTED`, and so is a changed or deleted record that the log doesn't attribute to another or an unknown actor. These are `NOT_CHECKED`: another actor's or an unknown entry's change; a read-back that lands on a different record or matches more than one; an exempted entry whose author or operation disagrees; a version that moved while the values stayed the same; a log read that didn't reach the checkpoint; a state that doesn't match its receipt; an early recheck; and a first result that wasn't verified. Entry ids decide what is in the window, never clock times. Every result lists what it didn't cover, including server-side async and outbound effects. Not yet: the log reader (the activity log adapter is a protocol; a reader for a system's own audit or event log is not on main), the receipt field, and an MCP tool | On main ([#2472](https://github.com/OpenAdaptAI/OpenAdapt/pull/2472)) | Synthetic (scripted log and record; MockMed's REST server over real HTTP: a late note edit refuted, a change to an undeclared field not checked) | `openadapt_flow/runtime/effects/api_recheck.py` | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index 7d05f4289d..04ec408372 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -10,26 +10,37 @@ ``begin`` runs right after a verified first check. It takes a log checkpoint, then reads the record, in that order, so nothing the log records can fall between the two reads unseen. It keeps a private state: a salt, keyed MACs of -the declared fields and of the record's version (never the values), the -log's opaque checkpoint, and keyed MACs of the write's own events. The +the record's identity, its declared fields and its version (never the +values), the log's checkpoint, and keyed MACs of the write's own events. The +MAC key is the salt keyed by this host's frame secret (the one +``db_snapshot`` uses), so the state alone can't be tested against guessed +values, and only a host holding that secret can recheck it. The checkpoint is +stored as the log adapter gives it: an adapter must return log positions +(entry ids, a stream cursor), never record values or identifiers. The receipt carries only ``state_sha256`` and the due time. ``recheck`` runs at or after the due time. It reads the record again, reads the log from the checkpoint and judges: -- ``VERIFIED``: as of the recheck time, the read-back showed the same - declared values and version, and the log, read back to the checkpoint, - holds no mutation of the record and no mutation by this caller that no - later declared write accounts for. It never means "persisted": a change - after the recheck read is not seen. -- ``REFUTED``: the record no longer shows the declared values, is gone, or - this caller's log entries show a mutation nothing accounts for (late - collateral, or an extra write to the record). +- ``VERIFIED``: between the start and the end of the recheck, the read-back + showed the same record with the same declared values and version. When a + log was read, the log since the checkpoint also holds no mutation of the + record and no mutation by this caller that no later declared write + accounts for. Without a log, the basis is the API read-back alone and the + result lists this caller's changes to other records as not covered. It + never means "persisted": a change after the recheck read is not seen. +- ``REFUTED``: the log shows this caller made a mutation nothing accounts + for (late collateral, or an extra write to the record), or the record no + longer shows the declared values (or is gone) and nothing in the log + attributes that change to another or an unknown actor. - ``NOT_CHECKED``: anything else. The recheck was early; the state is - malformed or doesn't match the receipt; the first check wasn't verified; a - read failed; the log didn't reach the checkpoint; another actor or an - unattributed entry changed the record; the version moved while the values - stayed (A to B to A); the log returned entries it didn't let us inspect. + malformed or doesn't match the receipt or this host; the first check + wasn't verified; a read failed or was ambiguous; the read-back shows a + different record; the log didn't reach the checkpoint; another actor or + an unattributed entry changed the record; an exempted entry's attribution + contradicts the write it was exempted for; the version moved while the + values stayed (A to B to A); the log returned entries it didn't let us + inspect. The local clock only decides when the recheck is due. Which log entries are in the window is decided by the log's own checkpoint and entry ids, never by @@ -50,6 +61,8 @@ import hashlib import hmac import json +import math +import re import secrets from collections.abc import Mapping, Sequence from dataclasses import dataclass, field @@ -64,21 +77,25 @@ ) #: The private recheck state's schema. -SCHEMA = "openadapt.api-recheck/v1" +SCHEMA = "openadapt.api-recheck/v2" #: Exactly these keys: nothing rides along unbound. STATE_KEYS: tuple[str, ...] = ( "schema_version", "salt", + "key_check", "target", "first_outcome", "read_at", "window_s", "due_at", + "identity_mac", "fields_mac", "version_mac", "log", "own_events", ) +#: The longest recheck window a state may carry (one year). +MAX_WINDOW_S = 366 * 24 * 3600.0 Outcome = Literal["VERIFIED", "REFUTED", "NOT_CHECKED"] #: Who made a log entry, as the log adapter attributes it. @@ -93,12 +110,20 @@ BASIS_API = "system_api" #: The verifier substrates whose read goes through the system's API. API_SUBSTRATES = frozenset({"rest", "fhir", "graphql"}) +#: Substrates whose records are a projection: only a named server version +#: can stand for the whole record. +_PROJECTED_SUBSTRATES = frozenset({"fhir", "graphql"}) BASIS_LOG = "activity_log" #: Always listed: a read of the record and the log can't see these. ALWAYS_NOT_COVERED: tuple[str, ...] = ( "server-side async and outbound effects not observed", "changes after the recheck read", ) +#: Listed when no log (or a log that records nothing) was read. +NO_LOG_NOT_COVERED: tuple[str, ...] = ( + "changes reverted between the two reads (no log read)", + "this caller's changes to other records (no log read)", +) #: The recheck outcome in the older vocabularies. TO_LATE: dict[Outcome, LateOutcome] = { @@ -113,9 +138,15 @@ "NOT_CHECKED": "indeterminate", } +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") + class ReadFailed(RuntimeError): - """A source could not be read. Nothing is known about it.""" + """A source could not be read. Nothing is known about it. + + Messages are fixed sentences: they never carry a URL, a record value or + an upstream error text, because a recheck result is serialized.""" # -- sources ------------------------------------------------------------------- @@ -125,16 +156,24 @@ class ReadFailed(RuntimeError): class Readback: """One read of the record through the system's API. + ``identity``: the record's own id as the read showed it (required when + ``found``): a read that lands on another record is never a match. ``fields``: the declared fields as read (judged: a change refutes). ``version``: anything that moves whenever the record changes (an ETag, - FHIR ``meta.versionId``, a digest of the whole record). A moved version - with unchanged fields is a change the fields don't show: never VERIFIED. - ``found``: False when the system answered that the record is not there. + FHIR ``meta.versionId``, a digest of the whole record), compared with + its JSON type. A moved version with unchanged fields is a change the + fields don't show: never VERIFIED. + ``found``: False when the system answered that no record matches. + + Values must be JSON values (``None``, ``bool``, ``int``, finite + ``float``, ``str``, lists and string-keyed objects of these); anything + else fails the read rather than being compared through ``str()``. """ found: bool fields: Mapping[str, Any] = field(default_factory=dict) - version: Optional[str] = None + version: Any = None + identity: Any = None class RecordSource(Protocol): @@ -164,9 +203,11 @@ class LogRead: short (a page limit, a failed page) leaves the window open. ``hidden``: entries the reader saw but did not return (for example another caller's entries a reader filters out). Any hidden entry may - have touched the record, so it blocks VERIFIED. + have touched the record, so it blocks VERIFIED and keeps a changed + value from being attributed. ``logs``: the operations this log records. A kind it doesn't record - can't be seen, and the result lists it as not covered. + can't be seen, and the result lists it as not covered. A log that + records nothing gives no ``activity_log`` basis. """ entries: Sequence[LogEntry] @@ -180,7 +221,9 @@ class ActivityLog(Protocol): def checkpoint(self) -> Mapping[str, Any]: """An opaque, JSON-safe position: the newest entry ids or a stream - cursor. Raises :class:`ReadFailed` when the log can't be placed.""" + cursor, never record values or identifiers (the private state keeps + it as given). Raises :class:`ReadFailed` when the log can't be + placed.""" ... def since(self, checkpoint: Mapping[str, Any]) -> LogRead: @@ -192,24 +235,88 @@ def since(self, checkpoint: Mapping[str, Any]) -> LogRead: # -- digests ------------------------------------------------------------------- +def _json_value(value: Any) -> None: + """Raise ``TypeError`` unless ``value`` is a plain JSON value.""" + + if value is None or isinstance(value, (bool, int, str)): + return + if isinstance(value, float): + if not math.isfinite(value): + raise TypeError("a non-finite number has no exact JSON form") + return + if isinstance(value, (list, tuple)): + for item in value: + _json_value(item) + return + if isinstance(value, Mapping): + for key, item in value.items(): + if not isinstance(key, str): + raise TypeError("object keys must be strings") + _json_value(item) + return + raise TypeError(f"{type(value).__name__} is not a JSON value") + + def _canonical(value: Any) -> bytes: + """One exact text per JSON value: ``1`` and ``"1"`` differ, and a type + without an exact JSON form raises ``TypeError``.""" + + _json_value(value) return json.dumps( - value, sort_keys=True, separators=(",", ":"), default=str + value, sort_keys=True, separators=(",", ":"), allow_nan=False ).encode() -def _mac(salt: bytes, label: str, value: Any) -> str: +def _key(salt: bytes) -> bytes: + """The state's MAC key: the salt keyed by this host's frame secret.""" + + from openadapt_flow.runtime.effects.db_snapshot import mac_key + + return mac_key(salt) + + +def _mac(key: bytes, label: str, value: Any) -> str: return hmac.new( - salt, label.encode() + b"\0" + _canonical(value), hashlib.sha256 + key, label.encode() + b"\0" + _canonical(value), hashlib.sha256 ).hexdigest() +def _fields_mac(key: bytes, seen: Readback) -> str: + return _mac(key, "fields", [seen.found, dict(seen.fields)]) + + +def _identity_mac(key: bytes, seen: Readback) -> str: + return _mac(key, "identity", seen.identity) + + +def _version_mac(key: bytes, seen: Readback) -> Optional[str]: + return None if seen.version is None else _mac(key, "version", seen.version) + + +def _event_mac(key: bytes, event_id: str, kind: str) -> str: + return _mac(key, "event", [event_id, kind]) + + def state_sha256(state: Mapping[str, Any]) -> str: """The digest a receipt binds: the whole private state, salt included.""" return "sha256:" + hashlib.sha256(_canonical(dict(state))).hexdigest() +def _events(events: Any) -> dict[str, Op]: + """``{entry id: operation}``; a bare string is refused, since its + characters would read as separate ids.""" + + if isinstance(events, (str, bytes)) or not isinstance(events, Mapping): + raise ValueError("events must be a mapping of entry id to operation") + out: dict[str, Op] = {} + for event_id, kind in events.items(): + if not isinstance(event_id, str) or not event_id or kind not in _ALL_OPS: + raise ValueError("each event is a non-empty id and create/update/delete") + out[event_id] = kind + return out + + # -- result -------------------------------------------------------------------- @@ -225,6 +332,8 @@ class RecheckResult: not_covered: list[str] entries_after_checkpoint: int = 0 other_actor_entries: int = 0 + #: When the recheck's reads started; ``rechecked_at`` is when they ended. + observed_from: Optional[str] = None @property def late_outcome(self) -> LateOutcome: @@ -239,6 +348,7 @@ def scope(self) -> dict[str, Any]: "basis": self.basis[0] if self.basis else None, "bases": list(self.basis), "read_back_at": self.read_back_at, + "observed_between": [self.observed_from, self.rechecked_at], "rechecked_at": self.rechecked_at, "recheck_window_s": self.recheck_window_s, "not_covered": list(self.not_covered), @@ -257,24 +367,35 @@ def to_json(self) -> dict[str, Any]: def _not_checked( reason: str, state: Optional[Mapping[str, Any]] = None, *, at: Optional[str] = None ) -> RecheckResult: + """``state`` only once :func:`state_problem` has passed it.""" + basis: list[str] = [] - if isinstance(state, Mapping): - basis = [BASIS_API] + ([BASIS_LOG] if state.get("log") is not None else []) - window = state.get("window_s") if isinstance(state, Mapping) else None + if state is not None: + basis = [BASIS_API] + ([BASIS_LOG] if state["log"] is not None else []) return RecheckResult( "NOT_CHECKED", reason, basis=basis, - read_back_at=str(state.get("read_at")) if isinstance(state, Mapping) else None, + read_back_at=str(state["read_at"]) if state is not None else None, rechecked_at=at, - recheck_window_s=window if isinstance(window, (int, float)) else None, + recheck_window_s=float(state["window_s"]) if state is not None else None, not_covered=list(ALWAYS_NOT_COVERED), + observed_from=at, ) # -- begin --------------------------------------------------------------------- +def _window_ok(window_s: Any) -> bool: + return ( + not isinstance(window_s, bool) + and isinstance(window_s, (int, float)) + and math.isfinite(window_s) + and 0 < window_s <= MAX_WINDOW_S + ) + + def begin( record: RecordSource, *, @@ -282,7 +403,7 @@ def begin( first_outcome: str, window_s: float, log: Optional[ActivityLog] = None, - own_event_ids: Sequence[str] = (), + own_events: Mapping[str, Op] | None = None, now: Optional[datetime] = None, ) -> dict[str, Any]: """The private recheck state, taken right after the first check. @@ -290,52 +411,68 @@ def begin( ``target``: the record's reference (``Patient/123``); bound, never re-read from the state. ``first_outcome``: the first check's outcome; a recheck of anything but ``VERIFIED`` stays ``NOT_CHECKED``. - ``own_event_ids``: the write's own log entries, which the first check - already judged; they may land after the checkpoint while the log lags. + ``own_events``: ``{entry id: operation}`` for the write's own log + entries, which the first check already judged; they may land after the + checkpoint while the log lags. They are exempt only when the log + attributes them to this caller with that operation. The log checkpoint is taken before the read, so an entry between the two reads shows up in the window rather than in the baseline. Raises - :class:`ReadFailed` when either source can't be read, and ``ValueError`` - for a window that isn't a positive number of seconds. + :class:`ReadFailed` when either source can't be read or the record is + not there (a baseline of "absent" would verify a deletion), and + ``ValueError`` for a window that isn't a positive number of seconds up + to :data:`MAX_WINDOW_S` or for malformed events. """ - if ( - isinstance(window_s, bool) - or not isinstance(window_s, (int, float)) - or not window_s > 0 - or window_s == float("inf") - ): + if not _window_ok(window_s): raise ValueError("the recheck window must be a positive number of seconds") + own = _events({} if own_events is None else own_events) salt = secrets.token_bytes(32) + key = _key(salt) checkpoint = None if log is None else dict(log.checkpoint()) seen = record.read() if not isinstance(seen, Readback): raise ReadFailed("the record source returned no read-back") + if not seen.found: + raise ReadFailed("the record is not there; there is nothing to recheck") + if seen.identity is None: + raise ReadFailed("the read-back did not show the record's identity") + try: + if checkpoint is not None: + _canonical(checkpoint) + fields_mac = _fields_mac(key, seen) + identity_mac = _identity_mac(key, seen) + version_mac = _version_mac(key, seen) + except (TypeError, ValueError): + raise ReadFailed("a read returned a value with no exact JSON form") from None read_at = format_time(now or datetime.now(timezone.utc)) return { "schema_version": SCHEMA, "salt": salt.hex(), - "target": _mac(salt, "target", target), + "key_check": _mac(key, "key-check", SCHEMA), + "target": _mac(key, "target", str(target)), "first_outcome": str(first_outcome), "read_at": read_at, "window_s": float(window_s), "due_at": due_at(read_at, float(window_s)), - "fields_mac": _mac(salt, "fields", [seen.found, dict(seen.fields)]), - "version_mac": None - if seen.version is None - else _mac(salt, "version", seen.version), + "identity_mac": identity_mac, + "fields_mac": fields_mac, + "version_mac": version_mac, "log": checkpoint, - "own_events": sorted({_mac(salt, "event", i) for i in own_event_ids}), + "own_events": sorted(_event_mac(key, i, k) for i, k in own.items()), } def schedule(state: Mapping[str, Any]) -> dict[str, Any]: """The block a receipt carries: when the recheck is due and the state it - binds. No salt, no values.""" + binds. No salt, no values. Raises ``ValueError`` for a malformed state.""" + problem = state_problem(state) + if problem is not None: + raise ValueError(problem) return { "compares": "api_readback_and_log_since_checkpoint" - if state.get("log") is not None + if state["log"] is not None else "api_readback", "read_back_at": state["read_at"], "recheck_window_s": state["window_s"], @@ -353,21 +490,40 @@ def state_problem(state: Any) -> Optional[str]: return f"the recheck state is not an {SCHEMA} document" if set(state) != set(STATE_KEYS): return "the recheck state must hold exactly " + ", ".join(STATE_KEYS) + for name in ("salt", "key_check", "target", "identity_mac", "fields_mac"): + if not isinstance(state[name], str) or not _HEX64.match(state[name]): + return f"the recheck state's {name} is not 64 hex digits" + version = state["version_mac"] + if version is not None and ( + not isinstance(version, str) or not _HEX64.match(version) + ): + return "the recheck state's version_mac is not 64 hex digits" + if not isinstance(state["first_outcome"], str): + return "the recheck state's first outcome is not text" + if not isinstance(state["read_at"], str) or not _TIME.match(state["read_at"]): + return "the recheck state's read time is malformed" + if not _window_ok(state["window_s"]): + return "the recheck state's window is out of range" + if not isinstance(state["due_at"], str) or not _TIME.match(state["due_at"]): + return "the recheck state's due time is malformed" try: - if len(bytes.fromhex(str(state["salt"]))) != 32: - return "the recheck state's salt is not 32 bytes" - except ValueError: - return "the recheck state's salt is not hex" - try: - expected_due = due_at(str(state["read_at"]), float(state["window_s"])) - except (TypeError, ValueError): + expected_due = due_at(state["read_at"], float(state["window_s"])) + except (TypeError, ValueError, OverflowError): return "the recheck state's read time or window is malformed" if state["due_at"] != expected_due: return "the recheck state's due time doesn't follow from its window" - if state["log"] is not None and not isinstance(state["log"], Mapping): - return "the recheck state's log checkpoint is not an object" - if not isinstance(state["own_events"], list): - return "the recheck state's own events are not a list" + if state["log"] is not None: + if not isinstance(state["log"], Mapping): + return "the recheck state's log checkpoint is not an object" + try: + _canonical(state["log"]) + except (TypeError, ValueError): + return "the recheck state's log checkpoint is not plain JSON" + events = state["own_events"] + if not isinstance(events, list) or not all( + isinstance(e, str) and _HEX64.match(e) for e in events + ): + return "the recheck state's own events are not a list of digests" return None @@ -381,39 +537,67 @@ def recheck( target: str, expected_state_sha256: str, log: Optional[ActivityLog] = None, - excused_event_ids: Sequence[str] = (), + excused_events: Mapping[str, Op] | None = None, now: Optional[datetime] = None, ) -> RecheckResult: """Read the record and the log again and judge what changed. ``expected_state_sha256``: from the receipt (:func:`schedule`), so a - state that was edited or swapped doesn't match. ``excused_event_ids``: - log entries of later declared writes by this caller that their own - checks account for (any outcome); they don't refute this write. + state that was edited or swapped doesn't match. ``excused_events``: + ``{entry id: operation}`` for log entries of later declared writes by + this caller that their own checks account for (any outcome); they don't + refute this write when the log attributes them to this caller with that + operation. An exempted entry the log attributes otherwise makes the + recheck ``NOT_CHECKED``. + + ``now`` fixes both ends of the observation (for tests); without it the + start is taken before the reads and the end after them. """ - current = now or datetime.now(timezone.utc) - at = format_time(current) + start = now or datetime.now(timezone.utc) + started = format_time(start) problem = state_problem(state) if problem is not None: - return _not_checked(problem, at=at) + return _not_checked(problem, at=started) if not hmac.compare_digest(state_sha256(state), str(expected_state_sha256)): - return _not_checked("the recheck state doesn't match its receipt", at=at) - salt = bytes.fromhex(str(state["salt"])) - if not hmac.compare_digest(_mac(salt, "target", target), str(state["target"])): + return _not_checked("the recheck state doesn't match its receipt", at=started) + salt = bytes.fromhex(state["salt"]) + try: + key = _key(salt) + except Exception: # noqa: BLE001 - no host secret: nothing can be compared + return _not_checked("this host's frame secret could not be read", at=started) + if not hmac.compare_digest(_mac(key, "key-check", SCHEMA), state["key_check"]): + return _not_checked( + "the recheck state was taken on a host with another frame secret", + at=started, + ) + if not hmac.compare_digest(_mac(key, "target", str(target)), state["target"]): return _not_checked( - "the recheck state was taken for another record", state, at=at + "the recheck state was taken for another record", state, at=started ) if state["first_outcome"] != "VERIFIED": return _not_checked( - "the first check was not VERIFIED; a recheck can't raise it", state, at=at + "the first check was not VERIFIED; a recheck can't raise it", + state, + at=started, ) - if seconds_until(str(state["due_at"]), current) > 0: - return _not_checked("the recheck is not due yet", state, at=at) + if seconds_until(state["due_at"], start) > 0: + return _not_checked("the recheck is not due yet", state, at=started) if (state["log"] is None) != (log is None): return _not_checked( - "the log given doesn't match the log the state was taken with", state, at=at + "the log given doesn't match the log the state was taken with", + state, + at=started, ) + try: + excused = { + _event_mac(key, i, k) + for i, k in _events( + {} if excused_events is None else excused_events + ).items() + } + except ValueError: + return _not_checked("the excused events are malformed", state, at=started) # The record first, then the log: an entry between the two reads is in # the log read, so a change can't slip between them. @@ -421,20 +605,29 @@ def recheck( seen = record.read() if not isinstance(seen, Readback): raise ReadFailed("the record source returned no read-back") - except ReadFailed as exc: - return _not_checked(f"the record could not be read again: {exc}", state, at=at) + fields_now = _fields_mac(key, seen) + identity_now = _identity_mac(key, seen) if seen.found else None + version_now = _version_mac(key, seen) + except (ReadFailed, TypeError, ValueError): + return _not_checked("the record could not be read again", state, at=started) window: Optional[LogRead] = None if log is not None: try: window = log.since(dict(state["log"])) - except ReadFailed as exc: - return _not_checked(f"the log could not be read: {exc}", state, at=at) - - basis = [BASIS_API] + ([BASIS_LOG] if window is not None else []) + if not isinstance(window, LogRead) or any( + op not in _ALL_OPS for op in window.logs + ): + raise ReadFailed("the log returned no log read") + except ReadFailed: + return _not_checked("the log could not be read", state, at=started) + at = format_time(now or datetime.now(timezone.utc)) + + log_covers = window is not None and bool(window.logs) + basis = [BASIS_API] + ([BASIS_LOG] if log_covers else []) not_covered = list(ALWAYS_NOT_COVERED) - if window is None: - not_covered.append("changes reverted between the two reads (no log read)") - else: + if not log_covers: + not_covered.extend(NO_LOG_NOT_COVERED) + if window is not None: missing = [op for op in _ALL_OPS if op not in window.logs] if missing: not_covered.append("log does not record: " + ", ".join(missing)) @@ -444,7 +637,7 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: outcome, reason, basis=basis, - read_back_at=str(state["read_at"]), + read_back_at=state["read_at"], rechecked_at=at, recheck_window_s=float(state["window_s"]), not_covered=not_covered, @@ -452,45 +645,78 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: other_actor_entries=sum(1 for e in window.entries if e.by == "other") if window else 0, + observed_from=started, ) # What the log says, when there is one. other_on_target = unknown_on_target = self_on_target = False - self_elsewhere = unknown_elsewhere = False + self_elsewhere = unknown_elsewhere = contradicted = False if window is not None: own = set(state["own_events"]) - excused = {_mac(salt, "event", i) for i in excused_event_ids} for entry in window.entries: + kind = entry.kind if entry.kind in _ALL_OPS else None if entry.kind == "read": continue - h = _mac(salt, "event", entry.id) - if h in own: - continue # the write's own entry, judged by the first check - if entry.on_target: - if entry.by == "other": + by = entry.by if entry.by in ("self", "other") else "unknown" + exempt = kind is not None and _event_mac(key, str(entry.id), kind) in ( + own | excused + ) + if exempt and by == "self": + continue # this caller's declared write, judged by its own check + if exempt or any( + _event_mac(key, str(entry.id), op) in (own | excused) for op in _ALL_OPS + ): + # An exempted id whose author or operation disagrees with the + # write it was exempted for. + contradicted = True + continue + if entry.on_target is True: + if by == "other": other_on_target = True - elif ( - entry.by == "self" and entry.kind != "unknown" and h not in excused - ): + elif by == "self" and kind is not None: self_on_target = True - elif h not in excused: + else: unknown_on_target = True - elif entry.by == "self" and h not in excused: - if entry.kind == "unknown": + elif entry.on_target is not False: + unknown_on_target = True + elif by == "self": + if kind is None: unknown_elsewhere = True else: self_elsewhere = True - elif entry.by == "unknown" and h not in excused: + elif by == "unknown": unknown_elsewhere = True - fields_now = _mac(salt, "fields", [seen.found, dict(seen.fields)]) - fields_held = hmac.compare_digest(fields_now, str(state["fields_mac"])) - if not fields_held: - if other_on_target: + # Mutations the log proves this caller made come first: another + # actor's change to the record doesn't explain them. + if self_on_target: + return result( + "REFUTED", + "the log shows another write to the record by this caller that " + "nothing declared accounts for", + ) + if self_elsewhere: + return result( + "REFUTED", + "the log shows a change by this caller to another record that " + "nothing declared accounts for", + ) + if seen.found and not hmac.compare_digest(str(identity_now), state["identity_mac"]): + return result( + "NOT_CHECKED", + "the read-back now lands on a different record than the first read", + ) + if not hmac.compare_digest(fields_now, state["fields_mac"]): + if ( + other_on_target + or unknown_on_target + or contradicted + or (window is not None and window.hidden) + ): return result( "NOT_CHECKED", - "the record changed since the first read, and the log attributes " - "a change to another actor", + "the record changed since the first read, and the log does not " + "attribute the change to this caller", ) if not seen.found: return result( @@ -500,17 +726,10 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: return result( "REFUTED", "the record no longer shows the values the first read showed" ) - if self_on_target: + if contradicted: return result( - "REFUTED", - "the log shows another write to the record by this caller that " - "nothing declared accounts for", - ) - if self_elsewhere: - return result( - "REFUTED", - "the log shows a change by this caller to another record that " - "nothing declared accounts for", + "NOT_CHECKED", + "an exempted log entry is attributed to another author or operation", ) if window is not None and not window.reached: return result("NOT_CHECKED", "the log read did not reach the checkpoint") @@ -529,7 +748,6 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: return result( "NOT_CHECKED", "the log holds entries whose author or kind is unknown" ) - version_now = None if seen.version is None else _mac(salt, "version", seen.version) if version_now != state["version_mac"]: return result( "NOT_CHECKED", @@ -537,27 +755,40 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: ) return result( "VERIFIED", - f"as of {at}, the read-back showed the values the first read showed" + f"read between {started} and {at}, the read-back showed the record and " + "values the first read showed" + ( ", and the log since the checkpoint shows no unexplained change" - if window is not None - else "" + if log_covers + else "; no log was read, so this caller's other changes are not covered" ), ) # -- adapters ------------------------------------------------------------------ +_MISSING = object() + def _dotted(record: Any, path: str) -> Any: current = record for part in path.split("."): if not isinstance(current, Mapping) or part not in current: - return None + return _MISSING current = current[part] return current +def _redacted(value: Any) -> bool: + if isinstance(value, str): + return value.startswith("[redacted") + if isinstance(value, Mapping): + return any(_redacted(v) for v in value.values()) + if isinstance(value, (list, tuple)): + return any(_redacted(v) for v in value) + return False + + class VerifierReadback: """A :class:`RecordSource` over a REST, FHIR or GraphQL verifier on main. @@ -569,13 +800,21 @@ class VerifierReadback: Each read runs ``verifier.verify(effect, before)`` against the pre-write baseline, as the first check did. CONFIRMED with exactly one matched - record gives that record's ``fields`` (default: the effect's match - keys); REFUTED gives ``found=False``; anything else fails the read. - - ``version_path`` names a server version (``meta.versionId``); without - it, the version is a digest of the whole matched record minus - ``ignore`` (volatile fields such as ``meta.lastUpdated`` belong there - only when the server rewrites them without a change). + record gives that record's ``identity_path`` (default ``id``) and + ``fields`` (default: the effect's match keys); REFUTED with no matched + record gives ``found=False``; anything else (an ambiguous match, a + refutation that names records, a missing declared field, a redacted + value) fails the read. + + ``version_path`` names a server version (``meta.versionId``, or the key + a FHIR ``field_paths`` maps it to). FHIR and GraphQL records are + projections, so they need one. A REST verifier that drops no fields may + leave it out: the version is then a digest of the whole matched record + minus ``ignore`` (volatile fields such as ``meta.lastUpdated`` belong + there only when the server rewrites them without a change). A verifier + whose redaction policy covers a compared field, or any field when the + version is a whole-record digest, is refused: redacted evidence can't + tell two values apart. """ def __init__( @@ -586,6 +825,7 @@ def __init__( *, fields: Optional[Sequence[str]] = None, version_path: Optional[str] = None, + identity_path: str = "id", ignore: Sequence[str] = (), context: Any = None, ) -> None: @@ -594,6 +834,7 @@ def __init__( self.before = before self.fields = tuple(fields) if fields is not None else tuple(effect.match) self.version_path = version_path + self.identity_path = identity_path self.ignore = tuple(ignore) self.context = context substrate = str(getattr(verifier, "substrate", "")) @@ -608,30 +849,53 @@ def __init__( or int(tier) != 1 ): raise ValueError("the verifier does not read the system of record") + if version_path is None and ( + substrate in _PROJECTED_SUBSTRATES + or tuple(getattr(verifier, "drop_fields", ())) + ): + raise ValueError( + "a projected read needs a named server version (version_path)" + ) + policy = getattr(verifier, "redaction", None) + if policy is not None: + compared = [*self.fields, identity_path] + if version_path is not None: + compared.append(version_path) + if version_path is None or any( + policy.is_redacted(path) or policy.is_redacted(path.split(".")[0]) + for path in compared + ): + raise ValueError("the verifier redacts evidence the recheck compares") def read(self) -> Readback: try: verdict = self.verifier.verify(self.effect, self.before, self.context) - except Exception as exc: # noqa: BLE001 - any failure is an unread record - raise ReadFailed(type(exc).__name__) from exc + except Exception: # noqa: BLE001 - any failure is an unread record + raise ReadFailed("the verifier could not read the record") from None status = getattr(getattr(verdict, "verdict", None), "value", None) - if status == "refuted": - return Readback(found=False) records = list(getattr(verdict, "matched_records", []) or []) + if status == "refuted" and not records: + return Readback(found=False) if status != "confirmed" or len(records) != 1: - raise ReadFailed( - getattr(verdict, "reason", "") or "the read was not conclusive" - ) + raise ReadFailed("the read did not identify exactly one record") rec = records[0] + identity = _dotted(rec, self.identity_path) + if identity is _MISSING or identity is None: + raise ReadFailed("the record carries no identity") + fields = {f: _dotted(rec, f) for f in self.fields} + if any(v is _MISSING for v in fields.values()): + raise ReadFailed("the record lacks a declared field") if self.version_path: - raw = _dotted(rec, self.version_path) - if raw is None: + version = _dotted(rec, self.version_path) + if version is _MISSING or version is None: # A named version that isn't there would silently drop the # check that catches A to B to A. - raise ReadFailed(f"the record has no {self.version_path}") - version = str(raw) + raise ReadFailed("the record has no named version") else: - trimmed = json.loads(_canonical(rec)) + try: + trimmed = json.loads(_canonical(rec)) + except (TypeError, ValueError): + raise ReadFailed("the record has a value with no exact form") from None for path in self.ignore: parts = path.split(".") holder = ( @@ -640,11 +904,9 @@ def read(self) -> Readback: if isinstance(holder, dict): holder.pop(parts[-1], None) version = hashlib.sha256(_canonical(trimmed)).hexdigest() - return Readback( - found=True, - fields={f: _dotted(rec, f) for f in self.fields}, - version=version, - ) + if _redacted([identity, fields, version]): + raise ReadFailed("the read-back carries redacted values") + return Readback(found=True, fields=fields, version=version, identity=identity) __all__ = [ @@ -655,6 +917,8 @@ def read(self) -> Readback: "BASIS_LOG", "LogEntry", "LogRead", + "MAX_WINDOW_S", + "NO_LOG_NOT_COVERED", "Outcome", "ReadFailed", "Readback", diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index 78aad2259b..cfa817b22e 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -39,13 +39,19 @@ def __init__(self, fields: Mapping[str, Any], version: Optional[str] = "1") -> N self.version = version self.found = True self.fail = False + self.identity: Any = "7" def read(self) -> Readback: if self.fail: raise ReadFailed("503") if not self.found: return Readback(found=False) - return Readback(found=True, fields=dict(self.fields), version=self.version) + return Readback( + found=True, + fields=dict(self.fields), + version=self.version, + identity=self.identity, + ) class Log: @@ -132,10 +138,16 @@ def test_unchanged_record_and_quiet_log_verify_as_of_the_recheck() -> None: def test_state_and_schedule_hold_no_values() -> None: - _, state, sched = _setup(Log()) + log = Log() + rec = Record({"name.family": "Lovelace-Q", "birthDate": "1815-12-10 (q)"}) + rec.identity = "Patient-Qz" + state = begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5, log=log) + sched = schedule(state) text = json.dumps(state) + json.dumps(sched) - assert "Lovelace" not in text and "1815" not in text and TARGET not in text - assert "salt" not in sched and state_problem(state) is None + for value in ("Lovelace-Q", "1815-12-10 (q)", "Patient-Qz", TARGET): + assert value not in text + assert state["salt"] not in json.dumps(sched) and "salt" not in sched + assert state_problem(state) is None def test_recheck_before_the_due_time_is_not_checked() -> None: @@ -208,13 +220,14 @@ def test_own_late_collateral_refutes_unless_a_later_write_accounts_for_it() -> N rec, state, sched = _setup(log) log.add("d1", "delete", "self", False) assert _run(state, rec, sched, log).outcome == "REFUTED" - assert _run(state, rec, sched, log, excused_event_ids=["d1"]).outcome == "VERIFIED" + excused = {"d1": "delete"} + assert _run(state, rec, sched, log, excused_events=excused).outcome == "VERIFIED" def test_the_writes_own_lagging_entry_is_not_a_change() -> None: log = Log() log.entries = [] - rec, state, sched = _setup(log, own_event_ids=["mine"]) + rec, state, sched = _setup(log, own_events={"mine": "create"}) log.add("mine", "create", "self", True) assert _run(state, rec, sched, log).outcome == "VERIFIED" @@ -480,3 +493,237 @@ def test_missing_named_version_fails_the_read() -> None: verifier.record = {"id": "7"} with pytest.raises(ReadFailed): source.read() + + +# -- review round 1: fail-closed cases ------------------------------------------ + + +def test_begin_refuses_an_absent_record() -> None: + rec = Record({"birthDate": "1815-12-10"}) + rec.found = False + with pytest.raises(ReadFailed): + begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + + +def test_begin_refuses_a_read_back_with_no_identity() -> None: + rec = Record({"birthDate": "1815-12-10"}) + rec.identity = None + with pytest.raises(ReadFailed): + begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + + +def test_a_read_back_landing_on_another_record_is_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + rec.identity = "8" # same declared values and version, another record + out = _run(state, rec, sched, log) + assert out.outcome == "NOT_CHECKED" and "different record" in out.reason + + +def test_no_log_verified_lists_other_records_as_not_covered() -> None: + rec, state, sched = _setup() + out = _run(state, rec, sched) + assert out.outcome == "VERIFIED" + assert any("other records" in line for line in out.not_covered) + assert "log since the checkpoint" not in out.reason + + +def test_a_log_that_records_nothing_gives_no_log_basis() -> None: + log = Log() + rec, state, sched = _setup(log) + log.logs = () + out = _run(state, rec, sched, log) + assert out.scope()["bases"] == ["system_api"] + assert any("other records" in line for line in out.not_covered) + assert "log since the checkpoint" not in out.reason + + +def test_missing_and_null_fields_and_version_types_differ() -> None: + rec, state, sched = _setup() + rec.version = 1 # was the string "1" + assert _run(state, rec, sched).outcome == "NOT_CHECKED" + rec.version = "1" + rec.fields["birthDate"] = None + assert _run(state, rec, sched).outcome == "REFUTED" + + +def test_a_value_with_no_exact_json_form_fails_the_read() -> None: + from decimal import Decimal + + with pytest.raises(ReadFailed): + begin( + Record({"amount": Decimal("1.0")}), + target=TARGET, + first_outcome="VERIFIED", + window_s=5, + ) + rec, state, sched = _setup() + rec.fields["birthDate"] = Decimal("1815") + assert _run(state, rec, sched).outcome == "NOT_CHECKED" + + +def test_exemptions_need_matching_attribution() -> None: + log = Log() + log.entries = [] + rec, state, sched = _setup(log, own_events={"mine": "create"}) + log.add("mine", "create", "other", True) # own id, another author + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + log = Log() + rec, state, sched = _setup(log) + log.add("q", "unknown", "unknown", True) + assert _run(state, rec, sched, log, excused_events={"q": "update"}).outcome == ( + "NOT_CHECKED" + ) + log = Log() + rec, state, sched = _setup(log) + log.add("d1", "update", "self", False) # excused as a delete, logged an update + out = _run(state, rec, sched, log, excused_events={"d1": "delete"}) + assert out.outcome == "NOT_CHECKED" + + +def test_a_bare_string_is_not_a_set_of_event_ids() -> None: + log = Log() + rec, state, sched = _setup(log) + log.add("1", "delete", "self", False) + assert _run(state, rec, sched, log, excused_events="12").outcome == "NOT_CHECKED" + with pytest.raises(ValueError): + begin( + Record({}), + target=TARGET, + first_outcome="VERIFIED", + window_s=5, + own_events="12", # type: ignore[arg-type] + ) + + +def test_a_proven_caller_mutation_refutes_despite_another_actor() -> None: + log = Log() + rec, state, sched = _setup(log) + rec.fields["birthDate"] = "1815-12-11" + log.add("o1", "update", "other", True) + log.add("d2", "delete", "self", False) + assert _run(state, rec, sched, log).outcome == "REFUTED" + + +def test_a_changed_value_by_an_unknown_actor_is_not_checked() -> None: + log = Log() + rec, state, sched = _setup(log) + rec.fields["birthDate"] = "1815-12-11" + log.add("u1", "update", "unknown", True) + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + log = Log() + rec, state, sched = _setup(log) + rec.fields["birthDate"] = "1815-12-11" + log.hidden = 1 + assert _run(state, rec, sched, log).outcome == "NOT_CHECKED" + + +def test_a_state_is_only_recheckable_with_the_same_host_secret( + monkeypatch: pytest.MonkeyPatch, +) -> None: + rec, state, sched = _setup() + monkeypatch.setenv("OPENADAPT_FRAME_SECRET", "22" * 32) + out = _run(state, rec, sched) + assert out.outcome == "NOT_CHECKED" and "frame secret" in out.reason + + +def test_read_failure_reasons_carry_no_upstream_text() -> None: + class Leaky: + def read(self) -> Readback: + raise ReadFailed("GET https://sor.example/Patient/7 returned 500") + + rec, state, sched = _setup() + out = _run(state, Leaky(), sched) + assert out.outcome == "NOT_CHECKED" + assert "Patient/7" not in json.dumps(out.to_json()) + + +@pytest.mark.parametrize( + "edit", + [ + lambda s: s.update(window_s=1e300), + lambda s: s.update(window_s="120"), + lambda s: s.update(read_at=s["salt"]), + lambda s: s.update(version_mac=1), + lambda s: s.update(own_events=["x"]), + ], +) +def test_malformed_state_is_refused_everywhere(edit: Any) -> None: + rec, state, sched = _setup() + edit(state) + assert state_problem(state) is not None + with pytest.raises(ValueError): + schedule(state) + assert _run(state, rec, sched).outcome == "NOT_CHECKED" + + +def test_the_result_reports_the_observation_interval() -> None: + rec, state, sched = _setup() + out = _run(state, rec, sched) + assert out.scope()["observed_between"] == [ + "2026-11-21T12:03:20Z", + "2026-11-21T12:03:20Z", + ] + assert "read between" in out.reason + + +def test_an_ambiguous_match_fails_the_read() -> None: + verifier = _Verifier() + source = VerifierReadback(verifier, _Effect(), None, version_path="meta.versionId") + verifier.verify = lambda *a: _Verdict( # type: ignore[method-assign] + "refuted", [{"id": "7"}, {"id": "9"}] + ) + with pytest.raises(ReadFailed): + source.read() + verifier.verify = lambda *a: _Verdict("refuted", []) # type: ignore[method-assign] + assert source.read().found is False + + +def test_a_missing_declared_field_fails_the_read() -> None: + verifier = _Verifier() + source = VerifierReadback( + verifier, _Effect(), None, fields=["note"], version_path="meta.versionId" + ) + with pytest.raises(ReadFailed): + source.read() + + +def test_redacted_or_projected_verifiers_are_refused() -> None: + from openadapt_flow.runtime.effects.adapter import RedactionPolicy + from openadapt_flow.runtime.effects.fhir import FhirEffectVerifier + from openadapt_flow.runtime.effects.graphql import GraphQLRecordVerifier + + class Note: + match = {"note": "A"} + + gql = GraphQLRecordVerifier( + "https://sor.invalid/graphql", + query="query { notes { id note version } }", + redaction=RedactionPolicy(redact_fields=["note"]), + ) + with pytest.raises(ValueError): + VerifierReadback(gql, Note(), None, version_path="version") + gql.redaction = None + with pytest.raises(ValueError): + VerifierReadback(gql, Note(), None) # a projection with no version + VerifierReadback(gql, Note(), None, version_path="version") + + fhir = FhirEffectVerifier( + "https://sor.invalid/fhir", + resource_type="Patient", + field_paths={"note": "note", "version": "meta.versionId"}, + ) + with pytest.raises(ValueError): + VerifierReadback(fhir, Note(), None) + VerifierReadback(fhir, Note(), None, version_path="version") + + +def test_a_redacted_value_in_the_read_back_fails_the_read() -> None: + verifier = _Verifier() + verifier.record = {"id": "7", "meta": {"versionId": "1"}, "note": "[redacted]"} + source = VerifierReadback( + verifier, _Effect(), None, fields=["note"], version_path="meta.versionId" + ) + with pytest.raises(ReadFailed): + source.read() From 288685b7a06564a46d58963d204b7ceeb62b7157 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:19:15 -0500 Subject: [PATCH 5/9] fix(verify): remove vendor name from docstring and close 4 Codex recheck findings --- .../runtime/effects/api_recheck.py | 176 ++++++++++++++++-- packages/flow/tests/test_api_recheck.py | 100 ++++++++++ 2 files changed, 260 insertions(+), 16 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index 04ec408372..200a9d102f 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -44,7 +44,7 @@ The local clock only decides when the recheck is due. Which log entries are in the window is decided by the log's own checkpoint and entry ids, never by -comparing clocks: Medplum's server clock ran about 1.5 s off the client's. +comparing clocks: remote server clocks routinely drift relative to the client. The recheck can only keep or lower the first result. It never turns a first result that wasn't verified into ``VERIFIED``. @@ -84,6 +84,8 @@ "salt", "key_check", "target", + "source_mac", + "log_scope_mac", "first_outcome", "read_at", "window_s", @@ -396,6 +398,13 @@ def _window_ok(window_s: Any) -> bool: ) +def _source_binding(obj: Any, attr: str) -> Any: + raw = getattr(obj, attr, None) + if callable(raw): + return raw() + return raw + + def begin( record: RecordSource, *, @@ -404,6 +413,7 @@ def begin( window_s: float, log: Optional[ActivityLog] = None, own_events: Mapping[str, Op] | None = None, + first_identity: Any = None, now: Optional[datetime] = None, ) -> dict[str, Any]: """The private recheck state, taken right after the first check. @@ -411,6 +421,8 @@ def begin( ``target``: the record's reference (``Patient/123``); bound, never re-read from the state. ``first_outcome``: the first check's outcome; a recheck of anything but ``VERIFIED`` stays ``NOT_CHECKED``. + ``first_identity``: optional record id observed by the first check; when + supplied, the baseline read must land on the same record id. ``own_events``: ``{entry id: operation}`` for the write's own log entries, which the first check already judged; they may land after the checkpoint while the log lags. They are exempt only when the log @@ -418,15 +430,22 @@ def begin( The log checkpoint is taken before the read, so an entry between the two reads shows up in the window rather than in the baseline. Raises - :class:`ReadFailed` when either source can't be read or the record is - not there (a baseline of "absent" would verify a deletion), and - ``ValueError`` for a window that isn't a positive number of seconds up - to :data:`MAX_WINDOW_S` or for malformed events. + :class:`ReadFailed` when either source can't be read, lacks a source or + stream/actor binding, or the record is not there (a baseline of "absent" + would verify a deletion), and ``ValueError`` for a window that isn't a + positive number of seconds up to :data:`MAX_WINDOW_S` or for malformed + events. """ if not _window_ok(window_s): raise ValueError("the recheck window must be a positive number of seconds") own = _events({} if own_events is None else own_events) + source_scope = _source_binding(record, "source_scope") + if source_scope is None: + raise ReadFailed("the record source carries no source binding") + log_scope = None if log is None else _source_binding(log, "stream_scope") + if log is not None and log_scope is None: + raise ReadFailed("the log source carries no stream and actor binding") salt = secrets.token_bytes(32) key = _key(salt) checkpoint = None if log is None else dict(log.checkpoint()) @@ -438,6 +457,18 @@ def begin( if seen.identity is None: raise ReadFailed("the read-back did not show the record's identity") try: + source_mac = _mac(key, "source", _canonical(source_scope).decode("ascii")) + log_scope_mac = ( + None + if log_scope is None + else _mac(key, "log-scope", _canonical(log_scope).decode("ascii")) + ) + if first_identity is not None and _canonical(seen.identity) != _canonical( + first_identity + ): + raise ReadFailed( + "the baseline read did not match the first check's observed record" + ) if checkpoint is not None: _canonical(checkpoint) fields_mac = _fields_mac(key, seen) @@ -451,6 +482,8 @@ def begin( "salt": salt.hex(), "key_check": _mac(key, "key-check", SCHEMA), "target": _mac(key, "target", str(target)), + "source_mac": source_mac, + "log_scope_mac": log_scope_mac, "first_outcome": str(first_outcome), "read_at": read_at, "window_s": float(window_s), @@ -490,9 +523,22 @@ def state_problem(state: Any) -> Optional[str]: return f"the recheck state is not an {SCHEMA} document" if set(state) != set(STATE_KEYS): return "the recheck state must hold exactly " + ", ".join(STATE_KEYS) - for name in ("salt", "key_check", "target", "identity_mac", "fields_mac"): + for name in ( + "salt", + "key_check", + "target", + "source_mac", + "identity_mac", + "fields_mac", + ): if not isinstance(state[name], str) or not _HEX64.match(state[name]): return f"the recheck state's {name} is not 64 hex digits" + log_scope_mac = state["log_scope_mac"] + if state["log"] is None: + if log_scope_mac is not None: + return "the recheck state carries a log_scope_mac without a log checkpoint" + elif not isinstance(log_scope_mac, str) or not _HEX64.match(log_scope_mac): + return "the recheck state's log_scope_mac is not 64 hex digits" version = state["version_mac"] if version is not None and ( not isinstance(version, str) or not _HEX64.match(version) @@ -589,6 +635,45 @@ def recheck( state, at=started, ) + source_scope = _source_binding(record, "source_scope") + if source_scope is None: + return _not_checked( + "the record source carries no source binding", state, at=started + ) + try: + source_mac = _mac(key, "source", _canonical(source_scope).decode("ascii")) + except (TypeError, ValueError): + return _not_checked( + "the record source binding has no exact JSON form", state, at=started + ) + if not hmac.compare_digest(source_mac, state["source_mac"]): + return _not_checked( + "the record source does not match the source the state was taken with", + state, + at=started, + ) + if log is not None: + log_scope = _source_binding(log, "stream_scope") + if log_scope is None: + return _not_checked( + "the log source carries no stream and actor binding", state, at=started + ) + try: + log_scope_mac = _mac( + key, "log-scope", _canonical(log_scope).decode("ascii") + ) + except (TypeError, ValueError): + return _not_checked( + "the log stream binding has no exact JSON form", state, at=started + ) + if state["log_scope_mac"] is None or not hmac.compare_digest( + log_scope_mac, state["log_scope_mac"] + ): + return _not_checked( + "the log stream or actor does not match the log the state was taken with", + state, + at=started, + ) try: excused = { _event_mac(key, i, k) @@ -706,6 +791,8 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: "NOT_CHECKED", "the read-back now lands on a different record than the first read", ) + if window is not None and not window.reached: + return result("NOT_CHECKED", "the log read did not reach the checkpoint") if not hmac.compare_digest(fields_now, state["fields_mac"]): if ( other_on_target @@ -731,8 +818,6 @@ def result(outcome: Outcome, reason: str) -> RecheckResult: "NOT_CHECKED", "an exempted log entry is attributed to another author or operation", ) - if window is not None and not window.reached: - return result("NOT_CHECKED", "the log read did not reach the checkpoint") if window is not None and window.hidden: return result( "NOT_CHECKED", @@ -849,24 +934,79 @@ def __init__( or int(tier) != 1 ): raise ValueError("the verifier does not read the system of record") + self._substrate = substrate + self._projected = substrate in _PROJECTED_SUBSTRATES if version_path is None and ( - substrate in _PROJECTED_SUBSTRATES - or tuple(getattr(verifier, "drop_fields", ())) + self._projected or tuple(getattr(verifier, "drop_fields", ())) ): raise ValueError( "a projected read needs a named server version (version_path)" ) - policy = getattr(verifier, "redaction", None) - if policy is not None: - compared = [*self.fields, identity_path] - if version_path is not None: - compared.append(version_path) + compared = [*self.fields, identity_path] + if version_path is not None: + compared.append(version_path) + for policy in self._redaction_policies(verifier): if version_path is None or any( policy.is_redacted(path) or policy.is_redacted(path.split(".")[0]) for path in compared ): raise ValueError("the verifier redacts evidence the recheck compares") + @staticmethod + def _redaction_policies(verifier: Any) -> list[Any]: + policies: list[Any] = [] + seen: set[int] = set() + cur: Any = verifier + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + for attr in ("redaction", "_policy"): + pol = cur.__dict__.get(attr) if hasattr(cur, "__dict__") else None + if pol is None: + pol = getattr(cur, attr, None) + if ( + pol is not None + and hasattr(pol, "is_redacted") + and pol not in policies + ): + policies.append(pol) + cur = getattr(cur, "_inner", None) + return policies + + def source_scope(self) -> Optional[dict[str, Any]]: + """Identify the underlying API endpoint and resource query, or None if unavailable.""" + cur: Any = self.verifier + seen: set[int] = set() + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + inner = getattr(cur, "_inner", None) + if inner is None: + break + cur = inner + base = ( + getattr(cur, "base_url", None) + or getattr(cur, "endpoint", None) + or getattr(cur, "url", None) + ) + if not isinstance(base, str) or not base.strip(): + return None + scope: dict[str, Any] = { + "substrate": self._substrate, + "endpoint": base.rstrip("/"), + "identity_path": self.identity_path, + } + for attr in ( + "records_path", + "records_key", + "resource_type", + "search_params", + "query", + "variables", + ): + val = getattr(cur, attr, None) + if val is not None: + scope[attr] = val + return scope + def read(self) -> Readback: try: verdict = self.verifier.verify(self.effect, self.before, self.context) @@ -883,7 +1023,9 @@ def read(self) -> Readback: if identity is _MISSING or identity is None: raise ReadFailed("the record carries no identity") fields = {f: _dotted(rec, f) for f in self.fields} - if any(v is _MISSING for v in fields.values()): + if any( + v is _MISSING or (self._projected and v is None) for v in fields.values() + ): raise ReadFailed("the record lacks a declared field") if self.version_path: version = _dotted(rec, self.version_path) @@ -903,6 +1045,8 @@ def read(self) -> Readback: ) if isinstance(holder, dict): holder.pop(parts[-1], None) + if _redacted(trimmed): + raise ReadFailed("the read-back carries redacted values") version = hashlib.sha256(_canonical(trimmed)).hexdigest() if _redacted([identity, fields, version]): raise ReadFailed("the read-back carries redacted values") diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index cfa817b22e..6b82deb9cb 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -40,6 +40,7 @@ def __init__(self, fields: Mapping[str, Any], version: Optional[str] = "1") -> N self.found = True self.fail = False self.identity: Any = "7" + self.source_scope: Any = {"system": "test-ehr", "resource": "Patient"} def read(self) -> Readback: if self.fail: @@ -66,6 +67,7 @@ def __init__(self) -> None: self.hidden = 0 self.logs: tuple[Any, ...] = ("create", "update", "delete") self.fail = False + self.stream_scope: Any = {"stream": "test-audit", "actor": "agent-1"} def add(self, id: str, kind: str, by: str, on: bool, stamp: float = 0.0) -> None: self.entries.append( @@ -630,6 +632,8 @@ def test_a_state_is_only_recheckable_with_the_same_host_secret( def test_read_failure_reasons_carry_no_upstream_text() -> None: class Leaky: + source_scope = {"system": "test-ehr", "resource": "Patient"} + def read(self) -> Readback: raise ReadFailed("GET https://sor.example/Patient/7 returned 500") @@ -727,3 +731,99 @@ def test_a_redacted_value_in_the_read_back_fails_the_read() -> None: ) with pytest.raises(ReadFailed): source.read() + + +def test_fhir_projection_omitted_field_none_fails_the_read() -> None: + """FHIR _flatten inserts None for missing paths; VerifierReadback must refuse it.""" + verifier = _Verifier() + verifier.record = {"id": "7", "meta": {"versionId": "1"}, "note": None} + source = VerifierReadback( + verifier, _Effect(), None, fields=["note"], version_path="meta.versionId" + ) + with pytest.raises(ReadFailed): + source.read() + + +def test_redacting_verifier_wrapper_and_masked_whole_record_are_refused() -> None: + from openadapt_flow.runtime.effects.adapter import ( + RedactingVerifier, + RedactionPolicy, + ) + from openadapt_flow.runtime.effects.rest import RestRecordVerifier + from tests._rest_read_contract_fixtures import mockmed_rest_read_kwargs + + class _Eff: + match = {"note": "A"} + + rest = RestRecordVerifier("https://sor.invalid", **mockmed_rest_read_kwargs()) + wrapped = RedactingVerifier(rest, RedactionPolicy(redact_fields=["secret"])) + with pytest.raises(ValueError, match="redacts evidence"): + VerifierReadback(wrapped, _Eff(), None) + + # Even if an un-annotated verifier returns a masked undeclared field, + # whole-record digesting must refuse it before hashing. + class _RestMasked(_Verifier): + substrate = "rest" + base_url = "https://sor.invalid" + + masked = _RestMasked() + masked.record = {"id": "7", "note": "A", "secret": "[redacted]"} + source = VerifierReadback(masked, _Eff(), None, fields=["note"]) + with pytest.raises(ReadFailed, match="redacted"): + source.read() + + +def test_source_stream_actor_and_first_identity_bindings_are_enforced() -> None: + log = Log() + rec, state, sched = _setup(log, first_identity="7") + assert _run(state, rec, sched, log).outcome == "VERIFIED" + + # Mismatched first_identity at begin fails. + with pytest.raises(ReadFailed, match="first check"): + _setup(log, first_identity="999") + + # Different record source scope with identical local id/fields/version -> NOT_CHECKED. + other_rec = Record({"name.family": "Lovelace", "birthDate": "1815-12-10"}) + other_rec.source_scope = {"system": "other-tenant-ehr", "resource": "Patient"} + out = _run(state, other_rec, sched, log) + assert out.outcome == "NOT_CHECKED" and "record source" in out.reason + + # Unavailable source binding -> ReadFailed on begin, NOT_CHECKED on recheck. + unbound_rec = Record({"name.family": "Lovelace", "birthDate": "1815-12-10"}) + unbound_rec.source_scope = None + with pytest.raises(ReadFailed, match="source binding"): + begin(unbound_rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + assert _run(state, unbound_rec, sched, log).outcome == "NOT_CHECKED" + + # Different log stream/actor with identical checkpoint -> NOT_CHECKED. + other_log = Log() + other_log.stream_scope = {"stream": "other-audit", "actor": "agent-2"} + out = _run(state, rec, sched, other_log) + assert out.outcome == "NOT_CHECKED" and "log stream" in out.reason + + # Unavailable log stream binding -> ReadFailed on begin, NOT_CHECKED on recheck. + unbound_log = Log() + unbound_log.stream_scope = None + with pytest.raises(ReadFailed, match="stream and actor"): + begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5, log=unbound_log) + assert _run(state, rec, sched, unbound_log).outcome == "NOT_CHECKED" + + +def test_incomplete_log_returns_not_checked_even_when_fields_changed_or_missing() -> ( + None +): + log = Log() + rec, state, sched = _setup(log) + log.reach = False + rec.fields["birthDate"] = "1815-12-11" + out = _run(state, rec, sched, log) + assert out.outcome == "NOT_CHECKED" and "checkpoint" in out.reason + + rec.found = False + out2 = _run(state, rec, sched, log) + assert out2.outcome == "NOT_CHECKED" and "checkpoint" in out2.reason + + # A proven caller mutation in the available page still refutes immediately. + log.add("bad1", "delete", "self", False) + out3 = _run(state, rec, sched, log) + assert out3.outcome == "REFUTED" From 37581850d95572a38cc3db17d293f8ad956b5d37 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:31:06 -0500 Subject: [PATCH 6/9] fix(verify): require reader account scope, original first_identity, and complete log stream/actor --- .../runtime/effects/api_recheck.py | 89 +++++++-- packages/flow/tests/test_api_recheck.py | 171 ++++++++++++++++-- 2 files changed, 233 insertions(+), 27 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index 200a9d102f..a4c8ad80d7 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -405,6 +405,24 @@ def _source_binding(obj: Any, attr: str) -> Any: return raw +def _nonempty_str(val: Any) -> bool: + return isinstance(val, str) and bool(val.strip()) + + +def _valid_source_scope(scope: Any) -> bool: + return isinstance(scope, Mapping) and any( + _nonempty_str(scope.get(k)) for k in ("account", "tenant", "principal") + ) + + +def _valid_log_scope(scope: Any) -> bool: + return ( + isinstance(scope, Mapping) + and _nonempty_str(scope.get("stream")) + and _nonempty_str(scope.get("actor")) + ) + + def begin( record: RecordSource, *, @@ -421,8 +439,9 @@ def begin( ``target``: the record's reference (``Patient/123``); bound, never re-read from the state. ``first_outcome``: the first check's outcome; a recheck of anything but ``VERIFIED`` stays ``NOT_CHECKED``. - ``first_identity``: optional record id observed by the first check; when - supplied, the baseline read must land on the same record id. + ``first_identity``: record id observed by the first check; required when + ``first_outcome == "VERIFIED"``, and the baseline read must land on the + same record id. ``own_events``: ``{entry id: operation}`` for the write's own log entries, which the first check already judged; they may land after the checkpoint while the log lags. They are exempt only when the log @@ -430,22 +449,27 @@ def begin( The log checkpoint is taken before the read, so an entry between the two reads shows up in the window rather than in the baseline. Raises - :class:`ReadFailed` when either source can't be read, lacks a source or - stream/actor binding, or the record is not there (a baseline of "absent" - would verify a deletion), and ``ValueError`` for a window that isn't a - positive number of seconds up to :data:`MAX_WINDOW_S` or for malformed - events. + :class:`ReadFailed` when either source can't be read, lacks a complete + account/source or stream-and-actor binding, lacks ``first_identity`` for a + ``VERIFIED`` first check, or the record is not there (a baseline of + "absent" would verify a deletion), and ``ValueError`` for a window that + isn't a positive number of seconds up to :data:`MAX_WINDOW_S` or for + malformed events. """ if not _window_ok(window_s): raise ValueError("the recheck window must be a positive number of seconds") own = _events({} if own_events is None else own_events) + if str(first_outcome) == "VERIFIED" and first_identity is None: + raise ReadFailed( + "the first check's observed record identity is required for a VERIFIED recheck" + ) source_scope = _source_binding(record, "source_scope") - if source_scope is None: - raise ReadFailed("the record source carries no source binding") + if not _valid_source_scope(source_scope): + raise ReadFailed("the record source carries no account/tenant source binding") log_scope = None if log is None else _source_binding(log, "stream_scope") - if log is not None and log_scope is None: - raise ReadFailed("the log source carries no stream and actor binding") + if log is not None and not _valid_log_scope(log_scope): + raise ReadFailed("the log source must bind both a non-empty stream and actor") salt = secrets.token_bytes(32) key = _key(salt) checkpoint = None if log is None else dict(log.checkpoint()) @@ -636,9 +660,11 @@ def recheck( at=started, ) source_scope = _source_binding(record, "source_scope") - if source_scope is None: + if not _valid_source_scope(source_scope): return _not_checked( - "the record source carries no source binding", state, at=started + "the record source carries no account/tenant source binding", + state, + at=started, ) try: source_mac = _mac(key, "source", _canonical(source_scope).decode("ascii")) @@ -654,9 +680,11 @@ def recheck( ) if log is not None: log_scope = _source_binding(log, "stream_scope") - if log_scope is None: + if not _valid_log_scope(log_scope): return _not_checked( - "the log source carries no stream and actor binding", state, at=started + "the log source must bind both a non-empty stream and actor", + state, + at=started, ) try: log_scope_mac = _mac( @@ -973,7 +1001,14 @@ def _redaction_policies(verifier: Any) -> list[Any]: return policies def source_scope(self) -> Optional[dict[str, Any]]: - """Identify the underlying API endpoint and resource query, or None if unavailable.""" + """Identify the underlying API endpoint, account/tenant principal, and query. + + Returns ``None`` when the actual reader cannot establish both its + endpoint and a stable, non-secret tenant or principal identifier + (``account_scope``, ``tenant_id``, ``principal_id``, ``account_id``, or + ``token_source.client_id``). Secret tokens and auth headers are never + included. + """ cur: Any = self.verifier seen: set[int] = set() while cur is not None and id(cur) not in seen: @@ -989,9 +1024,31 @@ def source_scope(self) -> Optional[dict[str, Any]]: ) if not isinstance(base, str) or not base.strip(): return None + account: Optional[str] = None + for attr in ("account_scope", "tenant_id", "principal_id", "account_id"): + cand = getattr(cur, attr, None) + if isinstance(cand, str) and cand.strip(): + account = cand.strip() + break + if account is None: + token_src = getattr(cur, "token_source", None) + if token_src is not None: + for attr in ( + "account_scope", + "tenant_id", + "principal_id", + "client_id", + ): + cand = getattr(token_src, attr, None) + if isinstance(cand, str) and cand.strip(): + account = cand.strip() + break + if account is None: + return None scope: dict[str, Any] = { "substrate": self._substrate, "endpoint": base.rstrip("/"), + "account": account, "identity_path": self.identity_path, } for attr in ( diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index 6b82deb9cb..f22f9a5f71 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -40,7 +40,11 @@ def __init__(self, fields: Mapping[str, Any], version: Optional[str] = "1") -> N self.found = True self.fail = False self.identity: Any = "7" - self.source_scope: Any = {"system": "test-ehr", "resource": "Patient"} + self.source_scope: Any = { + "system": "test-ehr", + "account": "tenant-a", + "resource": "Patient", + } def read(self) -> Readback: if self.fail: @@ -99,6 +103,7 @@ def _setup(log: Optional[Log] = None, **kw: Any): first_outcome=kw.pop("first_outcome", "VERIFIED"), window_s=kw.pop("window_s", 120), log=log, + first_identity=kw.pop("first_identity", "7"), now=T0, **kw, ) @@ -143,7 +148,14 @@ def test_state_and_schedule_hold_no_values() -> None: log = Log() rec = Record({"name.family": "Lovelace-Q", "birthDate": "1815-12-10 (q)"}) rec.identity = "Patient-Qz" - state = begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5, log=log) + state = begin( + rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="Patient-Qz", + window_s=5, + log=log, + ) sched = schedule(state) text = json.dumps(state) + json.dumps(sched) for value in ("Lovelace-Q", "1815-12-10 (q)", "Patient-Qz", TARGET): @@ -195,7 +207,13 @@ def test_a_to_b_to_a_with_no_version_is_caught_by_the_log() -> None: log = Log() rec = Record({"birthDate": "1815-12-10"}, version=None) state = begin( - rec, target=TARGET, first_outcome="VERIFIED", window_s=60, log=log, now=T0 + rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=60, + log=log, + now=T0, ) log.add("u2", "update", "other", True) log.add("u3", "update", "other", True) @@ -364,6 +382,7 @@ def test_rest_readback_over_http_verifies_then_refutes_a_late_edit() -> None: base_url, db, stop = serve() try: verifier = RestRecordVerifier(base_url, **mockmed_rest_read_kwargs()) + verifier.account_scope = "mockmed-local" before = verifier.capture_pre_state() written = db.add("p1", "Triage", "BP 120/80", key="k1") effect = Effect( @@ -376,7 +395,12 @@ def test_rest_readback_over_http_verifies_then_refutes_a_late_edit() -> None: verifier, effect, before, fields=["patient_id", "note"] ) state = begin( - source, target="encounter/1", first_outcome="VERIFIED", window_s=1, now=T0 + source, + target="encounter/1", + first_outcome="VERIFIED", + first_identity=written["id"], + window_s=1, + now=T0, ) sha = schedule(state)["state_sha256"] later = T0 + timedelta(seconds=5) @@ -408,6 +432,7 @@ def test_rest_readback_over_http_catches_an_undeclared_field_change() -> None: base_url, db, stop = serve() try: verifier = RestRecordVerifier(base_url, **mockmed_rest_read_kwargs()) + verifier.account_scope = "mockmed-local" before = verifier.capture_pre_state() written = db.add("p1", "Triage", "BP 120/80", key="k1") effect = Effect( @@ -418,7 +443,12 @@ def test_rest_readback_over_http_catches_an_undeclared_field_change() -> None: ) source = VerifierReadback(verifier, effect, before) state = begin( - source, target="encounter/1", first_outcome="VERIFIED", window_s=1, now=T0 + source, + target="encounter/1", + first_outcome="VERIFIED", + first_identity=written["id"], + window_s=1, + now=T0, ) with db._lock: written["type"] = "Consult" @@ -504,14 +534,26 @@ def test_begin_refuses_an_absent_record() -> None: rec = Record({"birthDate": "1815-12-10"}) rec.found = False with pytest.raises(ReadFailed): - begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + begin( + rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + ) def test_begin_refuses_a_read_back_with_no_identity() -> None: rec = Record({"birthDate": "1815-12-10"}) rec.identity = None with pytest.raises(ReadFailed): - begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + begin( + rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + ) def test_a_read_back_landing_on_another_record_is_not_checked() -> None: @@ -557,6 +599,7 @@ def test_a_value_with_no_exact_json_form_fails_the_read() -> None: Record({"amount": Decimal("1.0")}), target=TARGET, first_outcome="VERIFIED", + first_identity="7", window_s=5, ) rec, state, sched = _setup() @@ -632,7 +675,11 @@ def test_a_state_is_only_recheckable_with_the_same_host_secret( def test_read_failure_reasons_carry_no_upstream_text() -> None: class Leaky: - source_scope = {"system": "test-ehr", "resource": "Patient"} + source_scope = { + "system": "test-ehr", + "account": "tenant-a", + "resource": "Patient", + } def read(self) -> Readback: raise ReadFailed("GET https://sor.example/Patient/7 returned 500") @@ -784,7 +831,11 @@ def test_source_stream_actor_and_first_identity_bindings_are_enforced() -> None: # Different record source scope with identical local id/fields/version -> NOT_CHECKED. other_rec = Record({"name.family": "Lovelace", "birthDate": "1815-12-10"}) - other_rec.source_scope = {"system": "other-tenant-ehr", "resource": "Patient"} + other_rec.source_scope = { + "system": "test-ehr", + "account": "tenant-b", + "resource": "Patient", + } out = _run(state, other_rec, sched, log) assert out.outcome == "NOT_CHECKED" and "record source" in out.reason @@ -792,23 +843,121 @@ def test_source_stream_actor_and_first_identity_bindings_are_enforced() -> None: unbound_rec = Record({"name.family": "Lovelace", "birthDate": "1815-12-10"}) unbound_rec.source_scope = None with pytest.raises(ReadFailed, match="source binding"): - begin(unbound_rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + begin( + unbound_rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + ) assert _run(state, unbound_rec, sched, log).outcome == "NOT_CHECKED" + # Missing original observed identity for VERIFIED -> ReadFailed on begin. + with pytest.raises(ReadFailed, match="observed record identity is required"): + begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5) + # Different log stream/actor with identical checkpoint -> NOT_CHECKED. other_log = Log() other_log.stream_scope = {"stream": "other-audit", "actor": "agent-2"} out = _run(state, rec, sched, other_log) assert out.outcome == "NOT_CHECKED" and "log stream" in out.reason + # Log stream missing actor -> ReadFailed on begin, NOT_CHECKED on recheck. + actorless_log = Log() + actorless_log.stream_scope = {"stream": "test-audit"} + with pytest.raises(ReadFailed, match="stream and actor"): + begin( + rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + log=actorless_log, + ) + assert _run(state, rec, sched, actorless_log).outcome == "NOT_CHECKED" + # Unavailable log stream binding -> ReadFailed on begin, NOT_CHECKED on recheck. unbound_log = Log() unbound_log.stream_scope = None with pytest.raises(ReadFailed, match="stream and actor"): - begin(rec, target=TARGET, first_outcome="VERIFIED", window_s=5, log=unbound_log) + begin( + rec, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + log=unbound_log, + ) assert _run(state, rec, sched, unbound_log).outcome == "NOT_CHECKED" +def test_shared_endpoint_with_different_accounts_or_no_account_scope_is_refused() -> ( + None +): + class _AccountVerifier(_Verifier): + substrate = "fhir" + base_url = "https://shared-fhir.invalid/R4" + + def __init__(self, account: Optional[str]) -> None: + super().__init__() + self.record = {"id": "7", "meta": {"versionId": "1"}, "note": "A"} + if account is not None: + self.account_scope = account + + # Reader without account scope cannot establish source_scope -> begin refuses. + no_acct = VerifierReadback( + _AccountVerifier(None), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + assert no_acct.source_scope() is None + with pytest.raises(ReadFailed, match="account/tenant"): + begin( + no_acct, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + now=T0, + ) + + # Same shared endpoint, different account/principal -> NOT_CHECKED. + src_a = VerifierReadback( + _AccountVerifier("acct-alpha"), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + src_b = VerifierReadback( + _AccountVerifier("acct-beta"), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + state = begin( + src_a, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + now=T0, + ) + sha = schedule(state)["state_sha256"] + later = T0 + timedelta(seconds=10) + assert ( + recheck( + state, src_a, target=TARGET, expected_state_sha256=sha, now=later + ).outcome + == "VERIFIED" + ) + out_b = recheck(state, src_b, target=TARGET, expected_state_sha256=sha, now=later) + assert out_b.outcome == "NOT_CHECKED" and "record source" in out_b.reason + + def test_incomplete_log_returns_not_checked_even_when_fields_changed_or_missing() -> ( None ): From 853cc23d6d747099af60709c249c6c772cc4c3de Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:42:49 -0500 Subject: [PATCH 7/9] fix(verify): bind SMART client_id with authorization server identifier in source_scope --- .../runtime/effects/api_recheck.py | 26 ++++-- packages/flow/tests/test_api_recheck.py | 93 +++++++++++++++++++ 2 files changed, 113 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index a4c8ad80d7..23b3062a6a 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -1025,6 +1025,7 @@ def source_scope(self) -> Optional[dict[str, Any]]: if not isinstance(base, str) or not base.strip(): return None account: Optional[str] = None + auth_server: Optional[str] = None for attr in ("account_scope", "tenant_id", "principal_id", "account_id"): cand = getattr(cur, attr, None) if isinstance(cand, str) and cand.strip(): @@ -1033,16 +1034,27 @@ def source_scope(self) -> Optional[dict[str, Any]]: if account is None: token_src = getattr(cur, "token_source", None) if token_src is not None: - for attr in ( - "account_scope", - "tenant_id", - "principal_id", - "client_id", - ): + for attr in ("account_scope", "tenant_id", "principal_id"): cand = getattr(token_src, attr, None) if isinstance(cand, str) and cand.strip(): account = cand.strip() break + if account is None: + cid = getattr(token_src, "client_id", None) + if isinstance(cid, str) and cid.strip(): + for srv_attr in ( + "token_url", + "_token_url", + "token_endpoint", + "issuer", + ): + srv = getattr(token_src, srv_attr, None) + if isinstance(srv, str) and srv.strip(): + auth_server = srv.strip().rstrip("/") + break + if auth_server is None: + return None + account = cid.strip() if account is None: return None scope: dict[str, Any] = { @@ -1051,6 +1063,8 @@ def source_scope(self) -> Optional[dict[str, Any]]: "account": account, "identity_path": self.identity_path, } + if auth_server is not None: + scope["auth_server"] = auth_server for attr in ( "records_path", "records_key", diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index f22f9a5f71..368c0f0f83 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -958,6 +958,99 @@ def __init__(self, account: Optional[str]) -> None: assert out_b.outcome == "NOT_CHECKED" and "record source" in out_b.reason +def test_smart_client_id_binds_authorization_server_and_allows_key_renewal() -> None: + class _SmartTokenSource: + def __init__( + self, client_id: str, token_url: Optional[str], kid: str = "k1" + ) -> None: + self.client_id = client_id + self._token_url = token_url + self.kid = kid + + class _SmartVerifier(_Verifier): + substrate = "fhir" + base_url = "https://shared-fhir.invalid/R4" + + def __init__(self, token_source: _SmartTokenSource) -> None: + super().__init__() + self.token_source = token_source + self.record = {"id": "7", "meta": {"versionId": "1"}, "note": "A"} + + # Missing authorization server identifier -> declined. + no_auth = VerifierReadback( + _SmartVerifier(_SmartTokenSource("shared-client", None)), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + assert no_auth.source_scope() is None + with pytest.raises(ReadFailed, match="account/tenant"): + begin( + no_auth, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + now=T0, + ) + + # Same client_id at authority A, then token/signing-key renewal at authority A -> VERIFIED. + src_a1 = VerifierReadback( + _SmartVerifier( + _SmartTokenSource( + "shared-client", "https://auth-a.invalid/oauth2/token", kid="k1" + ) + ), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + src_a2_renewed = VerifierReadback( + _SmartVerifier( + _SmartTokenSource( + "shared-client", "https://auth-a.invalid/oauth2/token", kid="k2" + ) + ), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + # Same client_id at authority B -> NOT_CHECKED. + src_b = VerifierReadback( + _SmartVerifier( + _SmartTokenSource( + "shared-client", "https://auth-b.invalid/oauth2/token", kid="k1" + ) + ), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + + state = begin( + src_a1, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + now=T0, + ) + sha = schedule(state)["state_sha256"] + later = T0 + timedelta(seconds=10) + assert ( + recheck( + state, src_a2_renewed, target=TARGET, expected_state_sha256=sha, now=later + ).outcome + == "VERIFIED" + ) + out_b = recheck(state, src_b, target=TARGET, expected_state_sha256=sha, now=later) + assert out_b.outcome == "NOT_CHECKED" and "record source" in out_b.reason + + def test_incomplete_log_returns_not_checked_even_when_fields_changed_or_missing() -> ( None ): From 3ad47e25f14eedecb00c140d88de97d61804a063 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:45:22 -0500 Subject: [PATCH 8/9] fix(verify): compare the exact SMART token endpoint, not a trimmed one --- .../runtime/effects/api_recheck.py | 8 ++++++-- packages/flow/tests/test_api_recheck.py | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index 23b3062a6a..f7555cc022 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -1042,6 +1042,10 @@ def source_scope(self) -> Optional[dict[str, Any]]: if account is None: cid = getattr(token_src, "client_id", None) if isinstance(cid, str) and cid.strip(): + # The exact strings the token source signs as the + # assertion audience and sends the request to: no + # trimming, so ``/token`` and ``/token/`` (which can + # be different authorization endpoints) differ. for srv_attr in ( "token_url", "_token_url", @@ -1050,11 +1054,11 @@ def source_scope(self) -> Optional[dict[str, Any]]: ): srv = getattr(token_src, srv_attr, None) if isinstance(srv, str) and srv.strip(): - auth_server = srv.strip().rstrip("/") + auth_server = srv break if auth_server is None: return None - account = cid.strip() + account = cid if account is None: return None scope: dict[str, Any] = { diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index 368c0f0f83..2f29665b96 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -1050,6 +1050,25 @@ def __init__(self, token_source: _SmartTokenSource) -> None: out_b = recheck(state, src_b, target=TARGET, expected_state_sha256=sha, now=later) assert out_b.outcome == "NOT_CHECKED" and "record source" in out_b.reason + # The same authority host with a trailing slash is a different token + # endpoint and JWT audience -> NOT_CHECKED, not merged. + src_a_slash = VerifierReadback( + _SmartVerifier( + _SmartTokenSource( + "shared-client", "https://auth-a.invalid/oauth2/token/", kid="k1" + ) + ), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + assert src_a_slash.source_scope() != src_a1.source_scope() + out_slash = recheck( + state, src_a_slash, target=TARGET, expected_state_sha256=sha, now=later + ) + assert out_slash.outcome == "NOT_CHECKED" and "record source" in out_slash.reason + def test_incomplete_log_returns_not_checked_even_when_fields_changed_or_missing() -> ( None From 3224fdf1680cac70129278af053a7fa9623d12f5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:53:27 -0500 Subject: [PATCH 9/9] fix(verify): bind a discovered SMART token endpoint in a new-process recheck --- .../runtime/effects/api_recheck.py | 14 +++- .../runtime/effects/smart_auth.py | 14 ++++ packages/flow/tests/test_api_recheck.py | 69 +++++++++++++++++++ 3 files changed, 96 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py index f7555cc022..0d595ba680 100644 --- a/packages/flow/openadapt_flow/runtime/effects/api_recheck.py +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -1046,16 +1046,28 @@ def source_scope(self) -> Optional[dict[str, Any]]: # assertion audience and sends the request to: no # trimming, so ``/token`` and ``/token/`` (which can # be different authorization endpoints) differ. + # A discovering source (no configured token_url) + # learns its endpoint only on first use; ask it, so + # a recheck in a new process isn't declined. + resolve = getattr(token_src, "token_endpoint", None) + if callable(resolve): + try: + srv = resolve() + except Exception: # noqa: BLE001 - decline below + srv = None + if isinstance(srv, str) and srv.strip(): + auth_server = srv for srv_attr in ( "token_url", "_token_url", "token_endpoint", "issuer", ): + if auth_server is not None: + break srv = getattr(token_src, srv_attr, None) if isinstance(srv, str) and srv.strip(): auth_server = srv - break if auth_server is None: return None account = cid diff --git a/packages/flow/openadapt_flow/runtime/effects/smart_auth.py b/packages/flow/openadapt_flow/runtime/effects/smart_auth.py index 4c3f608241..165c2357ca 100644 --- a/packages/flow/openadapt_flow/runtime/effects/smart_auth.py +++ b/packages/flow/openadapt_flow/runtime/effects/smart_auth.py @@ -410,6 +410,20 @@ def access_token(self) -> Optional[str]: self._renew_at = self._clock() + expires_in - margin return token + def token_endpoint(self) -> str: + """The exact token URL this source signs its assertions for. + + The configured ``token_url``, or the one ``smart-configuration`` + names, discovered once (no token is requested). A delayed recheck in + a new process needs it before any token was asked for. Raises + :class:`SmartTokenError` when discovery fails. + """ + + with self._lock: + if self._token_url is None: + self._token_url = self._discover() + return self._token_url + def invalidate(self) -> None: with self._lock: self._token = None diff --git a/packages/flow/tests/test_api_recheck.py b/packages/flow/tests/test_api_recheck.py index 2f29665b96..27317fa17a 100644 --- a/packages/flow/tests/test_api_recheck.py +++ b/packages/flow/tests/test_api_recheck.py @@ -1070,6 +1070,75 @@ def __init__(self, token_source: _SmartTokenSource) -> None: assert out_slash.outcome == "NOT_CHECKED" and "record source" in out_slash.reason +def test_discovered_smart_endpoint_binds_in_a_new_process() -> None: + """A delayed recheck runs in a new process, before any token request: + the discovered token endpoint must still bind (and still differ).""" + from openadapt_flow.runtime.effects.smart_auth import ( + SmartBackendTokenSource, + SmartTokenError, + ) + + class _Discovering(SmartBackendTokenSource): + def __init__(self, discovered: Optional[str]) -> None: + super().__init__( + client_id="shared-client", + scope="system/Patient.read", + key=None, + kid="k1", + alg="RS384", + fhir_base_url="https://shared-fhir.invalid/R4", + ) + self.discovered = discovered + self.discoveries = 0 + + def _discover(self) -> str: + self.discoveries += 1 + if self.discovered is None: + raise SmartTokenError("smart-configuration request failed") + return self.discovered + + class _SmartVerifier(_Verifier): + substrate = "fhir" + base_url = "https://shared-fhir.invalid/R4" + + def __init__(self, token_source: Any) -> None: + super().__init__() + self.token_source = token_source + self.record = {"id": "7", "meta": {"versionId": "1"}, "note": "A"} + + def readback(discovered: Optional[str]) -> VerifierReadback: + return VerifierReadback( + _SmartVerifier(_Discovering(discovered)), + _Effect(), + None, + fields=["note"], + version_path="meta.versionId", + ) + + url = "https://auth-a.invalid/oauth2/token" + first = readback(url) + state = begin( + first, + target=TARGET, + first_outcome="VERIFIED", + first_identity="7", + window_s=5, + now=T0, + ) + sha = schedule(state)["state_sha256"] + later = T0 + timedelta(seconds=10) + fresh = readback(url) # new process: nothing discovered yet + assert fresh.verifier.token_source._token_url is None + out = recheck(state, fresh, target=TARGET, expected_state_sha256=sha, now=later) + assert out.outcome == "VERIFIED" + assert fresh.verifier.token_source.discoveries == 1 + for other in (url + "/", "https://auth-b.invalid/oauth2/token", None): + out = recheck( + state, readback(other), target=TARGET, expected_state_sha256=sha, now=later + ) + assert out.outcome == "NOT_CHECKED" and "source" in out.reason + + def test_incomplete_log_returns_not_checked_even_when_fields_changed_or_missing() -> ( None ):