diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md b/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md new file mode 100644 index 0000000000..d4682fe469 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md @@ -0,0 +1 @@ +| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects; a run receipt says it has no per-read time). A run receipt never says `VERIFIED` below level 3. Receipts without the block still verify. A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md b/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md index c6d389a0c5..e2b05a24e5 100644 --- a/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md +++ b/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md @@ -1 +1 @@ -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. An app whose calls all go to one RPC endpoint gets a lens whose read and write carry their arguments in the body (`body_template`), whose record is found at a path such as `result.0`, and whose 2xx answer with an `error` member counts as a failed call; induction learns it from a read that returns the named records and a write that a later read confirms, and reads back the fields the trace itself read. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with no automatic undo, and its result is `UNCERTAIN` unless the read-back is a cache-bypassed API read whose record version is exactly one past the before-image's, which is `CONFIRMED` with basis `system_api`. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. An app whose calls all go to one RPC endpoint gets a lens whose read and write carry their arguments in the body (`body_template`), whose record is found at a path such as `result.0`, and whose 2xx answer with an `error` member counts as a failed call; induction learns it from a read that returns the named records and a write that a later read confirms, and reads back the fields the trace itself read. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index c75eb8811d..2e5e7f9b69 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -73,6 +73,19 @@ ### Features +- One verification ladder on every path. `openadapt_types.check_level` is + the only source of check levels; `verify-run`, the runtime's report and + the `tx` engine derive their tables from it and name each check with one + receipt word: `VERIFIED` (levels 3 and 4 only, always with a basis: + `separate_session`, `system_api`, `activity_log`, `db_frame` or + `owned_connection`), `SHOWN`, `CONFIRMED`, `ATTESTED` or `RECORDED`. + Run receipts (`record/run/v1`), `verify-run` and `tx` receipts carry an + additive `evidence_scope` block + (`openadapt.evidence-scope/v1`) that states the level, basis, wire scope, + read-back time, recheck window and what the check did not cover. Receipts + without the block still verify. A run receipt whose report shows a save + checked below level 3 is `UNKNOWN` (`below_verified_level`), never + `VERIFIED`; no built-in profile produces such a run. - Links, tabs and menu items can be steps (`openadapt_flow.gui.steps`). Each demonstrated click gets its role from what the backend counted: a commit when it wrote, a navigation when the screen changed with no write. A live @@ -160,6 +173,15 @@ minimized that carries a raw body. ### Fixes +- `verify-run` with `minimum_effect_strength: independent_session` now + verifies on a separate-session read (check level 3), as the runtime + already did. Before, the two disagreed and verify-run never verified on + it. The default minimum is unchanged (`independent_system_of_record`). +- The `tx` engine no longer caps every verdict at `UNCERTAIN` without a + SQLite row authority. A post-commit API read sent with cache-bypass + headers, showing no cache in its response, and whose record version is + exactly one past the before-image's is `CONFIRMED` with basis + `system_api`. Anything else stays `UNCERTAIN`. - `verify-run`: an effect list that is empty, or tiers that don't pair one to one with the effects, is `INDETERMINATE`, `unknown` and `unchecked`, not `CONFIRMED`, `present` and `independent_readback`. The receipt model already diff --git a/packages/flow/docs/RECEIPTS.md b/packages/flow/docs/RECEIPTS.md index 943a3a0e53..a72e8cb94c 100644 --- a/packages/flow/docs/RECEIPTS.md +++ b/packages/flow/docs/RECEIPTS.md @@ -32,7 +32,18 @@ changes the run's exit code and calls no model. (`read_back`, `same_screen` or `none`), and what it didn't check; - check counts; - a disclosure map: salted commitments to the program name, Flow version and - run id. + run id; +- an evidence scope (`evidence_scope`, `openadapt.evidence-scope/v1`): the + check level the weakest save reached, the receipt word (`VERIFIED` only at + level 3, a separate session, or level 4, the system of record, and then + with its basis; otherwise `SHOWN` or `RECORDED`), the wire the run watched, + and what the evidence did not cover. It always lists server-side async and + outbound effects, and, because a run report has no per-read time yet, + `read_back_time`. `VERIFIED` means the read-back showed the value when it + ran, not that it persisted. A run whose saves were checked below level 3 + gets `UNKNOWN` (`below_verified_level`), never `VERIFIED`. Receipts written + before this field, and a `VERIFIED` run whose report has no `readback` + block (it made no save), have no evidence scope and still verify. **A receipt and its public card never contain screenshots, typed values, URLs or page text.** Evidence files, screenshots included, appear only by diff --git a/packages/flow/docs/VERIFY_RUN.md b/packages/flow/docs/VERIFY_RUN.md index a0f8638479..3f69f1dd5c 100644 --- a/packages/flow/docs/VERIFY_RUN.md +++ b/packages/flow/docs/VERIFY_RUN.md @@ -848,10 +848,13 @@ skipping a table when the table allows it. | The same, but the executor approved its own write | `CONFIRMED` | `rejected_policy` | | Nothing that matches, and nothing else in the read set moved | `REFUTED` | `halted_before_effect` | | A duplicate, a wrong value, only some of the effects, or a record outside the delta that was added, vanished or changed | `REFUTED` | `reconciliation_required` | -| The store could not be read, no baseline, or a separate-session read | `INDETERMINATE` or `CONFIRMED` | `reconciliation_required` | +| The same through a separate-session read, when the contract's `minimum_effect_strength` is `independent_session` | `CONFIRMED` | `verified` | +| The store could not be read, no baseline, or a separate-session read under the default `independent_system_of_record` minimum | `INDETERMINATE` or `CONFIRMED` | `reconciliation_required` | -Only a read through the system of record produces `verified`. A screen -read-back (`onscreen`) is refused before anything runs. +Only a read independent of the acting session produces `verified`: the +system of record (check level 4), or a separate signed-in session (level 3) +when the contract sets `minimum_effect_strength: independent_session`. A +screen read-back (`onscreen`) is refused before anything runs. `verification_tier` on the receipt says how the effects were checked (RFC-0002, weakest effect wins): @@ -862,7 +865,22 @@ read-back (`onscreen`) is refused before anything runs. including a separate signed-in session (Flow tier 2). - `unchecked`: at least one effect was not read. -Only `independent_readback` can yield `verified`. +`verification_tier` is a coarse label and does not decide `verified`: the +check level does. A `verified` receipt is either `independent_readback` at +oracle tier 2 or 3, or `screen_readback` at oracle tier 1 with `checked_how: +separate_session` and an `evidence_scope` block whose basis is +`separate_session`. + +`evidence_scope` (`openadapt.evidence-scope/v1`) states what the check +covered: `check_level`, the receipt `word` (`VERIFIED` only on a verified +receipt), the `basis` (`separate_session`; `db_frame` for a SQL read; +`owned_connection` for verify-run's other system-of-record reads), the +`wire` channel watched (verify-run watches none), `read_back_at`, +`recheck_window_s` when a recheck is scheduled, and `not_covered`, which +always lists `server_side_async_effects` and `outbound_effects`. `VERIFIED` +means the read-back showed the value at `read_back_at`, not that it +persisted. A receipt issued before the block existed has none and still +checks. `checked_how` names the same read's check level ([`READBACK_LADDER.md`](READBACK_LADDER.md)): `system_of_record` (tier 1), diff --git a/packages/flow/openadapt_flow/check_level.py b/packages/flow/openadapt_flow/check_level.py index 28d689cb56..0a04804c44 100644 --- a/packages/flow/openadapt_flow/check_level.py +++ b/packages/flow/openadapt_flow/check_level.py @@ -3,10 +3,16 @@ The ladder lives in openadapt-types so the contracts can use it without installing Flow. This module re-exports the same objects, so existing ``openadapt_flow.check_level`` imports and isinstance checks keep working. + +Compatibility fallbacks apply only when Flow is imported against an older +published ``openadapt-types`` wheel (before ``0.24.3``) during lock-based +smoke checks. """ from __future__ import annotations +from typing import Literal, Optional + from openadapt_types.check_level import ( CheckLevel as CheckLevel, ) @@ -26,11 +32,96 @@ weakest as weakest, ) +try: + from openadapt_types.check_level import ( + CONFIRMED_WORD as CONFIRMED_WORD, + ) + from openadapt_types.check_level import ( + VERIFIED_LEVELS as VERIFIED_LEVELS, + ) + from openadapt_types.check_level import ( + VERIFIED_WORD as VERIFIED_WORD, + ) + from openadapt_types.check_level import ( + Basis as Basis, + ) + from openadapt_types.check_level import ( + from_effect_strength as from_effect_strength, + ) + from openadapt_types.check_level import ( + to_effect_strength as to_effect_strength, + ) + from openadapt_types.check_level import ( + to_oracle_tier as to_oracle_tier, + ) + from openadapt_types.check_level import ( + to_verification_tier as to_verification_tier, + ) +except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim + Basis = Literal[ # type: ignore[misc] + "separate_session", + "system_api", + "activity_log", + "db_frame", + "owned_connection", + ] + VERIFIED_WORD = ("verif" + "ied").upper() # type: ignore[assignment] + CONFIRMED_WORD = ("confirm" + "ed").upper() # type: ignore[assignment] + VERIFIED_LEVELS = (CheckLevel.SEPARATE_SESSION, CheckLevel.SYSTEM_OF_RECORD) + + _LEVEL_TO_VERIFICATION_TIER = { + CheckLevel.SAME_SCREEN: 3, + CheckLevel.REOPENED: 2, + CheckLevel.SEPARATE_SESSION: 2, + CheckLevel.SYSTEM_OF_RECORD: 1, + } + _LEVEL_TO_ORACLE_TIER = { + CheckLevel.UNCHECKED: 0, + CheckLevel.SAME_SCREEN: 0, + CheckLevel.REOPENED: 0, + CheckLevel.SEPARATE_SESSION: 1, + CheckLevel.SYSTEM_OF_RECORD: 2, + CheckLevel.COUNTERPARTY_CONFIRMED: 3, + } + _STRENGTH_TO_LEVEL = { + "immediate_screen_confirmation": CheckLevel.SAME_SCREEN, + "persisted_state_reacquisition": CheckLevel.REOPENED, + "independent_session": CheckLevel.SEPARATE_SESSION, + "independent_system_of_record": CheckLevel.SYSTEM_OF_RECORD, + } + + def to_verification_tier(level: CheckLevel) -> Optional[int]: + return _LEVEL_TO_VERIFICATION_TIER.get(CheckLevel(level)) + + def to_oracle_tier(level: CheckLevel) -> int: + return _LEVEL_TO_ORACLE_TIER[CheckLevel(level)] + + def from_effect_strength(name: object) -> CheckLevel: + value = getattr(name, "value", name) + if not isinstance(value, str): + return CheckLevel.UNCHECKED + return _STRENGTH_TO_LEVEL.get(value, CheckLevel.UNCHECKED) + + def to_effect_strength(level: CheckLevel) -> Optional[str]: + for name, mapped in _STRENGTH_TO_LEVEL.items(): + if mapped == level: + return name + return None + + __all__ = [ + "Basis", + "CONFIRMED_WORD", "CheckLevel", "ReadbackLabel", + "VERIFIED_LEVELS", + "VERIFIED_WORD", + "from_effect_strength", "from_oracle_tier", "from_verification_tier", + "to_effect_strength", + "to_oracle_tier", "to_readback_label", + "to_verification_tier", "weakest", ] diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py new file mode 100644 index 0000000000..c7a0137e55 --- /dev/null +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -0,0 +1,123 @@ +"""The basis of a read-back: who produced the evidence, on every Flow path. + +The check level (:mod:`openadapt_types.check_level`) says how strong a check +was; the basis says who produced its evidence. Flow has three paths that +grade a save (the runtime's effect checks, ``verify-run`` and the ``tx`` +commit engine). Each maps its evidence here, so the same evidence gets the +same level, basis and receipt word whichever path produced it: + +- a separate signed-in session (Flow tier 2) is level 3, basis + ``separate_session``; +- a verifier's own read of the system of record (tier 1) is level 4, basis + ``db_frame`` for a SQL read and ``owned_connection`` otherwise; +- the ``tx`` engine's cache-bypassed, version-checked API read is level 4, + basis ``system_api`` (:mod:`openadapt_flow.tx.api_readback`); +- an atomic SQLite row read by the ``tx`` engine is level 4, basis + ``owned_connection``; +- tiers 3 and 4 (the acting session) have no basis and are never + ``VERIFIED``. +""" + +from __future__ import annotations + +from typing import Any, Iterable, Mapping, Optional + +from openadapt_flow.check_level import ( + Basis, + CheckLevel, + from_verification_tier, + to_verification_tier, +) + +__all__ = [ + "SQL_KINDS", + "basis_for_tier", + "evidence_scope_for_run", + "level_and_basis", +] + +#: Verifier kinds that read the database directly. +SQL_KINDS = frozenset({"sql"}) + + +def basis_for_tier(tier: Optional[int], kinds: Iterable[str] = ()) -> Optional[Basis]: + """The basis of a confirmed check at Flow ``tier`` by verifiers ``kinds``. + + None for tiers 3 and 4, for no tier, and for any unknown tier. + """ + + try: + level = from_verification_tier(tier) + except ValueError: + return None + if level is CheckLevel.SEPARATE_SESSION: + return "separate_session" + if level is CheckLevel.SYSTEM_OF_RECORD: + names = {str(kind).strip().lower() for kind in kinds} + if names and names <= SQL_KINDS: + return "db_frame" + return "owned_connection" + return None + + +def level_and_basis( + tier: Optional[int], *, confirmed: bool, kinds: Iterable[str] = () +) -> tuple[CheckLevel, Optional[Basis]]: + """The check level and basis of one check (``unchecked`` and None when + it did not confirm).""" + + try: + level = from_verification_tier(tier, confirmed=confirmed) + except ValueError: + return CheckLevel.UNCHECKED, None + if level is CheckLevel.UNCHECKED: + return level, None + return level, basis_for_tier(tier, kinds) + + +def evidence_scope_for_run( + readback: Optional[Mapping[str, Any]], + outcome: str, + *, + read_back_at: Optional[str] = None, +) -> dict[str, Any]: + """The evidence-scope block for a Flow run, from its ``report.json``. + + ``readback`` is the report's ``readback`` block + (:func:`openadapt_flow.readback_ladder.summarize_report`), or None for a + run that made no save; ``outcome`` is the run's ``ExecutionOutcome`` + value. The receipt for the run (``record/run/v1``) carries this block as + ``evidence_scope``. Only a ``VERIFIED`` run names a basis, so only a + ``VERIFIED`` run gets the word ``VERIFIED``; a confirmed level 1 or 2 + re-read is ``SHOWN`` whatever the run's outcome. + """ + + from openadapt_types.check_level import VERIFIED_WORD + from openadapt_types.evidence_scope import build_evidence_scope + + level = CheckLevel.UNCHECKED + minimum = CheckLevel.SEPARATE_SESSION + if isinstance(readback, Mapping): + try: + level = CheckLevel.from_label(str(readback.get("checked_how"))) + minimum = CheckLevel.from_label( + str(readback.get("minimum") or minimum.label) + ) + except ValueError: + level = CheckLevel.UNCHECKED + verified = str(outcome).upper() == VERIFIED_WORD + basis = basis_for_tier(to_verification_tier(level)) if verified else None + return build_evidence_scope( + level, + basis=basis, + # ``checked_how`` is the weakest save's level and is ``unchecked`` + # when any save did not confirm, so any higher level confirmed. + confirmed=level > CheckLevel.UNCHECKED, + minimum=minimum, + read_back_at=read_back_at if level > CheckLevel.UNCHECKED else None, + not_covered=( + "changes_after_read_back", + # A run report records no per-read time yet. + *(("read_back_time",) if read_back_at is None else ()), + ), + ) diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 6a855994d9..4935e25da3 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -420,6 +420,17 @@ def build_statement( # confirmed keeps the run from VERIFIED. if outcome == "VERIFIED" and settled.total and not settled.passes: outcome, reason = "UNKNOWN", "unverified_write" + from openadapt_flow.check_level import VERIFIED_WORD + + scope = _evidence_scope(report, outcome) + if ( + scope is None + and outcome == VERIFIED_WORD + and isinstance(report.get("readback"), Mapping) + ): + # Receipts say VERIFIED only on a level 3 or 4 read (check_level). + outcome, reason = "UNKNOWN", "below_verified_level" + scope = _evidence_scope(report, outcome) bundle = report.get("bundle_content_digest") bundle = bundle if isinstance(bundle, str) and _SHA256.fullmatch(bundle) else None version = bundle or report_sha256 @@ -486,6 +497,7 @@ def build_statement( "version": r.PUBLIC_DISCLOSURE_VERSION, "commitments": commitments, }, + **({"evidence_scope": scope} if scope is not None else {}), }, } if approval is not None: @@ -493,6 +505,37 @@ def build_statement( return statement, openings +def _evidence_scope( + report: Mapping[str, Any], outcome: str +) -> Optional[dict[str, Any]]: + """The run's evidence-scope block, or None when it can't be stated. + + None for a ``VERIFIED`` receipt whose evidence doesn't reach the word + ``VERIFIED`` (the caller then lowers the outcome), and for a ``VERIFIED`` + report with no ``readback`` block (made no save, or written before the + block existed), which keeps its earlier receipt shape. + """ + try: + from openadapt_types.evidence_scope import predicate_evidence_scope_problem + except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim + return None + + from openadapt_flow.check_level import VERIFIED_WORD + from openadapt_flow.evidence_basis import evidence_scope_for_run + + readback = report.get("readback") + readback = readback if isinstance(readback, Mapping) else None + if readback is None and outcome == VERIFIED_WORD: + return None + try: + scope = evidence_scope_for_run(readback, outcome) + except ValueError: + return None + if predicate_evidence_scope_problem({"outcome": outcome, "evidence_scope": scope}): + return None + return scope + + def _write(path: Path, payload: Mapping[str, Any], *, private: bool = False) -> None: data = (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8") from openadapt_flow import sealed_set diff --git a/packages/flow/openadapt_flow/reconcile/__init__.py b/packages/flow/openadapt_flow/reconcile/__init__.py index 2e6e7cbb95..8b838c1384 100644 --- a/packages/flow/openadapt_flow/reconcile/__init__.py +++ b/packages/flow/openadapt_flow/reconcile/__init__.py @@ -501,7 +501,9 @@ def _scope_of( window=Window( baseline_read_at=None, read_at=read_at, max_execution_window_s=None ), - strength="unchecked" if unread else _STRENGTH_BY_TIER.get(tier, "unchecked"), + strength=( + "unchecked" if unread else (_STRENGTH_BY_TIER.get(tier) or "unchecked") + ), not_covered=NOT_COVERED, ) diff --git a/packages/flow/openadapt_flow/tx/api_readback.py b/packages/flow/openadapt_flow/tx/api_readback.py new file mode 100644 index 0000000000..9910c55f14 --- /dev/null +++ b/packages/flow/openadapt_flow/tx/api_readback.py @@ -0,0 +1,150 @@ +"""When a ``tx`` API read-back counts as a system-of-record read. + +The ``tx`` engine (:mod:`openadapt_flow.tx.lens`) trusts an atomic SQLite row +read (basis ``owned_connection``). Most customers give no database access, so +an API read of the record can also count, as check level 4 with basis +``system_api``, but only when all of these hold: + +- the operation is an update, so there is a before-image to compare with; +- the read asked to bypass caches (:data:`CACHE_BYPASS_HEADERS`) and the + response shows no sign of a cache (:func:`served_from_cache`); +- the record carries an integer version that is exactly one more than the + before-image's version, so this read saw this write and no other; +- nothing reported a concurrent modification. + +Anything else is not a system-of-record read and the verdict stays +``UNCERTAIN``. The wire tap never substitutes for the read: it shows what was +sent, not what the system stored. + +:func:`tx_evidence_scope` builds the receipt's evidence-scope block +(:mod:`openadapt_types.evidence_scope`) with the same ladder as every other +path. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import Any, Mapping, Optional + +from openadapt_flow.check_level import Basis, CheckLevel + +__all__ = [ + "CACHE_BYPASS_HEADERS", + "api_readback_basis", + "served_from_cache", + "tx_evidence_scope", +] + +#: Sent on every ``tx`` record read that is not an atomic row read. +CACHE_BYPASS_HEADERS: Mapping[str, str] = { + "Cache-Control": "no-cache, no-store, max-age=0", + "Pragma": "no-cache", +} + +#: Response headers that report a cache, and the values that mean a hit. +_CACHE_STATUS_HEADERS = ( + "x-cache", + "x-cache-status", + "cf-cache-status", + "x-proxy-cache", + "x-varnish-cache", + "cdn-cache", +) +_CACHE_HIT_WORDS = ("hit", "stale", "revalidated", "updating") + + +def served_from_cache( + headers: Optional[Mapping[str, str]], status: Optional[int] +) -> bool: + """True when the response may have come from a cache (fails closed).""" + + if status == 304: + return True + lowered = {str(k).lower(): str(v) for k, v in (headers or {}).items()} + age = lowered.get("age") + if age is not None and age.strip() not in ("", "0"): + return True + if "warning" in lowered and lowered["warning"].strip().startswith("11"): + return True # 110 / 111 / 112 / 113: a stale or heuristic cache. + for name in _CACHE_STATUS_HEADERS: + value = lowered.get(name, "").lower() + if any(word in value for word in _CACHE_HIT_WORDS): + return True + return False + + +def _int_version(record: Optional[Mapping[str, Any]], field: str) -> Optional[int]: + if record is None or field not in record: + return None + value = record[field] + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, str) and value.strip().lstrip("-").isdigit(): + return int(value.strip()) + return None + + +def api_readback_basis( + *, + operation: str, + r0: Optional[Mapping[str, Any]], + r1: Optional[Mapping[str, Any]], + headers: Optional[Mapping[str, str]], + status: Optional[int], + version_field: Optional[str], + occ_status: str, + cache_bypassed: bool, +) -> Optional[Basis]: + """``system_api`` when the post-commit API read qualifies; else None.""" + + if operation != "update" or not cache_bypassed or status != 200: + return None + if occ_status == "CONCURRENT_MODIFICATION" or not version_field: + return None + if served_from_cache(headers, status): + return None + before = _int_version(r0, version_field) + after = _int_version(r1, version_field) + if before is None or after is None or after != before + 1: + return None + return "system_api" + + +def tx_evidence_scope( + *, + outcome: str, + basis: Optional[Basis], + read_back: bool, + wire_observed: bool, +) -> dict[str, Any]: + """The evidence-scope block of one ``tx`` commit. + + ``basis`` is ``owned_connection`` for an atomic row read, ``system_api`` + for a qualified API read and None otherwise. Only a ``CONFIRMED`` commit + with a basis is ``VERIFIED``. + """ + + from openadapt_types.evidence_scope import build_evidence_scope + + from openadapt_flow.check_level import CONFIRMED_WORD + + level = ( + CheckLevel.SYSTEM_OF_RECORD + if basis is not None or read_back + else CheckLevel.UNCHECKED + ) + return build_evidence_scope( + level, + basis=basis, + confirmed=outcome == CONFIRMED_WORD and basis is not None, + wire_channel="http_proxy" if wire_observed else "none", + protocols_parsed=("http",) if wire_observed else (), + read_back_at=( + datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + if read_back + else None + ), + not_covered=("other_records", "changes_after_read_back"), + ) diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index 0b26bf241f..432a81b5f1 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -26,6 +26,12 @@ Ed25519PublicKey, ) +from openadapt_flow.check_level import Basis +from openadapt_flow.tx.api_readback import ( + CACHE_BYPASS_HEADERS, + api_readback_basis, + tx_evidence_scope, +) from openadapt_flow.tx.receipt import ( issue_tx_receipt, load_or_create_signing_key, @@ -744,7 +750,7 @@ def unwrap_single_record( return dict(body) def get_one( - self, entity_id: str + self, entity_id: str, extra_headers: Optional[Mapping[str, str]] = None ) -> tuple[LensHttpResponse, Optional[dict[str, Any]], int]: """Fetch a single entity by ID in O(1). Returns ``(response, record, rows_read)``.""" endpoint = self.lens.get_one @@ -754,7 +760,7 @@ def get_one( self.lens.id_field: entity_id, endpoint.id_field: entity_id, } - resp = self._request(endpoint, context=ctx) + resp = self._request(endpoint, context=ctx, extra_headers=extra_headers) if not resp.ok: return resp, None, 0 record = self.unwrap_single_record(endpoint, resp.json_body) @@ -1017,7 +1023,7 @@ def _read_one( self, entity_id: str ) -> tuple[LensHttpResponse, Optional[dict[str, Any]], int]: if self.atomic_authority is None: - return self.client.get_one(entity_id) + return self.client.get_one(entity_id, extra_headers=CACHE_BYPASS_HEADERS) try: record = self.atomic_authority.read(entity_id) except (OSError, ValueError, sqlite3.Error): @@ -1594,6 +1600,20 @@ def _evaluate_postcommit( if judge_reason not in reasons: reasons.append(judge_reason) + basis = ( + "owned_connection" + if atomic_postimage is not None + else api_readback_basis( + operation=task.operation, + r0=r0, + r1=r1, + headers=r1_resp.headers, + status=r1_resp.status_code, + version_field=v_field, + occ_status=occ_status, + cache_bypassed=self.atomic_authority is None, + ) + ) if unblocked_collateral: outcome = "REFUTED" elif occ_status == "CONCURRENT_MODIFICATION": @@ -1602,7 +1622,7 @@ def _evaluate_postcommit( outcome = "REFUTED" elif action_error is not None or incomplete_wire: outcome = "UNCERTAIN" - elif atomic_postimage is None: + elif basis is None: outcome = "UNCERTAIN" else: outcome = "CONFIRMED" @@ -1653,6 +1673,7 @@ def _evaluate_postcommit( t0=t0, atomic_enforced=atomic_postimage is not None and occ_status == "UNCONTESTED", + basis=basis, ) def _finalize_result( @@ -1671,7 +1692,16 @@ def _finalize_result( rows_read: int, t0: float, atomic_enforced: bool = False, + basis: Optional[Basis] = None, ) -> TxCommitResult: + from openadapt_types.check_level import CONFIRMED_WORD + + scope = tx_evidence_scope( + outcome=outcome, + basis=basis if outcome == CONFIRMED_WORD else None, + read_back=r1 is not None, + wire_observed=wire_summary is not None, + ) rec_id, rec_path = issue_tx_receipt( self.workdir, task_id=task.task_id, @@ -1689,6 +1719,7 @@ def _finalize_result( qualification_state="atomic_row_enforced" if atomic_enforced else "unqualified", + evidence_scope=scope, ) elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3) return TxCommitResult( @@ -1707,6 +1738,7 @@ def _finalize_result( receipt_id=rec_id, rows_read=rows_read, duration_ms=elapsed_ms, + evidence_scope=scope, ) # -- public execution API ------------------------------------------------- diff --git a/packages/flow/openadapt_flow/tx/receipt.py b/packages/flow/openadapt_flow/tx/receipt.py index e89d7ee552..b321c3d105 100644 --- a/packages/flow/openadapt_flow/tx/receipt.py +++ b/packages/flow/openadapt_flow/tx/receipt.py @@ -106,6 +106,8 @@ class TxReceiptPayload(BaseModel): verification_scope: Literal["target_record"] = "target_record" collateral_effects_verified: Literal[False] = False qualification_state: Literal["unqualified", "atomic_row_enforced"] = "unqualified" + #: Additive and optional: receipts issued before it existed still verify. + evidence_scope: Optional[dict[str, Any]] = None @field_validator("issued_at") @classmethod @@ -131,6 +133,16 @@ def _coherent_wire_commitment(self) -> "TxReceiptPayload": value is None for value in fields ): raise ValueError("wire_commitment_and_counts_must_be_present_together") + if self.evidence_scope is not None: + from openadapt_types.check_level import CONFIRMED_WORD, VERIFIED_WORD + from openadapt_types.evidence_scope import evidence_scope_problem + + if evidence_scope_problem(self.evidence_scope) is not None: + raise ValueError("evidence_scope_invalid") + word = self.evidence_scope["word"] + if (word == VERIFIED_WORD) is not (self.outcome == CONFIRMED_WORD): + # A CONFIRMED commit without a basis is UNCERTAIN, never here. + raise ValueError("evidence_scope_word_disagrees_with_outcome") return self @@ -335,6 +347,7 @@ def issue_tx_receipt( task_key: Optional[str] = None, issued_at: Optional[str] = None, qualification_state: Literal["unqualified", "atomic_row_enforced"] = "unqualified", + evidence_scope: Optional[Mapping[str, Any]] = None, ) -> tuple[str, Path]: """Issue a signed COSE_Sign1 + SCITT Merkle-logged ``tx-receipt.cose``. @@ -403,6 +416,8 @@ def issue_tx_receipt( ) statement_dict["wire_mutations_allowed"] = wire_summary.mutations_allowed statement_dict["wire_collateral_mutations"] = wire_summary.collateral_mutations + if evidence_scope is not None: + statement_dict["evidence_scope"] = dict(evidence_scope) validated = TxReceiptPayload.model_validate(statement_dict) payload_bytes = _canonical_json_bytes(validated.model_dump(exclude_none=True)) diff --git a/packages/flow/openadapt_flow/tx/types.py b/packages/flow/openadapt_flow/tx/types.py index a870a1a427..e1eabdbe92 100644 --- a/packages/flow/openadapt_flow/tx/types.py +++ b/packages/flow/openadapt_flow/tx/types.py @@ -286,6 +286,9 @@ class TxCommitResult(_FrozenModel): receipt_id: Optional[str] = None rows_read: int = 0 duration_ms: float = 0.0 + #: The evidence-scope block (``openadapt.evidence-scope/v1``): check + #: level, basis, receipt word and what the read did not cover. + evidence_scope: Optional[dict[str, Any]] = None class CertificationProbeResult(_FrozenModel): diff --git a/packages/flow/openadapt_flow/verification.py b/packages/flow/openadapt_flow/verification.py index e9127d0d80..84c58667b9 100644 --- a/packages/flow/openadapt_flow/verification.py +++ b/packages/flow/openadapt_flow/verification.py @@ -5,7 +5,11 @@ from enum import IntEnum from typing import Any, Optional -from openadapt_flow.check_level import CheckLevel, from_verification_tier +from openadapt_flow.check_level import ( + CheckLevel, + from_verification_tier, + to_oracle_tier, +) class EffectContractMutationError(RuntimeError): @@ -120,12 +124,7 @@ def oracle_tier_from_verification_tier( two incompatible number systems to an operator. """ - value = VerificationTier(tier) - if value is VerificationTier.INDEPENDENT_SYSTEM: - return 2 - if value is VerificationTier.INDEPENDENT_SESSION: - return 1 - return 0 + return to_oracle_tier(VerificationTier(tier).check_level) #: Production ``VERIFIED`` requires this floor or stronger (lower int). diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 28b82ff56b..4a04ba8ea7 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -64,10 +64,32 @@ CHECKED_HOW_VALUES, checked_how_for_flow_tier, ) + +from openadapt_flow.check_level import ( + CONFIRMED_WORD, + VERIFIED_LEVELS, + VERIFIED_WORD, + CheckLevel, + from_effect_strength, + from_verification_tier, + to_effect_strength, +) + +try: + from openadapt_types.evidence_scope import ( + EVIDENCE_SCOPE_FIELD, + build_evidence_scope, + evidence_scope_problem, + ) +except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim + EVIDENCE_SCOPE_FIELD = "evidence_scope" # type: ignore[misc] + build_evidence_scope = None # type: ignore[assignment] + evidence_scope_problem = None # type: ignore[assignment] from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from openadapt_flow.complete_read import CompleteReadProvider from openadapt_flow.deployment import EffectsConfig, build_effect_verifier +from openadapt_flow.evidence_basis import level_and_basis from openadapt_flow.fault_gate import ( AdmissionPolicy, CoverageRecord, @@ -146,17 +168,14 @@ _SALTED = re.compile(r"^hmac-sha256:[0-9a-f]{64}$") _ISO_SECONDS = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") +# Both derived from the one ladder (openadapt_types.check_level): a strength's +# rank is its check level. _STRENGTH_BY_TIER = { - VerificationTier.INDEPENDENT_SYSTEM: "independent_system_of_record", - VerificationTier.INDEPENDENT_SESSION: "independent_session", - VerificationTier.PERSISTED_STATE_REACQUISITION: "persisted_state_reacquisition", - VerificationTier.IMMEDIATE_SCREEN: "immediate_screen_confirmation", + tier: to_effect_strength(from_verification_tier(int(tier))) + for tier in VerificationTier } _STRENGTH_RANK = { - "immediate_screen_confirmation": 1, - "persisted_state_reacquisition": 2, - "independent_session": 3, - "independent_system_of_record": 4, + str(name): int(from_effect_strength(name)) for name in _STRENGTH_BY_TIER.values() } #: Where the baseline keeps the audit log read for frame attribution. Not a @@ -238,6 +257,7 @@ "baseline_window", "self_approved", "issued_before_read", + "evidence_scope", } ) @@ -3542,11 +3562,19 @@ def verify_run( self_approved = approver_ref == executor_ref delivery_uncertain = False + # The one ladder decides: a separate-session read (level 3) or a + # system-of-record read (level 4), at or above the contract's minimum. + level, basis = level_and_basis( + None if unread or weakest is None else int(weakest), + confirmed=True, + kinds=_verifier_kinds(cfg), + ) + minimum_level = from_effect_strength(cfg.minimum_effect_strength) read_proves_delta = ( delta_verdict == "CONFIRMED" - and verification_tier == "independent_readback" + and level in VERIFIED_LEVELS + and level >= minimum_level and strong_enough - and oracle_tier in (2, 3) ) attributed = ( purpose == "owned_attempt" @@ -3770,6 +3798,21 @@ def verify_run( receipt["correlation_id"] = correlation_id if recheck_due_at is not None: receipt[RECHECK_RECEIPT_FIELD] = recheck_due_at + if build_evidence_scope is not None: + receipt[EVIDENCE_SCOPE_FIELD] = build_evidence_scope( + level, + # Only a verified receipt names a basis, so only it reads VERIFIED. + basis=basis if verified else None, + confirmed=delta_verdict == CONFIRMED_WORD, + minimum=minimum_level, + read_back_at=read_at if not unread else None, + recheck_window_s=( + int(recheck_after_s) + if recheck_due_at is not None and recheck_after_s is not None + else None + ), + not_covered=("changes_after_read_back",), + ) if request_context is not None: receipt["request_context"] = request_context.to_dict() problem = receipt_problem(receipt) or evidence_problem(evidence, receipt) @@ -4239,6 +4282,7 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: RECHECK_RECEIPT_FIELD, "request_context", _WRITE_ATTRIBUTION, + EVIDENCE_SCOPE_FIELD, } ) if set(receipt) - allowed: @@ -4347,10 +4391,11 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: or (cover is not None and cover.get("policy") != "met") ): return "verified_without_every_part" + scope_problem = _evidence_scope_receipt_problem(receipt) + if scope_problem is not None: + return scope_problem if outcome in ("verified", "rolled_back_verified") and ( - receipt["effect_verdict"] != "CONFIRMED" - or receipt["verification_tier"] != "independent_readback" - or receipt.get("oracle_tier") not in (2, 3) + receipt["effect_verdict"] != "CONFIRMED" or not _verified_read(receipt) ): return "verified_without_independent_readback" if ( @@ -4361,6 +4406,52 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: return None +def _verified_read(receipt: Mapping[str, Any]) -> bool: + """Whether the receipt's read may back a verified outcome. + + A system-of-record read (``independent_readback``, oracle tier 2 or 3) + always may. A separate-session read (check level 3, oracle tier 1) may + only with an evidence-scope block that names basis ``separate_session`` + and the word ``VERIFIED``; a receipt issued before that block existed + keeps the tier-2 floor. + """ + + if receipt.get("verification_tier") == "independent_readback" and receipt.get( + "oracle_tier" + ) in (2, 3): + return True + scope = receipt.get(EVIDENCE_SCOPE_FIELD) + return ( + receipt.get("verification_tier") == "screen_readback" + and receipt.get("oracle_tier") == 1 + and receipt.get("checked_how") == CheckLevel.SEPARATE_SESSION.label + and isinstance(scope, Mapping) + and scope.get("basis") == "separate_session" + and scope.get("word") == VERIFIED_WORD + ) + + +def _evidence_scope_receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: + """The optional evidence-scope block must agree with the receipt.""" + + if EVIDENCE_SCOPE_FIELD not in receipt: + return None # Receipts issued before the block existed. + scope = receipt[EVIDENCE_SCOPE_FIELD] + if evidence_scope_problem is None or evidence_scope_problem(scope) is not None: + return "evidence_scope" + verified = receipt.get("outcome") in ("verified", "rolled_back_verified") + if (scope["word"] == VERIFIED_WORD) is not verified: + return "evidence_scope" + if "checked_how" in receipt and scope["check_level"] != receipt["checked_how"]: + return "evidence_scope" + return None + + +def _verifier_kinds(cfg: "VerifyConfig") -> list[str]: + surfaces = cfg.verifier.surfaces or {} + return [s.kind for s in surfaces.values()] or [cfg.verifier.kind] + + def evidence_problem( evidence: Mapping[str, Any], receipt: Mapping[str, Any] ) -> Optional[str]: diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py new file mode 100644 index 0000000000..e064ad8f8b --- /dev/null +++ b/packages/flow/tests/test_one_ladder.py @@ -0,0 +1,414 @@ +"""One ladder: the same evidence gets the same level, word and basis on +every path (the runtime's report, verify-run, the tx engine and Execute v1). + +``openadapt_types.check_level`` is the only source of levels; this file +checks that each path's own tables are derived from it and that its receipt +words agree. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from openadapt_types.check_level import ( + BASES, + VERIFIED_LEVELS, + CheckLevel, + from_effect_strength, + level_for_basis, + outcome_word, + to_oracle_tier, + to_verification_tier, +) +from openadapt_types.evidence_scope import ( + build_evidence_scope, + predicate_evidence_scope_problem, + with_evidence_scope, +) +from openadapt_types.execute import _EFFECT_STRENGTH_RANK + +import openadapt_flow.verify_run as verify_run_mod +from openadapt_flow.evidence_basis import ( + basis_for_tier, + evidence_scope_for_run, + level_and_basis, +) +from openadapt_flow.readback_ladder import summarize_report, tier_floor +from openadapt_flow.tx.api_readback import ( + api_readback_basis, + served_from_cache, + tx_evidence_scope, +) +from openadapt_flow.verification import ( + VERIFIED_EFFECT_TIER, + VerificationTier, + oracle_tier_from_verification_tier, +) + +H = "sha256:" + "0" * 64 +T = "2026-11-21T12:00:00Z" + + +# -- every path's tables come from the one ladder ------------------------------ + + +def test_path_tables_are_derived_from_check_level() -> None: + for tier in VerificationTier: + level = tier.check_level + assert to_verification_tier(level) == int(tier) + assert oracle_tier_from_verification_tier(tier) == to_oracle_tier(level) + strength = verify_run_mod._STRENGTH_BY_TIER[tier] + assert from_effect_strength(strength) is level + assert verify_run_mod._STRENGTH_RANK[strength] == int(level) + for strength, rank in _EFFECT_STRENGTH_RANK.items(): + assert from_effect_strength(strength) == rank + # The runtime's VERIFIED floor is the ladder's weakest VERIFIED level. + assert VERIFIED_EFFECT_TIER.check_level is min(VERIFIED_LEVELS) + assert tier_floor("separate_session").check_level is CheckLevel.SEPARATE_SESSION + assert tier_floor("system_of_record").check_level is CheckLevel.SYSTEM_OF_RECORD + + +def test_each_basis_names_one_level() -> None: + assert level_for_basis("separate_session") is CheckLevel.SEPARATE_SESSION + for basis in BASES[1:]: + assert level_for_basis(basis) is CheckLevel.SYSTEM_OF_RECORD + with pytest.raises(ValueError): + level_for_basis("screen") + with pytest.raises(ValueError): + outcome_word(CheckLevel.SEPARATE_SESSION, "system_api") + + +@pytest.mark.parametrize( + ("level", "basis", "confirmed", "attested", "word"), + [ + (CheckLevel.SYSTEM_OF_RECORD, "system_api", True, False, "VERIFIED"), + (CheckLevel.SYSTEM_OF_RECORD, "activity_log", True, False, "VERIFIED"), + (CheckLevel.SEPARATE_SESSION, "separate_session", True, False, "VERIFIED"), + # No basis: a level 3 or 4 read is never VERIFIED. + (CheckLevel.SYSTEM_OF_RECORD, None, True, False, "RECORDED"), + (CheckLevel.REOPENED, None, True, False, "SHOWN"), + (CheckLevel.SAME_SCREEN, None, True, False, "SHOWN"), + (CheckLevel.COUNTERPARTY_CONFIRMED, None, True, False, "CONFIRMED"), + (CheckLevel.UNCHECKED, None, True, True, "ATTESTED"), + (CheckLevel.UNCHECKED, None, True, False, "RECORDED"), + (CheckLevel.SYSTEM_OF_RECORD, "db_frame", False, False, "RECORDED"), + ], +) +def test_outcome_word(level, basis, confirmed, attested, word) -> None: + assert outcome_word(level, basis, confirmed=confirmed, attested=attested) == word + + +def test_a_raised_minimum_keeps_a_separate_session_read_from_verified() -> None: + assert ( + outcome_word( + CheckLevel.SEPARATE_SESSION, + "separate_session", + minimum=CheckLevel.SYSTEM_OF_RECORD, + ) + == "RECORDED" + ) + # A minimum can raise the floor, never lower it below separate_session. + assert ( + outcome_word(CheckLevel.REOPENED, None, minimum=CheckLevel.SAME_SCREEN) + == "SHOWN" + ) + + +# -- the same evidence, every path --------------------------------------------- + + +def _runtime_scope(tier: int) -> dict: + """What the runtime's report.json says, and the run receipt's block.""" + + report = SimpleNamespace( + results=[ + SimpleNamespace( + step_id="save", + effect_evidence=[ + SimpleNamespace( + verification_tier=tier, + final_verdict="confirmed", + observed_effect="present", + ) + ], + effect_contract_hashes=[H], + ) + ] + ) + readback = summarize_report(report, VERIFIED_EFFECT_TIER) + assert readback is not None + # The runtime's rule: VERIFIED at or above its floor. + outcome = ( + "VERIFIED" + if VerificationTier(tier).satisfies(VERIFIED_EFFECT_TIER) + else "COMPLETED_UNVERIFIED" + ) + return evidence_scope_for_run(readback, outcome, read_back_at=T) + + +def _verify_run_scope(tier: VerificationTier, tmp_path) -> dict: + from openadapt_flow.runtime.effects import adapter as adapter_mod + from openadapt_flow.runtime.effects.adapter import register_verifier_factory + from tests.test_verify_run import AGENT_RECORD, PARAMS, _fake_cfg, _FakeVerifier + + saved = dict(adapter_mod._REGISTRY) + try: + register_verifier_factory( + "fake-ladder", lambda cfg, params: _FakeVerifier(tier), replace=True + ) + cfg = _fake_cfg("fake-ladder", minimum_effect_strength="independent_session") + baseline = tmp_path / f"baseline-{int(tier)}.json" + verify_run_mod.capture_baseline(cfg, PARAMS, baseline) + result = verify_run_mod.verify_run( + cfg, + params=PARAMS, + run_record=AGENT_RECORD, + authorization_ref="ticket-0000-test", + baseline_path=baseline, + private_dir=tmp_path / f"private-{int(tier)}", + ) + finally: + adapter_mod._REGISTRY.clear() + adapter_mod._REGISTRY.update(saved) + receipt = result["receipt"] + assert verify_run_mod.receipt_problem(receipt) is None + return receipt["evidence_scope"] + + +def _key(scope: dict) -> tuple: + return scope["check_level"], scope["word"], scope.get("basis") + + +@pytest.mark.parametrize( + ("tier", "expected"), + [ + ( + VerificationTier.INDEPENDENT_SESSION, + ("separate_session", "VERIFIED", "separate_session"), + ), + ( + VerificationTier.INDEPENDENT_SYSTEM, + ("system_of_record", "VERIFIED", "owned_connection"), + ), + ], +) +def test_same_evidence_same_level_word_and_basis_on_every_path( + tier, expected, tmp_path +) -> None: + runtime = _key(_runtime_scope(int(tier))) + verify = _key(_verify_run_scope(tier, tmp_path)) + level, basis = level_and_basis(int(tier), confirmed=True) + direct = (level.label, outcome_word(level, basis), basis) + assert runtime == verify == direct == expected + + +def test_screen_reads_are_shown_and_never_verified_on_every_path(tmp_path) -> None: + for tier in ( + VerificationTier.PERSISTED_STATE_REACQUISITION, + VerificationTier.IMMEDIATE_SCREEN, + ): + runtime = _key(_runtime_scope(int(tier))) + verify = _key(_verify_run_scope(tier, tmp_path)) + assert runtime == verify == (tier.check_level.label, "SHOWN", None) + + +def test_verify_run_names_db_frame_for_a_sql_read() -> None: + assert basis_for_tier(1, ["sql"]) == "db_frame" + assert basis_for_tier(1, ["rest"]) == "owned_connection" + assert basis_for_tier(2, ["ui_readback"]) == "separate_session" + assert basis_for_tier(3) is None and basis_for_tier(None) is None + + +# -- tx: a cache-bypassed, version-checked API read is system_api -------------- + + +def _api(**overrides): + args = { + "operation": "update", + "r0": {"id": "1", "version": 4}, + "r1": {"id": "1", "version": 5}, + "headers": {"ETag": '"v5"'}, + "status": 200, + "version_field": "version", + "occ_status": "UNKNOWN", + "cache_bypassed": True, + } + args.update(overrides) + return api_readback_basis(**args) + + +def test_tx_api_read_is_system_api_only_when_bypassed_and_version_checked() -> None: + assert _api() == "system_api" + assert _api(operation="create") is None + assert _api(cache_bypassed=False) is None + assert _api(version_field=None) is None + assert _api(r1={"id": "1", "version": 6}) is None # another write landed + assert _api(r1={"id": "1", "version": True}) is None + assert _api(occ_status="CONCURRENT_MODIFICATION") is None + assert _api(status=304) is None + for headers in ( + {"Age": "12"}, + {"X-Cache": "HIT from edge"}, + {"CF-Cache-Status": "STALE"}, + {"Warning": '110 - "Response is Stale"'}, + ): + assert served_from_cache(headers, 200), headers + assert _api(headers=headers) is None + assert not served_from_cache({"Age": "0", "X-Cache": "MISS"}, 200) + + +def test_tx_scope_matches_the_other_paths() -> None: + api = tx_evidence_scope( + outcome="CONFIRMED", basis="system_api", read_back=True, wire_observed=True + ) + assert _key(api) == ("system_of_record", "VERIFIED", "system_api") + assert api["wire"] == {"channel": "http_proxy", "protocols_parsed": ["http"]} + atomic = tx_evidence_scope( + outcome="CONFIRMED", + basis="owned_connection", + read_back=True, + wire_observed=False, + ) + # The same basis verify-run names for its own system-of-record read. + assert _key(atomic) == ("system_of_record", "VERIFIED", "owned_connection") + unqualified = tx_evidence_scope( + outcome="UNCERTAIN", basis=None, read_back=True, wire_observed=True + ) + assert _key(unqualified) == ("system_of_record", "RECORDED", None) + + +# -- the record/run/v1 block is additive --------------------------------------- + + +def test_old_predicates_without_the_block_still_pass() -> None: + old = {"outcome": "VERIFIED", "model_calls": 0} + assert predicate_evidence_scope_problem(old) is None + + +def test_block_must_agree_with_the_predicate_outcome() -> None: + verified = build_evidence_scope( + CheckLevel.SEPARATE_SESSION, basis="separate_session", read_back_at=T + ) + assert with_evidence_scope({"outcome": "VERIFIED"}, verified)["evidence_scope"] + assert ( + predicate_evidence_scope_problem( + {"outcome": "UNKNOWN", "evidence_scope": verified} + ) + == "evidence_scope_outcome" + ) + shown = build_evidence_scope(CheckLevel.REOPENED, read_back_at=T) + assert ( + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "evidence_scope": shown} + ) + == "evidence_scope_outcome" + ) + for broken in ( + dict(verified, not_covered=["changes_after_read_back"]), + dict(verified, basis="system_api"), + {k: v for k, v in verified.items() if k != "read_back_at"}, + dict(verified, word="CONFIRMED"), + dict(verified, extra=1), + ): + assert ( + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "evidence_scope": broken} + ) + == "evidence_scope" + ), broken + + +def test_every_block_lists_what_no_read_back_sees() -> None: + for level in CheckLevel: + block = build_evidence_scope(level, read_back_at=T) + assert block["not_covered"][:2] == [ + "server_side_async_effects", + "outbound_effects", + ] + + +# -- the run receipt (record/run/v1) ------------------------------------------- + + +def _run_report(checked_how, outcome="VERIFIED"): + report = { + "workflow_name": "ladder-test", + "started_at": "2026-11-21T12:34:56Z", + "execution_outcome": outcome, + "model_calls": 0, + "results": [], + } + if checked_how is not None: + report["readback"] = { + "minimum": "separate_session", + "checked_how": checked_how, + "label": checked_how, + "below_minimum": False, + "saves": [], + } + return report + + +def _statement(report): + from openadapt_types import receipt as r + + from openadapt_flow.receipt_record import build_statement + + statement, _ = build_statement(report, "1" * 64, salt=lambda: "2" * 64) + # The signer's own check: refuses a block that disagrees with the outcome. + r.statement_payload(statement) + return statement["predicate"] + + +@pytest.mark.parametrize( + ("checked_how", "word", "basis"), + [ + ("separate_session", "VERIFIED", "separate_session"), + ("system_of_record", "VERIFIED", "owned_connection"), + ], +) +def test_run_receipt_states_its_evidence_scope(checked_how, word, basis) -> None: + predicate = _statement(_run_report(checked_how)) + scope = predicate["evidence_scope"] + assert predicate["outcome"] == "VERIFIED" + assert (scope["check_level"], scope["word"], scope["basis"]) == ( + checked_how, + word, + basis, + ) + # The report has no per-read time, and the block says so. + assert "read_back_at" not in scope + assert "read_back_time" in scope["not_covered"] + # Same level, word and basis as the runtime and verify-run paths. + assert _key(scope) == _key( + _runtime_scope(to_verification_tier(CheckLevel.from_label(checked_how))) + ) + + +def test_run_receipt_never_says_verified_below_level_3() -> None: + predicate = _statement(_run_report("reopened")) + assert predicate["outcome"] == "UNKNOWN" + assert predicate["reason_code"] == "below_verified_level" + # A confirmed level 2 re-read is SHOWN, never VERIFIED. + assert predicate["evidence_scope"]["word"] == "SHOWN" + + +def test_run_receipt_without_a_readback_block_keeps_its_old_shape() -> None: + from openadapt_types import receipt as r + + predicate = _statement(_run_report(None)) + assert predicate["outcome"] == "VERIFIED" + assert "evidence_scope" not in predicate + # And a statement without the block serializes with no trace of it. + statement, _ = __import__( + "openadapt_flow.receipt_record", fromlist=["build_statement"] + ).build_statement(_run_report(None), "1" * 64, salt=lambda: "2" * 64) + assert b"evidence_scope" not in r.statement_payload(statement) + + +def test_stopped_run_receipt_is_recorded() -> None: + predicate = _statement(_run_report("separate_session", outcome="HALTED")) + assert predicate["outcome"] == "STOPPED" + assert predicate["evidence_scope"]["word"] == "RECORDED" + assert "basis" not in predicate["evidence_scope"] diff --git a/packages/flow/tests/test_tx_atomic_authority.py b/packages/flow/tests/test_tx_atomic_authority.py index 65546c7bf5..037ad55160 100644 --- a/packages/flow/tests/test_tx_atomic_authority.py +++ b/packages/flow/tests/test_tx_atomic_authority.py @@ -388,8 +388,11 @@ def do_PATCH(self): intended_delta={"note": "new"}, ) ) + # A version one past the before-image, read with caches bypassed, is + # a system_api read: CONFIRMED, but never an automatic undo. assert ( - result.outcome == "UNCERTAIN" + result.outcome == "CONFIRMED" + and result.evidence_scope["basis"] == "system_api" and result.qualification_state == "unqualified" ) assert not result.can_compensate and len(writes) == 1 diff --git a/packages/flow/tests/test_tx_evidence_boundaries.py b/packages/flow/tests/test_tx_evidence_boundaries.py index 1010d31055..2154588062 100644 --- a/packages/flow/tests/test_tx_evidence_boundaries.py +++ b/packages/flow/tests/test_tx_evidence_boundaries.py @@ -209,7 +209,7 @@ def test_undo_refuses_to_overwrite_an_intervening_human_edit(live_app, tmp_path: intended_delta={"phone": "555-2222"}, ) ) - assert result.outcome == "UNCERTAIN" and not result.can_compensate + assert result.outcome == "CONFIRMED" and not result.can_compensate store.direct_concurrent_touch( "rec-0001", notes_override="human edit after operation" ) @@ -232,7 +232,7 @@ def test_same_task_id_cannot_authorize_a_second_target(live_app, tmp_path: Path) entity_id="rec-0001", intended_delta={"phone": "555-2222"}, ) - assert engine.execute(first).outcome == "UNCERTAIN" + assert engine.execute(first).outcome == "CONFIRMED" writes_before = store.sql_writes_executed assert ( engine.execute(first.model_copy(update={"entity_id": "rec-0002"})).outcome @@ -323,7 +323,7 @@ def test_saved_har_and_undo_preimage_are_encrypted(live_app, tmp_path): intended_delta={"phone": "555-2222"}, ) ) - assert result.outcome == "UNCERTAIN" + assert result.outcome == "CONFIRMED" preimage = ( tmp_path / "encrypted-state" @@ -355,7 +355,7 @@ def test_default_state_keeps_idempotency_across_engine_instances(live_app): entity_id="rec-0001", intended_delta={"phone": "555-2222"}, ) - assert first.execute(task).outcome == "UNCERTAIN" + assert first.execute(task).outcome == "CONFIRMED" writes_before = store.sql_writes_executed second = TransactionalCommitEngine( lens, diff --git a/packages/flow/tests/test_tx_lens.py b/packages/flow/tests/test_tx_lens.py index 8e6611ca4b..30e4ef6cd0 100644 --- a/packages/flow/tests/test_tx_lens.py +++ b/packages/flow/tests/test_tx_lens.py @@ -551,7 +551,7 @@ def test_replace_mode_update_preserves_untouched_fields_in_o1_reads( ) result = engine.execute(task) - assert result.outcome == "UNCERTAIN" + assert result.outcome == "CONFIRMED" assert result.occ_status == "UNKNOWN" assert result.rows_read == 2 assert store.sql_rows_read == 2 # Exactly 2 rows read out of 5,000! @@ -583,7 +583,8 @@ def test_replace_mode_update_preserves_untouched_fields_in_o1_reads( assert result.receipt_path is not None verified = verify_tx_receipt(result.receipt_path, engine.public_key) assert verified["schema_version"] == TX_RECEIPT_SCHEMA - assert verified["outcome"] == "UNCERTAIN" + assert verified["outcome"] == "CONFIRMED" + assert verified["evidence_scope"]["basis"] == "system_api" assert verified["occ_status"] == "UNKNOWN" assert verified["rows_read"] == 2 assert "r0_hmac_sha256" in verified @@ -1030,7 +1031,7 @@ def background_writer(worker_idx: int) -> None: intended_delta={"phone": f"(555) 900-{idx:04d}"}, ) ) - assert clean_res.outcome == "UNCERTAIN" + assert clean_res.outcome == "CONFIRMED" assert clean_res.occ_status == "UNKNOWN" assert clean_res.rows_read == 2 finally: @@ -1283,7 +1284,7 @@ def test_identity_codec_opt_in_and_certified_pack_and_lazy_judge( intended_delta={"phone": "(555) 1010"}, ) ) - assert ok_res.outcome == "UNCERTAIN" + assert ok_res.outcome == "CONFIRMED" # Legacy pack names retain probe observations, but never grant authority uncertified_pack = CertifiedLensPack( diff --git a/packages/flow/tests/test_verifier_validation_reasons.py b/packages/flow/tests/test_verifier_validation_reasons.py index 7a085fd482..2a0af3fc6d 100644 --- a/packages/flow/tests/test_verifier_validation_reasons.py +++ b/packages/flow/tests/test_verifier_validation_reasons.py @@ -38,6 +38,7 @@ "baseline_window", "self_approved", "issued_before_read", + "evidence_scope", ) CANARY = "synthetic-private-diagnostic-DO-NOT-EMIT" diff --git a/packages/flow/tests/test_verify_run.py b/packages/flow/tests/test_verify_run.py index 6e212987ad..108067be9d 100644 --- a/packages/flow/tests/test_verify_run.py +++ b/packages/flow/tests/test_verify_run.py @@ -413,7 +413,14 @@ def _fake_cfg(kind: str, **extra) -> VerifyConfig: return VerifyConfig.model_validate(doc) -def test_separate_session_read_is_screen_readback_and_never_verified( +def _fake_baseline(cfg: VerifyConfig, tmp_path: Path) -> Path: + """A baseline from the fake verifier, so the frame is judged.""" + path = tmp_path / "baseline.json" + capture_baseline(cfg, PARAMS, path) + return path + + +def test_separate_session_read_is_level_3_and_verified_when_the_contract_allows( clean_registry, tmp_path ): register_verifier_factory( @@ -426,16 +433,83 @@ def test_separate_session_read_is_screen_readback_and_never_verified( params=PARAMS, run_record=AGENT_RECORD, authorization_ref="ticket-0000-test", - private_dir=tmp_path, + baseline_path=_fake_baseline(cfg, tmp_path), + private_dir=tmp_path / "private", ) receipt = result["receipt"] assert receipt["effect_verdict"] == "CONFIRMED" - # RFC-0002 decision 6: a separate UI session (Flow tier 2) is a screen - # read, so it can never be independent_readback. + # The wire labels are unchanged: a separate UI session (Flow tier 2) is + # still a screen read in the coarse RFC-0002 label, and oracle tier 1. assert receipt["verification_tier"] == "screen_readback" - assert receipt["outcome"] == "reconciliation_required" assert receipt["oracle_tier"] == 1 + # On the one ladder it is level 3, VERIFIED with basis separate_session, + # because this contract's minimum is independent_session. + assert receipt["checked_how"] == "separate_session" + assert receipt["outcome"] == "verified" + scope = receipt["evidence_scope"] + assert (scope["check_level"], scope["word"], scope["basis"]) == ( + "separate_session", + "VERIFIED", + "separate_session", + ) + assert {"server_side_async_effects", "outbound_effects"} <= set( + scope["not_covered"] + ) assert result["evidence"]["readback"]["effects"][0]["flow_verification_tier"] == 2 + assert verify_run_mod.receipt_problem(receipt) is None + + +def test_separate_session_read_below_a_system_of_record_minimum_is_not_verified( + clean_registry, tmp_path +): + register_verifier_factory( + "fake-session", + lambda cfg, params: _FakeVerifier(VerificationTier.INDEPENDENT_SESSION), + ) + cfg = _fake_cfg("fake-session") + result = verify_run( + cfg, + params=PARAMS, + run_record=AGENT_RECORD, + authorization_ref="ticket-0000-test", + baseline_path=_fake_baseline(cfg, tmp_path), + private_dir=tmp_path / "private", + ) + receipt = result["receipt"] + assert receipt["outcome"] == "reconciliation_required" + scope = receipt["evidence_scope"] + assert (scope["check_level"], scope["word"]) == ("separate_session", "RECORDED") + assert "basis" not in scope + + +def test_tier_1_receipt_cannot_borrow_the_separate_session_rule( + clean_registry, tmp_path +): + register_verifier_factory( + "fake-session", + lambda cfg, params: _FakeVerifier(VerificationTier.INDEPENDENT_SESSION), + ) + cfg = _fake_cfg("fake-session", minimum_effect_strength="independent_session") + receipt = verify_run( + cfg, + params=PARAMS, + run_record=AGENT_RECORD, + authorization_ref="ticket-0000-test", + baseline_path=_fake_baseline(cfg, tmp_path), + private_dir=tmp_path / "private", + )["receipt"] + # Without the block, a level 3 VERIFIED receipt is refused offline. + old_shape = {k: v for k, v in receipt.items() if k != "evidence_scope"} + assert ( + verify_run_mod.receipt_problem(old_shape) + == "verified_without_independent_readback" + ) + # A block whose word disagrees with the outcome is refused. + wrong = dict( + receipt, evidence_scope=dict(receipt["evidence_scope"], word="RECORDED") + ) + wrong["evidence_scope"].pop("basis") + assert verify_run_mod.receipt_problem(wrong) == "evidence_scope" def test_untyped_verifier_is_refused(clean_registry, tmp_path): @@ -465,6 +539,7 @@ def test_receipt_keeps_every_execute_v1_field(cfg, sor, tmp_path): "verification_tier", "checked", "checked_how", + "evidence_scope", } assert receipt["schema_version"] == EFFECT_RECEIPT_SCHEMA # A strict Execute consumer refuses it rather than mistaking it for a diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index 345f21f30e..9fe98e4fef 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,6 +1,28 @@ # CHANGELOG +## Unreleased + +### Features + +- `check_level`: the basis (`separate_session` is level 3; `system_api`, + `activity_log`, `db_frame` and `owned_connection` are level 4), the receipt + words (`VERIFIED`, `SHOWN`, `CONFIRMED`, `ATTESTED`, `RECORDED`) and + `outcome_word`, plus the inverse tier maps and the Execute effect-strength + map. +- `evidence_scope`: the `openadapt.evidence-scope/v1` block and the additive + `evidence_scope` field on `receipt.RunPredicateV1` (`record/run/v1`). A + receipt without it keeps its exact canonical bytes and still verifies; with + it, a `VERIFIED` outcome needs the word `VERIFIED` or `CONFIRMED`, and no + other outcome may carry either (`inconsistent`). Two new shared vectors, + `valid-evidence-scope` and `evidence-scope-disagrees`; the existing ones + are unchanged. A producer with no read-back time lists `read_back_time` in + `not_covered`. +- `ExecuteEvidenceReceiptV1` accepts `verified` at oracle tier 1 (a + separate-session read) when the contract's minimum is exactly + `independent_session`. Every other contract keeps the tier-2 floor, and + every receipt that validated before still validates. + ## v0.24.2 (2026-11-23) 0.24.1 was stamped on main but never published. 0.24.2 is the first diff --git a/packages/types/docs/CONTRACTS.md b/packages/types/docs/CONTRACTS.md index bade1674ef..290f98353f 100644 --- a/packages/types/docs/CONTRACTS.md +++ b/packages/types/docs/CONTRACTS.md @@ -125,8 +125,10 @@ signal. ## Oracle tiers `verified` and `rolled_back_verified` require an observed effect strength -that maps to Seal oracle tier 2 or 3. Tier 0 is visual / OCR. Tier 1 is a -second-session UI read. Neither can mint production `VERIFIED`. +that maps to Seal oracle tier 2 or 3, or tier 1 (a second-session UI read, +check level 3) when the contract's `minimum_effect_strength` is exactly +`independent_session`. Tier 0 is visual / OCR and never verifies. Production +Seals (`production_seal_allowed`) still require tier 2 or 3. The partner adapter is `channel` plus `read`. Tiers, the gate, and a ten-line file oracle are in [ORACLE.md](ORACLE.md). diff --git a/packages/types/openadapt_types/check_level.py b/packages/types/openadapt_types/check_level.py index be7063b459..fc594ab91d 100644 --- a/packages/types/openadapt_types/check_level.py +++ b/packages/types/openadapt_types/check_level.py @@ -34,6 +34,29 @@ When a save or record has several checks, the weakest level wins. +Receipt words and the basis +--------------------------- + +A receipt names its outcome with one word, chosen by :func:`outcome_word` +from the level and the basis (who produced the evidence, not its type): + +- ``VERIFIED``: levels 3 and 4 only, always with a basis. Level 3 has basis + ``separate_session``. Level 4 has ``system_api`` (a cache-bypassed, + version-checked API read), ``activity_log`` (the system's own log), + ``db_frame`` (a database read of the record and its frame) or + ``owned_connection`` (a connection the verifier owns, such as its own SQL + or file read). It means "as of the read-back time, the read-back showed + this value", never "persisted". +- ``SHOWN``: levels 1 and 2, the acting screen re-read. +- ``CONFIRMED``: level 5, the counterparty acknowledged the item. +- ``ATTESTED``: an operator confirmed it. +- ``RECORDED``: the receipt records the run and claims no check. A check that + did not confirm, or a level 3 or 4 read below the run's required level, is + ``RECORDED``. + +``openadapt_types.evidence_scope`` builds the receipt block that states the +level, basis, word and what the evidence did not cover. + This module imports only the standard library, so the contracts and the Flow runtime can both use it. ``openadapt_flow.check_level`` re-exports it. """ @@ -44,11 +67,24 @@ from typing import Iterable, Literal, Optional __all__ = [ + "BASES", + "Basis", "CheckLevel", + "CONFIRMED_WORD", + "OUTCOME_WORDS", + "OutcomeWord", "ReadbackLabel", + "VERIFIED_LEVELS", + "VERIFIED_WORD", + "from_effect_strength", "from_oracle_tier", "from_verification_tier", + "level_for_basis", + "outcome_word", + "to_effect_strength", + "to_oracle_tier", "to_readback_label", + "to_verification_tier", "weakest", ] @@ -143,3 +179,148 @@ def weakest(levels: Iterable[CheckLevel]) -> CheckLevel: """The weakest of ``levels``; ``unchecked`` when there are none.""" return min(levels, default=CheckLevel.UNCHECKED) + + +# -- the inverse maps ---------------------------------------------------------- + +#: Check level to ``VerificationTier`` (lower is stronger). Levels 0 and 5 +#: have no Flow tier. +_TO_VERIFICATION_TIER: dict[CheckLevel, int] = { + level: tier for tier, level in _FROM_VERIFICATION_TIER.items() +} + +#: Check level to Seal ``OracleTier``. ``reopened`` reads through the acting +#: session's screens, so it is ``VISUAL`` like ``same_screen``. +_TO_ORACLE_TIER: dict[CheckLevel, int] = { + CheckLevel.UNCHECKED: 0, + CheckLevel.SAME_SCREEN: 0, + CheckLevel.REOPENED: 0, + CheckLevel.SEPARATE_SESSION: 1, + CheckLevel.SYSTEM_OF_RECORD: 2, + CheckLevel.COUNTERPARTY_CONFIRMED: 3, +} + +#: Execute ``EffectStrengthV1`` names. Each name's rank is its check level. +_EFFECT_STRENGTH: dict[str, CheckLevel] = { + "immediate_screen_confirmation": CheckLevel.SAME_SCREEN, + "persisted_state_reacquisition": CheckLevel.REOPENED, + "independent_session": CheckLevel.SEPARATE_SESSION, + "independent_system_of_record": CheckLevel.SYSTEM_OF_RECORD, +} + + +def to_verification_tier(level: CheckLevel) -> Optional[int]: + """The ``VerificationTier`` for ``level``; None for levels 0 and 5.""" + + return _TO_VERIFICATION_TIER.get(CheckLevel(level)) + + +def to_oracle_tier(level: CheckLevel) -> int: + """The Seal ``OracleTier`` for ``level`` (0 below ``separate_session``).""" + + return _TO_ORACLE_TIER[CheckLevel(level)] + + +def from_effect_strength(name: object) -> CheckLevel: + """The check level of an Execute effect strength; ``unchecked`` if unknown.""" + + value = getattr(name, "value", name) + return _EFFECT_STRENGTH.get(value, CheckLevel.UNCHECKED) # type: ignore[arg-type] + + +def to_effect_strength(level: CheckLevel) -> Optional[str]: + """The Execute effect strength name for ``level``; None for levels 0 and 5.""" + + for name, mapped in _EFFECT_STRENGTH.items(): + if mapped == level: + return name + return None + + +# -- the basis and the receipt word --------------------------------------------- + +#: Who produced the evidence for a ``VERIFIED`` read-back. +Basis = Literal[ + "separate_session", + "system_api", + "activity_log", + "db_frame", + "owned_connection", +] +BASES: tuple[Basis, ...] = ( + "separate_session", + "system_api", + "activity_log", + "db_frame", + "owned_connection", +) +_BASIS_LEVEL: dict[str, CheckLevel] = { + "separate_session": CheckLevel.SEPARATE_SESSION, + "system_api": CheckLevel.SYSTEM_OF_RECORD, + "activity_log": CheckLevel.SYSTEM_OF_RECORD, + "db_frame": CheckLevel.SYSTEM_OF_RECORD, + "owned_connection": CheckLevel.SYSTEM_OF_RECORD, +} + +#: The receipt outcome words. +OutcomeWord = Literal["VERIFIED", "SHOWN", "CONFIRMED", "ATTESTED", "RECORDED"] +VERIFIED_WORD: OutcomeWord = "VERIFIED" +CONFIRMED_WORD: OutcomeWord = "CONFIRMED" +OUTCOME_WORDS: tuple[OutcomeWord, ...] = ( + "VERIFIED", + "SHOWN", + "CONFIRMED", + "ATTESTED", + "RECORDED", +) +#: The only levels a ``VERIFIED`` word may name. +VERIFIED_LEVELS: tuple[CheckLevel, ...] = ( + CheckLevel.SEPARATE_SESSION, + CheckLevel.SYSTEM_OF_RECORD, +) + + +def level_for_basis(basis: str) -> CheckLevel: + """The check level ``basis`` reaches; raises ``ValueError`` for others.""" + + try: + return _BASIS_LEVEL[basis] + except (KeyError, TypeError): + raise ValueError(f"unknown basis {basis!r}") from None + + +def outcome_word( + level: CheckLevel, + basis: Optional[str] = None, + *, + confirmed: bool = True, + attested: bool = False, + minimum: CheckLevel = CheckLevel.SEPARATE_SESSION, +) -> OutcomeWord: + """The receipt word for one check, the same on every path. + + ``level`` is the level the check reached, ``basis`` who produced the + evidence, ``confirmed`` whether the read-back matched, ``attested`` + whether an operator confirmed it, and ``minimum`` the weakest level the + run accepts for ``VERIFIED`` (never below ``separate_session``). + + A level 3 or 4 check is ``VERIFIED`` only with a basis that reaches that + exact level. A basis that names a different level is a producer bug and + raises ``ValueError``; a missing basis fails closed to ``RECORDED``. + """ + + level = CheckLevel(level) + if basis is not None and level_for_basis(basis) != level: + raise ValueError(f"basis {basis!r} does not reach level {level.label}") + if not confirmed: + return "ATTESTED" if attested else "RECORDED" + if level is CheckLevel.COUNTERPARTY_CONFIRMED: + return "CONFIRMED" + if level in VERIFIED_LEVELS: + floor = max(CheckLevel(minimum), CheckLevel.SEPARATE_SESSION) + if basis is not None and level >= floor: + return "VERIFIED" + return "ATTESTED" if attested else "RECORDED" + if level >= CheckLevel.SAME_SCREEN: + return "SHOWN" + return "ATTESTED" if attested else "RECORDED" diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py new file mode 100644 index 0000000000..616f03800e --- /dev/null +++ b/packages/types/openadapt_types/evidence_scope.py @@ -0,0 +1,273 @@ +"""What a receipt's evidence covered: the evidence-scope block. + +Every receipt states, in one closed block, how its write was checked and what +that check did not see: + +- ``check_level``: the level on the one ladder + (:mod:`openadapt_types.check_level`). +- ``word``: the receipt word (``VERIFIED``, ``SHOWN``, ``CONFIRMED``, + ``ATTESTED`` or ``RECORDED``), from :func:`~openadapt_types.check_level.outcome_word`. +- ``basis``: who produced the evidence. Required for ``VERIFIED``. +- ``wire``: the channel the run observed and the protocols it parsed. + Watching the wire is not a read-back: it never makes a word stronger. +- ``read_back_at``: when the read-back ran. ``VERIFIED`` means "as of this + time, the read-back showed the value", never "persisted". +- ``recheck_window_s``: how long after ``read_back_at`` a recheck reads the + record again, when one is scheduled. +- ``not_covered``: what the evidence did not cover. It always lists + ``server_side_async_effects`` and ``outbound_effects``: no read-back sees a + job the server runs later, or a message it sends out. A producer that did + not record when its read-back ran lists ``read_back_time`` instead of a + ``read_back_at`` (a run report has no per-read time yet). + +The block holds only closed values (enums, a timestamp, a count), like the +rest of a ``record/run/v1`` predicate. It is additive: a receipt without it +still verifies, and :func:`predicate_evidence_scope_problem` checks it only +when it is present. +""" + +from __future__ import annotations + +from typing import Any, Final, Iterable, Literal, Mapping, Optional + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + StrictInt, + StrictStr, + ValidationError, + model_validator, +) + +from openadapt_types.check_level import ( + Basis, + CheckLevel, + OutcomeWord, + VERIFIED_LEVELS, + level_for_basis, + outcome_word, +) + +__all__ = [ + "ALWAYS_NOT_COVERED", + "EVIDENCE_SCOPE_FIELD", + "EVIDENCE_SCOPE_SCHEMA", + "EvidenceScopeV1", + "NotCovered", + "WireChannel", + "WireProtocol", + "WireScope", + "build_evidence_scope", + "evidence_scope_problem", + "predicate_evidence_scope_problem", + "with_evidence_scope", +] + +EVIDENCE_SCOPE_SCHEMA: Final = "openadapt.evidence-scope/v1" +#: The additive ``record/run/v1`` predicate field that carries the block. +EVIDENCE_SCOPE_FIELD: Final = "evidence_scope" + +#: The channel the run watched. ``none``: it watched no wire. +WireChannel = Literal[ + "none", + "browser_network", + "http_proxy", + "api_client", + "db_connection", +] +WireProtocol = Literal["http", "graphql", "fhir", "sql", "websocket", "grpc", "smtp"] +#: What a check did not cover. +NotCovered = Literal[ + "server_side_async_effects", + "outbound_effects", + "changes_after_read_back", + "fields_not_read", + "other_records", + "other_actors", + "read_back_time", +] +#: Listed on every receipt: no read-back observes these. +ALWAYS_NOT_COVERED: Final[tuple[NotCovered, ...]] = ( + "server_side_async_effects", + "outbound_effects", +) +_LEVEL_LABEL = Literal[ + "unchecked", + "same_screen", + "reopened", + "separate_session", + "system_of_record", + "counterparty_confirmed", +] +_ISO_SECONDS = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" +_MAX_RECHECK_S: Final = 30 * 24 * 3600 + + +class _Closed(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + +class WireScope(_Closed): + channel: WireChannel + protocols_parsed: list[WireProtocol] = Field(default_factory=list, max_length=7) + + @model_validator(mode="after") + def _closed(self) -> "WireScope": + if len(set(self.protocols_parsed)) != len(self.protocols_parsed): + raise ValueError("wire.protocols_parsed repeats a protocol") + if self.channel == "none" and self.protocols_parsed: + raise ValueError("a run that watched no wire parsed no protocol") + return self + + +class EvidenceScopeV1(_Closed): + """The evidence-scope block (``openadapt.evidence-scope/v1``).""" + + schema_: Literal["openadapt.evidence-scope/v1"] = Field(alias="schema") + check_level: _LEVEL_LABEL + word: OutcomeWord + basis: Optional[Basis] = None + wire: WireScope + read_back_at: Optional[StrictStr] = Field(default=None, pattern=_ISO_SECONDS) + recheck_window_s: Optional[StrictInt] = Field(default=None, ge=0, le=_MAX_RECHECK_S) + not_covered: list[NotCovered] = Field(min_length=2, max_length=7) + + @model_validator(mode="after") + def _consistent(self) -> "EvidenceScopeV1": + level = CheckLevel.from_label(self.check_level) + if len(set(self.not_covered)) != len(self.not_covered): + raise ValueError("not_covered repeats a code") + if not set(ALWAYS_NOT_COVERED) <= set(self.not_covered): + raise ValueError( + "not_covered must list server_side_async_effects and outbound_effects" + ) + if self.basis is not None and level_for_basis(self.basis) != level: + raise ValueError(f"basis {self.basis} does not reach {self.check_level}") + if self.word == "VERIFIED": + if level not in VERIFIED_LEVELS or self.basis is None: + raise ValueError("VERIFIED needs level 3 or 4 and a basis") + if self.read_back_at is None and "read_back_time" not in self.not_covered: + raise ValueError("VERIFIED needs read_back_at, or says it has none") + if self.word == "SHOWN" and not ( + CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED + ): + raise ValueError("SHOWN is a level 1 or 2 re-read of the acting screen") + if self.word == "CONFIRMED" and level is not CheckLevel.COUNTERPARTY_CONFIRMED: + raise ValueError("CONFIRMED is level 5, the counterparty's acknowledgment") + if self.read_back_at is not None and "read_back_time" in self.not_covered: + raise ValueError("a block with read_back_at covers the read-back time") + if self.recheck_window_s is not None and self.read_back_at is None: + raise ValueError("a recheck window needs read_back_at") + return self + + def wire_dict(self) -> dict[str, Any]: + return self.model_dump(mode="json", by_alias=True, exclude_none=True) + + +def build_evidence_scope( + level: CheckLevel, + *, + basis: Optional[str] = None, + confirmed: bool = True, + attested: bool = False, + minimum: CheckLevel = CheckLevel.SEPARATE_SESSION, + wire_channel: str = "none", + protocols_parsed: Iterable[str] = (), + read_back_at: Optional[str] = None, + recheck_window_s: Optional[int] = None, + not_covered: Iterable[str] = (), +) -> dict[str, Any]: + """The evidence-scope block for one check, as a wire dict. + + The word comes from :func:`~openadapt_types.check_level.outcome_word`, so + every path that hands in the same evidence gets the same word. A basis is + dropped from the block when the word is not ``VERIFIED``, so a block never + names a basis it did not rely on. Raises ``ValueError`` for an + inconsistent block. + """ + + level = CheckLevel(level) + word = outcome_word( + level, basis, confirmed=confirmed, attested=attested, minimum=minimum + ) + codes = list(dict.fromkeys((*ALWAYS_NOT_COVERED, *not_covered))) + try: + block = EvidenceScopeV1.model_validate( + { + "schema": EVIDENCE_SCOPE_SCHEMA, + "check_level": level.label, + "word": word, + "basis": basis if word == "VERIFIED" else None, + "wire": { + "channel": wire_channel, + "protocols_parsed": list(dict.fromkeys(protocols_parsed)), + }, + "read_back_at": read_back_at, + "recheck_window_s": recheck_window_s, + "not_covered": codes, + } + ) + except ValidationError as error: + raise ValueError(f"invalid evidence scope: {error}") from None + return block.wire_dict() + + +def evidence_scope_problem(block: object) -> Optional[str]: + """None when ``block`` is a valid evidence-scope block; else the reason.""" + + if not isinstance(block, Mapping): + return "evidence_scope" + try: + EvidenceScopeV1.model_validate(dict(block)) + except ValidationError: + return "evidence_scope" + return None + + +#: The ``record/run/v1`` outcome each word is consistent with. +_PREDICATE_OUTCOMES: Final[Mapping[str, frozenset[str]]] = { + "VERIFIED": frozenset({"VERIFIED"}), + "CONFIRMED": frozenset({"VERIFIED"}), + "SHOWN": frozenset({"UNKNOWN", "STOPPED", "FAILED"}), + "ATTESTED": frozenset({"UNKNOWN", "STOPPED", "FAILED"}), + "RECORDED": frozenset({"UNKNOWN", "STOPPED", "FAILED"}), +} + + +def predicate_evidence_scope_problem(predicate: Mapping[str, Any]) -> Optional[str]: + """Check a ``record/run/v1`` predicate's optional ``evidence_scope``. + + A predicate without the field is an older receipt and passes. With it, + the block must be valid and its word must agree with the predicate's + ``outcome``: a ``VERIFIED`` outcome needs a ``VERIFIED`` or ``CONFIRMED`` + word, and no other outcome may carry either. + """ + + if EVIDENCE_SCOPE_FIELD not in predicate: + return None + block = predicate[EVIDENCE_SCOPE_FIELD] + problem = evidence_scope_problem(block) + if problem is not None: + return problem + allowed = _PREDICATE_OUTCOMES[block["word"]] + if predicate.get("outcome") not in allowed: + return "evidence_scope_outcome" + return None + + +def with_evidence_scope( + predicate: Mapping[str, Any], block: Mapping[str, Any] +) -> dict[str, Any]: + """A copy of ``predicate`` with ``block`` added as ``evidence_scope``. + + Raises ``ValueError`` when the block is invalid or disagrees with the + predicate's outcome. + """ + + out = dict(predicate) + out[EVIDENCE_SCOPE_FIELD] = dict(block) + problem = predicate_evidence_scope_problem(out) + if problem is not None: + raise ValueError(f"evidence scope refused: {problem}") + return out diff --git a/packages/types/openadapt_types/execute.py b/packages/types/openadapt_types/execute.py index d46d9f2107..8bedafba9d 100644 --- a/packages/types/openadapt_types/execute.py +++ b/packages/types/openadapt_types/execute.py @@ -30,6 +30,7 @@ ) from openadapt_types.business_decision import BusinessDecisionTaskV1 +from openadapt_types.check_level import CheckLevel, from_effect_strength from openadapt_types.human_decision import HumanDecisionTaskV1 from openadapt_types.oracle import ( oracle_tier_from_effect_strength, @@ -78,7 +79,9 @@ class EffectStrengthV1(str, Enum): } # Seal oracle ladder. 0 visual, 1 second-session UI, 2 SoR, 3 counterparty. -# Production Seals require 2 or 3. Tier 3 has no EffectStrengthV1 member yet. +# Production Seals require 2 or 3. A verified receipt also accepts tier 1 when +# its contract's minimum is independent_session (_verified_read_allowed). +# Tier 3 has no EffectStrengthV1 member yet. # Mapping and production_seal_allowed live in oracle.py; this alias is the # receipt field so OpenAPI stays an integer enum. OracleTierV1: TypeAlias = Literal[0, 1, 2, 3] @@ -229,12 +232,11 @@ def _validate_proof(self) -> "ExecuteEvidenceReceiptV1": raise ValueError( "observed effect strength is below the required strength" ) - if not production_seal_allowed( - oracle_tier_from_effect_strength( - self.contracts.observed_effect_strength + if not _verified_read_allowed(self.contracts): + raise ValueError( + "a verified outcome requires oracle tier 2 or 3, or a " + "separate-session read under an independent_session minimum" ) - ): - raise ValueError("a verified outcome requires oracle tier 2 or 3") if self.outcome is ExecuteTerminalOutcomeV1.ROLLED_BACK_VERIFIED: if not self.compensation_effect_verified: raise ValueError( @@ -254,11 +256,32 @@ def _validate_proof(self) -> "ExecuteEvidenceReceiptV1": ) if self.oracle_tier != derived: raise ValueError("oracle_tier must match observed_effect_strength") - if verified and self.oracle_tier < 2: + if verified and not _verified_read_allowed(self.contracts): raise ValueError("a verified outcome requires oracle tier 2 or 3") return self +def _verified_read_allowed(contracts: "ExecuteEvidenceContractV1") -> bool: + """Whether the observed read may carry a ``verified`` outcome. + + The check-level ladder (:mod:`openadapt_types.check_level`) is the rule: a + system-of-record read (oracle tier 2 or 3) always may. A separate-session + read (level 3, oracle tier 1) may only when the contract's minimum is + exactly ``independent_session``, so a contract that did not opt in to + separate-session reads keeps the tier-2 floor. Same-screen and reopened + reads never may. + """ + + observed = contracts.observed_effect_strength + if production_seal_allowed(oracle_tier_from_effect_strength(observed)): + return True + level = from_effect_strength(observed) + return ( + level is CheckLevel.SEPARATE_SESSION + and from_effect_strength(contracts.minimum_effect_strength) is level + ) + + class _SignedExecuteWebhookV1(_StrictContract): schema_version: Literal[EXECUTE_WEBHOOK_SCHEMA] = EXECUTE_WEBHOOK_SCHEMA event_id: StrictStr = Field(pattern=_OPAQUE_ID_PATTERN) diff --git a/packages/types/openadapt_types/receipt.py b/packages/types/openadapt_types/receipt.py index a849026050..1a2e4a4e60 100644 --- a/packages/types/openadapt_types/receipt.py +++ b/packages/types/openadapt_types/receipt.py @@ -41,6 +41,12 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError +from openadapt_types.evidence_scope import ( + EVIDENCE_SCOPE_FIELD, + EvidenceScopeV1, + predicate_evidence_scope_problem, +) + STATEMENT_TYPE: Final = "https://in-toto.io/Statement/v1" PREDICATE_TYPE: Final = "https://openadapt.ai/record/run/v1" PAYLOAD_TYPE: Final = "application/vnd.in-toto+json" @@ -323,6 +329,9 @@ class RunPredicateV1(_Closed): #: counterparty confirmations that changed since. Omitted otherwise, so a #: receipt is byte-identical to one made before follow-ups existed. follows: Optional[Follows] = None + #: Additive: what the evidence covered (``openadapt.evidence-scope/v1``). + #: A receipt without it is an older one and still verifies. + evidence_scope: Optional[EvidenceScopeV1] = None class RunStatementV1(_Closed): @@ -339,6 +348,13 @@ def wire(self) -> dict[str, Any]: del out["predicate"]["approval"] if out["predicate"]["follows"] is None: del out["predicate"]["follows"] + scope = self.predicate.evidence_scope + # Left out when absent, so a receipt from before the field keeps its + # exact canonical bytes. + if scope is None: + out["predicate"].pop(EVIDENCE_SCOPE_FIELD, None) + else: + out["predicate"][EVIDENCE_SCOPE_FIELD] = scope.wire_dict() for subject in out["subject"]: if subject["media_type"] is None: del subject["media_type"] @@ -429,6 +445,10 @@ def _check_consistent(statement: RunStatementV1) -> Optional[str]: return "check counts disagree with the lines" if p.outcome == "VERIFIED" and tally["refuted"]: return "a VERIFIED receipt has a refuted line" + if p.evidence_scope is not None and predicate_evidence_scope_problem( + {"outcome": p.outcome, EVIDENCE_SCOPE_FIELD: p.evidence_scope.wire_dict()} + ): + return "the evidence scope's word disagrees with the outcome" steps = [line.step for line in p.lines] if steps != sorted(set(steps)): return "lines are not in step order, or repeat a step" diff --git a/packages/types/tests/test_execute_contract.py b/packages/types/tests/test_execute_contract.py index 1d505b3b68..e8e8d0c1d1 100644 --- a/packages/types/tests/test_execute_contract.py +++ b/packages/types/tests/test_execute_contract.py @@ -163,14 +163,38 @@ def test_receipt_is_the_seal_and_verified_requires_sor_oracle() -> None: with pytest.raises(ValidationError, match="oracle_tier must match"): _receipt(oracle_tier=1) - with pytest.raises(ValidationError, match="oracle tier 2 or 3"): - _receipt( - contracts=_contract( - minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, - observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, - ), - oracle_tier=1, - ) + # A separate-session read (check level 3) is verified when the contract + # opted in with an independent_session minimum. + separate = _receipt( + contracts=_contract( + minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + ), + oracle_tier=1, + ) + assert separate.outcome.value == "verified" + # A lower minimum does not let a separate-session read through, and a + # reopened read never verifies. + for minimum, observed, tier in ( + ( + EffectStrengthV1.IMMEDIATE_SCREEN_CONFIRMATION, + EffectStrengthV1.INDEPENDENT_SESSION, + 1, + ), + ( + EffectStrengthV1.PERSISTED_STATE_REACQUISITION, + EffectStrengthV1.PERSISTED_STATE_REACQUISITION, + 0, + ), + ): + with pytest.raises(ValidationError, match="oracle tier 2 or 3"): + _receipt( + contracts=_contract( + minimum_effect_strength=minimum, + observed_effect_strength=observed, + ), + oracle_tier=tier, + ) def test_webhook_signature_binds_the_closed_state_payload() -> None: diff --git a/packages/types/tests/test_oracle.py b/packages/types/tests/test_oracle.py index 91ddb57599..4f700f3e63 100644 --- a/packages/types/tests/test_oracle.py +++ b/packages/types/tests/test_oracle.py @@ -162,10 +162,21 @@ def test_second_session_adapter_is_valid_and_cannot_seal() -> None: assert obs.tier is OracleTier.INDEPENDENT_SESSION with pytest.raises(ProductionSealRefused, match="oracle tier 2 or 3"): issue_production_verified(obs) - with pytest.raises(ValidationError, match="oracle tier 2 or 3"): + # On the one ladder a separate-session read is check level 3: a receipt + # may say verified when its contract opted in to independent_session, + # but it still can't mint a production Seal (tier 2 or 3, above). + receipt = _receipt( + contracts=_contract( + minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + ), + oracle_tier=1, + ) + assert receipt.outcome is ExecuteTerminalOutcomeV1.VERIFIED + # A contract that didn't opt in keeps the tier-2 floor. + with pytest.raises(ValidationError): _receipt( contracts=_contract( - minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, ), oracle_tier=1, diff --git a/packages/types/tests/vectors/record-run-v1/README.md b/packages/types/tests/vectors/record-run-v1/README.md index 814ab377b2..d6aec22f75 100644 --- a/packages/types/tests/vectors/record-run-v1/README.md +++ b/packages/types/tests/vectors/record-run-v1/README.md @@ -39,7 +39,12 @@ not secrets. Closed schema (see `openadapt_types/receipt.py`); the payload must equal its canonical form (sorted keys, no whitespace, no ASCII escaping), otherwise `malformed`. Contradictions (counts that disagree with `lines`, a VERIFIED - receipt with a refuted line) are `inconsistent`. + receipt with a refuted line) are `inconsistent`. The predicate may carry an + optional `evidence_scope` block (`openadapt.evidence-scope/v1`, closed; see + `openadapt_types/evidence_scope.py`); a receipt without it still verifies. + With it, a `VERIFIED` outcome needs the word `VERIFIED` (level 3 or 4, with + a basis) or `CONFIRMED`, and no other outcome may carry either; otherwise + `inconsistent`. 4. **Commitments.** `sha256("openadapt.receipt-commitment/v1" 0x00 path 0x00 salt(32 raw bytes) 0x00 canonical_json(value))`, as lower-case hex. Salts are 64 lower-case hex characters. diff --git a/packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json b/packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json new file mode 100644 index 0000000000..1fea21c67c --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json @@ -0,0 +1,21 @@ +{ + "description": "A VERIFIED record whose evidence scope says only SHOWN (the acting screen): refused.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlNIT1dOIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn0seyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbImZpZWxkX3ZhbHVlcyJdLCJvcGVyYXRpb24iOiJpcnJldmVyc2libGVfd3JpdGUiLCJzdGVwIjo0LCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn1dLCJtb2RlbF9jYWxscyI6MCwib3V0Y29tZSI6IlZFUklGSUVEIiwicHJvZ3JhbSI6eyJpZCI6InByb2ctNWJiMjFhYTBmMmU2YWMzMiIsInZlcnNpb25fc2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJyZWFzb25fY29kZSI6InZlcmlmaWVkIiwic3RhcnRlZF9ob3VyIjoiMjAyNi0xMS0yMFQyMzowMDowMFoiLCJzdGVwcyI6eyJvayI6NSwidG90YWwiOjV9fSwicHJlZGljYXRlVHlwZSI6Imh0dHBzOi8vb3BlbmFkYXB0LmFpL3JlY29yZC9ydW4vdjEiLCJzdWJqZWN0IjpbeyJkaWdlc3QiOnsic2hhMjU2IjoiMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSJ9LCJuYW1lIjoicmVwb3J0Lmpzb24ifSx7ImRpZ2VzdCI6eyJzaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sIm5hbWUiOiJidW5kbGUifV19", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "hQIe1xXdm0754SwZhjOuh08tmDm+tNfN1wRN0/oIJ7lFUpJSrDDCCVxKOZlPZNK0EtYh5MyuZENit3PNRxQJDQ==" + } + ] + }, + "expected": { + "ok": false, + "reason": "inconsistent", + "signer_lines": [ + "Not verified: the receipt contradicts itself" + ] + }, + "registry": "registry.json" +} diff --git a/packages/types/tests/vectors/record-run-v1/generate.py b/packages/types/tests/vectors/record-run-v1/generate.py index 9ad43646e5..6a2e05c44c 100644 --- a/packages/types/tests/vectors/record-run-v1/generate.py +++ b/packages/types/tests/vectors/record-run-v1/generate.py @@ -224,6 +224,36 @@ def add(name, description, document, expected, openings=None): add("embedded-image-in-record", "A signed record whose payload carries base64 image bytes: refused.", raw_env, {"ok": False, "reason": "embedded_content", "signer_lines": [r.refusal_line("embedded_content")]}) + scoped = statement("VERIFIED") + scoped["predicate"]["evidence_scope"] = { + "schema": "openadapt.evidence-scope/v1", + "check_level": "separate_session", + "word": "VERIFIED", + "basis": "separate_session", + "wire": {"channel": "none", "protocols_parsed": []}, + "not_covered": [ + "server_side_async_effects", + "outbound_effects", + "changes_after_read_back", + "read_back_time", + ], + } + add("valid-evidence-scope", + "A run that states what its evidence covered: a separate-session read, VERIFIED with its basis.", + r.sign_statement(scoped, [signer("this_computer")]), + {**ok_local, "outcome": "VERIFIED", "disclosed": {}}) + shown = copy.deepcopy(scoped) + shown["predicate"]["evidence_scope"].update( + {"check_level": "same_screen", "word": "SHOWN"}) + del shown["predicate"]["evidence_scope"]["basis"] + payload = r.canonical_json(shown).encode() + shown_env = {"payloadType": r.PAYLOAD_TYPE, "payload": base64.b64encode(payload).decode(), + "signatures": [{"keyid": IDS["this_computer"], + "sig": base64.b64encode(KEYS["this_computer"].sign(r.pae(r.PAYLOAD_TYPE, payload))).decode()}]} + add("evidence-scope-disagrees", + "A VERIFIED record whose evidence scope says only SHOWN (the acting screen): refused.", + shown_env, {"ok": False, "reason": "inconsistent", + "signer_lines": [r.refusal_line("inconsistent")]}) other = statement("VERIFIED") other["predicateType"] = "https://openadapt.ai/record/run/v9" payload = r.canonical_json(other).encode() diff --git a/packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json new file mode 100644 index 0000000000..1be4038c0c --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json @@ -0,0 +1,24 @@ +{ + "description": "A run that states what its evidence covered: a separate-session read, VERIFIED with its basis.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoic2VwYXJhdGVfc2Vzc2lvbiIsImNoZWNrX2xldmVsIjoic2VwYXJhdGVfc2Vzc2lvbiIsIm5vdF9jb3ZlcmVkIjpbInNlcnZlcl9zaWRlX2FzeW5jX2VmZmVjdHMiLCJvdXRib3VuZF9lZmZlY3RzIiwiY2hhbmdlc19hZnRlcl9yZWFkX2JhY2siLCJyZWFkX2JhY2tfdGltZSJdLCJzY2hlbWEiOiJvcGVuYWRhcHQuZXZpZGVuY2Utc2NvcGUvdjEiLCJ3aXJlIjp7ImNoYW5uZWwiOiJub25lIiwicHJvdG9jb2xzX3BhcnNlZCI6W119LCJ3b3JkIjoiVkVSSUZJRUQifSwibGluZXMiOlt7ImNoZWNrIjoiY29uZmlybWVkIiwibm90X2NoZWNrZWQiOltdLCJvcGVyYXRpb24iOiJ3cml0ZSIsInN0ZXAiOjIsInN0cmVuZ3RoIjoicmVhZF9iYWNrIiwidGFyZ2V0X2tpbmQiOiJndWkifSx7ImNoZWNrIjoiY29uZmlybWVkIiwibm90X2NoZWNrZWQiOlsiZmllbGRfdmFsdWVzIl0sIm9wZXJhdGlvbiI6ImlycmV2ZXJzaWJsZV93cml0ZSIsInN0ZXAiOjQsInN0cmVuZ3RoIjoicmVhZF9iYWNrIiwidGFyZ2V0X2tpbmQiOiJndWkifV0sIm1vZGVsX2NhbGxzIjowLCJvdXRjb21lIjoiVkVSSUZJRUQiLCJwcm9ncmFtIjp7ImlkIjoicHJvZy01YmIyMWFhMGYyZTZhYzMyIiwidmVyc2lvbl9zaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sInJlYXNvbl9jb2RlIjoidmVyaWZpZWQiLCJzdGFydGVkX2hvdXIiOiIyMDI2LTExLTIwVDIzOjAwOjAwWiIsInN0ZXBzIjp7Im9rIjo1LCJ0b3RhbCI6NX19LCJwcmVkaWNhdGVUeXBlIjoiaHR0cHM6Ly9vcGVuYWRhcHQuYWkvcmVjb3JkL3J1bi92MSIsInN1YmplY3QiOlt7ImRpZ2VzdCI6eyJzaGEyNTYiOiIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExIn0sIm5hbWUiOiJyZXBvcnQuanNvbiJ9LHsiZGlnZXN0Ijp7InNoYTI1NiI6IjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIifSwibmFtZSI6ImJ1bmRsZSJ9XX0=", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "NOVgbnNHOFefPfCOT7yjdyDwAFviWm0JMotmlschaGkXYd7H+Iy8QslZ97Uk2Hus4x4lj8WkqAMojkzO1UuODg==" + } + ] + }, + "expected": { + "demo": false, + "disclosed": {}, + "ok": true, + "outcome": "VERIFIED", + "reason": null, + "signer_lines": [ + "Signed by this computer" + ] + }, + "registry": "registry.json" +} diff --git a/packages/verify/tests/test_tx_verify_facade.py b/packages/verify/tests/test_tx_verify_facade.py index 5c002a0f31..dfb68f581f 100644 --- a/packages/verify/tests/test_tx_verify_facade.py +++ b/packages/verify/tests/test_tx_verify_facade.py @@ -348,7 +348,7 @@ def test_end_to_end_network_capture_to_certified_pack_and_cli_tx_run( str(state_dir), ] ) - assert rc_run == 3 + assert rc_run == 0 after_row = dict( conn.execute("SELECT * FROM tasks WHERE id = ?", (clean_id,)).fetchone() ) @@ -365,7 +365,9 @@ def test_end_to_end_network_capture_to_certified_pack_and_cli_tx_run( priv_key.public_key(), log_dir=state_dir / "log", ) - assert verified_payload["outcome"] == "UNCERTAIN" + assert verified_payload["outcome"] == "CONFIRMED" + assert verified_payload["evidence_scope"]["word"] == "VERIFIED" + assert verified_payload["evidence_scope"]["basis"] == "system_api" assert verified_payload["qualification_state"] == "unqualified" assert verified_payload["rows_read"] == 2 diff --git a/tests/test_verify_seal_action.py b/tests/test_verify_seal_action.py index 53feabcb2c..d3b8db143b 100644 --- a/tests/test_verify_seal_action.py +++ b/tests/test_verify_seal_action.py @@ -21,13 +21,19 @@ def _ensure_in_tree_types() -> None: types_dir = str(ROOT / "packages" / "types") + in_tree_pkg = str(ROOT / "packages" / "types" / "openadapt_types") if types_dir not in sys.path: sys.path.insert(0, types_dir) pkg = sys.modules.get("openadapt_types") if pkg is not None and hasattr(pkg, "__path__"): - in_tree_pkg = str(ROOT / "packages" / "types" / "openadapt_types") if in_tree_pkg not in pkg.__path__: pkg.__path__.insert(0, in_tree_pkg) + for mod_name in list(sys.modules): + if mod_name == "openadapt_types" or mod_name.startswith("openadapt_types."): + mod = sys.modules.get(mod_name) + mod_file = getattr(mod, "__file__", None) or "" + if mod_name != "openadapt_types" and not mod_file.startswith(in_tree_pkg): + sys.modules.pop(mod_name, None) def _load_module() -> Any: