diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 306c5c9da3..9317d3f12a 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -185,6 +185,7 @@ improvising or retrying when something is off. | Verify a write to an API or SaaS system with no database to diff: `openadapt proxy --api systems.tx.yaml` serves `api_read` and `api_write` beside the SQL tools on the same MCP endpoint and keeps the API credentials out of the agent's environment. Each write is sent once under a key derived from the task and the record, never the payload. A retry returns the first result, a regenerated payload is refused, and a crash between the send and the ledger is recovered by finding the write. The key goes out as `Idempotency-Key` where the API honors one, or as a FHIR conditional create. The record is then read back and judged with the tx codecs, including `null_empty`. The system's own event or audit log is read from an id-placed cursor, and the write's own event must appear with no other resource changed by the same credentials. A FHIR `AuditEvent` search, an event stream and a REST activity feed are all declared as data in the tx file. Every outcome gets a `record/run/v1` receipt. Scope is the resource and the actor: changes by other callers, and changes the log doesn't record, aren't checked. A whole-record (`replace`) update or a delete over another caller's edit is refused by the server when the route declares a `precondition` (`If-Match` from the read's `ETag` or a version field) with enforcement evidence: a probe recorded in the pack, or one the adapter runs once per route. Without a precondition it is never `VERIFIED`, only `COMPLETED_UNVERIFIED` (`unconditional_write`; `precondition_unproven` without evidence), and `api_write` reports it as an error. A retry that returns a stored result is capped the same way | [#2437](https://github.com/OpenAdaptAI/OpenAdapt/pull/2437), stacked on [#2428](https://github.com/OpenAdaptAI/OpenAdapt/pull/2428) | Real apps (Medplum 5.2.8 `AuditEvent`, Gitea 1.24.6 activity feed, synthetic data): 0 of 400 clean writes stopped on each; Medplum rerun with its `If-Match` probe recorded in the pack, 400 of 400 `VERIFIED`. Every planted fault the log exposes was stopped: wrong value, duplicate, partial write and same-actor collateral change, 50 of 50 per class, except that on Medplum a duplicate update no longer lands (the server refused all 50 second PUTs with 412). Known misses: a collateral title edit on Gitea, which its feed doesn't record (0 of 50 stopped), and another caller's change on either system (0 of 50). 50 of 50 regenerated-payload retries were refused on each. Stripe not run (no test-mode key) | [API_VERIFICATION.md](packages/flow/docs/API_VERIFICATION.md), [benchmark/api_scoped](packages/flow/benchmark/api_scoped/RESULTS.md), `openadapt_flow/txplan/scoped.py`, `openadapt_flow/txplan/audit.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 (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 ae1ca3e8ca..d46a8505a5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -645,6 +645,7 @@ improvising or retrying when something is off. | Verify a write to an API or SaaS system with no database to diff: `openadapt proxy --api systems.tx.yaml` serves `api_read` and `api_write` beside the SQL tools on the same MCP endpoint and keeps the API credentials out of the agent's environment. Each write is sent once under a key derived from the task and the record, never the payload. A retry returns the first result, a regenerated payload is refused, and a crash between the send and the ledger is recovered by finding the write. The key goes out as `Idempotency-Key` where the API honors one, or as a FHIR conditional create. The record is then read back and judged with the tx codecs, including `null_empty`. The system's own event or audit log is read from an id-placed cursor, and the write's own event must appear with no other resource changed by the same credentials. A FHIR `AuditEvent` search, an event stream and a REST activity feed are all declared as data in the tx file. Every outcome gets a `record/run/v1` receipt. Scope is the resource and the actor: changes by other callers, and changes the log doesn't record, aren't checked. A whole-record (`replace`) update or a delete over another caller's edit is refused by the server when the route declares a `precondition` (`If-Match` from the read's `ETag` or a version field) with enforcement evidence: a probe recorded in the pack, or one the adapter runs once per route. Without a precondition it is never `VERIFIED`, only `COMPLETED_UNVERIFIED` (`unconditional_write`; `precondition_unproven` without evidence), and `api_write` reports it as an error. A retry that returns a stored result is capped the same way | [#2437](https://github.com/OpenAdaptAI/OpenAdapt/pull/2437), stacked on [#2428](https://github.com/OpenAdaptAI/OpenAdapt/pull/2428) | Real apps (Medplum 5.2.8 `AuditEvent`, Gitea 1.24.6 activity feed, synthetic data): 0 of 400 clean writes stopped on each; Medplum rerun with its `If-Match` probe recorded in the pack, 400 of 400 `VERIFIED`. Every planted fault the log exposes was stopped: wrong value, duplicate, partial write and same-actor collateral change, 50 of 50 per class, except that on Medplum a duplicate update no longer lands (the server refused all 50 second PUTs with 412). Known misses: a collateral title edit on Gitea, which its feed doesn't record (0 of 50 stopped), and another caller's change on either system (0 of 50). 50 of 50 regenerated-payload retries were refused on each. Stripe not run (no test-mode key) | [API_VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/API_VERIFICATION.md), [benchmark/api_scoped](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/api_scoped/RESULTS.md), `openadapt_flow/txplan/scoped.py`, `openadapt_flow/txplan/audit.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 (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 new file mode 100644 index 0000000000..0d595ba680 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/effects/api_recheck.py @@ -0,0 +1,1167 @@ +"""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 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``: 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 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 +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``. + +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``. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import math +import re +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/v2" +#: Exactly these keys: nothing rides along unbound. +STATE_KEYS: tuple[str, ...] = ( + "schema_version", + "salt", + "key_check", + "target", + "source_mac", + "log_scope_mac", + "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. +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" +#: 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] = { + "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", +} + +_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. + + Messages are fixed sentences: they never carry a URL, a record value or + an upstream error text, because a recheck result is serialized.""" + + +# -- sources ------------------------------------------------------------------- + + +@dataclass(frozen=True) +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), 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: Any = None + identity: Any = 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 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. A log that + records nothing gives no ``activity_log`` basis. + """ + + 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, 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: + """Every entry after ``checkpoint``, newest first or in log order. + Raises :class:`ReadFailed` when the log can't be read.""" + ... + + +# -- 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=(",", ":"), allow_nan=False + ).encode() + + +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( + 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 -------------------------------------------------------------------- + + +@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 + #: When the recheck's reads started; ``rechecked_at`` is when they ended. + observed_from: Optional[str] = None + + @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, + "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), + } + + 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: + """``state`` only once :func:`state_problem` has passed it.""" + + basis: list[str] = [] + 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["read_at"]) if state is not None else None, + rechecked_at=at, + 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 _source_binding(obj: Any, attr: str) -> Any: + raw = getattr(obj, attr, None) + if callable(raw): + return raw() + 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, + *, + target: str, + first_outcome: str, + 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. + + ``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``: 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 + 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, 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 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 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()) + 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: + 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) + 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(), + "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), + "due_at": due_at(read_at, float(window_s)), + "identity_mac": identity_mac, + "fields_mac": fields_mac, + "version_mac": version_mac, + "log": checkpoint, + "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. 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["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) + 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) + ): + 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: + 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: + 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 + + +# -- recheck ------------------------------------------------------------------- + + +def recheck( + state: Mapping[str, Any], + record: RecordSource, + *, + target: str, + expected_state_sha256: str, + log: Optional[ActivityLog] = None, + 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_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. + """ + + 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=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=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=started + ) + if state["first_outcome"] != "VERIFIED": + return _not_checked( + "the first check was not VERIFIED; a recheck can't raise it", + state, + at=started, + ) + 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=started, + ) + source_scope = _source_binding(record, "source_scope") + if not _valid_source_scope(source_scope): + return _not_checked( + "the record source carries no account/tenant 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 not _valid_log_scope(log_scope): + return _not_checked( + "the log source must bind both a non-empty stream and actor", + 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) + 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. + try: + seen = record.read() + if not isinstance(seen, Readback): + raise ReadFailed("the record source returned no read-back") + 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"])) + 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 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)) + + def result(outcome: Outcome, reason: str) -> RecheckResult: + return RecheckResult( + outcome, + reason, + basis=basis, + read_back_at=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, + 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 = contradicted = False + if window is not None: + own = set(state["own_events"]) + for entry in window.entries: + kind = entry.kind if entry.kind in _ALL_OPS else None + if entry.kind == "read": + continue + 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 by == "self" and kind is not None: + self_on_target = True + else: + unknown_on_target = True + 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 by == "unknown": + unknown_elsewhere = True + + # 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 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 + 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 does not " + "attribute the change to this caller", + ) + if not seen.found: + 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" + ) + if contradicted: + return result( + "NOT_CHECKED", + "an exempted log entry is attributed to another author or operation", + ) + 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" + ) + 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"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 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 _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. + + 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 + 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__( + self, + verifier: Any, + effect: Any, + before: Any, + *, + fields: Optional[Sequence[str]] = None, + version_path: Optional[str] = None, + identity_path: str = "id", + 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.identity_path = identity_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") + self._substrate = substrate + self._projected = substrate in _PROJECTED_SUBSTRATES + if version_path is None and ( + self._projected or tuple(getattr(verifier, "drop_fields", ())) + ): + raise ValueError( + "a projected read needs a named server version (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, 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: + 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 + 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(): + 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"): + 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(): + # 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. + # 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 + if auth_server is None: + return None + account = cid + if account is None: + return None + scope: dict[str, Any] = { + "substrate": self._substrate, + "endpoint": base.rstrip("/"), + "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", + "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) + 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) + 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("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 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) + 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("the record has no named version") + else: + 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 = ( + _dotted(trimmed, ".".join(parts[:-1])) if parts[:-1] else trimmed + ) + 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") + return Readback(found=True, fields=fields, version=version, identity=identity) + + +__all__ = [ + "ALWAYS_NOT_COVERED", + "ActivityLog", + "API_SUBSTRATES", + "BASIS_API", + "BASIS_LOG", + "LogEntry", + "LogRead", + "MAX_WINDOW_S", + "NO_LOG_NOT_COVERED", + "Outcome", + "ReadFailed", + "Readback", + "RecheckResult", + "RecordSource", + "SCHEMA", + "TO_LATE", + "TO_VERDICT", + "VerifierReadback", + "begin", + "recheck", + "schedule", + "state_problem", + "state_sha256", +] 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 new file mode 100644 index 0000000000..27317fa17a --- /dev/null +++ b/packages/flow/tests/test_api_recheck.py @@ -0,0 +1,1159 @@ +"""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 + self.identity: Any = "7" + self.source_scope: Any = { + "system": "test-ehr", + "account": "tenant-a", + "resource": "Patient", + } + + 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, + identity=self.identity, + ) + + +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 + 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( + {"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, + first_identity=kw.pop("first_identity", "7"), + 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: + 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", + 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): + 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: + 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 "no single record" 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", + first_identity="7", + 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" + 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_events={"mine": "create"}) + 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()) + verifier.account_scope = "mockmed-local" + 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", + first_identity=written["id"], + 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()) + verifier.account_scope = "mockmed-local" + 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", + first_identity=written["id"], + 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() + + +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() + + +# -- 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", + 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", + first_identity="7", + 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", + first_identity="7", + 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: + source_scope = { + "system": "test-ehr", + "account": "tenant-a", + "resource": "Patient", + } + + 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() + + +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": "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 + + # 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", + 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", + 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_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 + + # 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_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 +): + 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"