From 8ac01cb338f78f97e83f2ce424a91b3c0ea9374a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:48:06 -0500 Subject: [PATCH 01/14] feat(flow): one verdict kernel, a fail-open harness and a fold ratchet Fail-open blockers kept coming back one PR at a time. This fixes the classes once: - openadapt_flow/verdict.py: obligations fixed from the plan, settle(), allow-list codes, run binding, trust labels. An empty set, a short read, a raised probe, another run's result or an unknown code never passes. - tests/failopen: 13 generic mutations run against every @verdict_site. The self-test flags 14 historical bugs rebuilt from this repository's code and passes their fixes; three live sites on main are strict xfails owned by #2470, #2258 and the connector status follow-up. - scripts/check_verdict_folds.py: fails CI when a file gains a hand-written fold; never on a drop. - verify_run: an empty or unpaired effect list is INDETERMINATE, unknown and unchecked (latent behind min_length=1). See packages/flow/docs/FAIL_CLOSED.md. --- .github/workflows/packages.yml | 8 + CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 18 + packages/flow/docs/FAIL_CLOSED.md | 183 +++ .../flow/openadapt_flow/hard_invariants.py | 3 + .../runtime/effects/versions.py | 2 + packages/flow/openadapt_flow/verdict.py | 474 +++++++ packages/flow/openadapt_flow/verdict_sites.py | 36 + packages/flow/openadapt_flow/verify_run.py | 45 +- packages/flow/public-artifacts.json | 4 + packages/flow/scripts/check_verdict_folds.py | 337 +++++ packages/flow/scripts/verdict_folds.toml | 33 + .../flow/scripts/verdict_folds_baseline.json | 1236 +++++++++++++++++ packages/flow/tests/failopen/__init__.py | 0 packages/flow/tests/failopen/corpus/urls.json | 31 + .../flow/tests/failopen/corpus/values.json | 25 + packages/flow/tests/failopen/harness.py | 310 +++++ packages/flow/tests/failopen/mutators.py | 243 ++++ .../flow/tests/failopen/selftest/__init__.py | 0 .../failopen/selftest/_v_s1_receipt_post.py | 91 ++ .../failopen/selftest/_v_s1_receipt_pre.py | 85 ++ .../failopen/selftest/_v_s2_audit_post.py | 83 ++ .../failopen/selftest/_v_s2_audit_pre.py | 80 ++ .../failopen/selftest/_v_s3_undo_post.py | 65 + .../tests/failopen/selftest/_v_s3_undo_pre.py | 62 + .../selftest/_v_s4_form_judge_post.py | 101 ++ .../failopen/selftest/_v_s4_form_judge_pre.py | 89 ++ .../failopen/selftest/_v_s5_gate_head.py | 97 ++ .../tests/failopen/selftest/_v_s5_gate_pre.py | 86 ++ .../failopen/selftest/_v_s6_typeahead_post.py | 118 ++ .../failopen/selftest/_v_s6_typeahead_pre.py | 108 ++ .../failopen/selftest/_v_s7_cancel_post.py | 70 + .../failopen/selftest/_v_s7_cancel_pre.py | 46 + .../failopen/selftest/_v_s8_governed_post.py | 255 ++++ .../failopen/selftest/_v_s9_verify_run_pre.py | 61 + .../failopen/selftest/_v_wire_tap_post.py | 91 ++ .../flow/tests/failopen/selftest/specs.py | 473 +++++++ .../flow/tests/failopen/sites/__init__.py | 0 packages/flow/tests/failopen/sites/_vocab.py | 27 + .../tests/failopen/sites/connector_status.py | 88 ++ .../tests/failopen/sites/governed_safety.py | 87 ++ .../tests/failopen/sites/hard_invariants.py | 50 + .../tests/failopen/sites/verify_run_folds.py | 109 ++ .../tests/failopen/sites/versions_judge.py | 67 + .../tests/failopen/sites/wire_tap_relay.py | 61 + packages/flow/tests/failopen/test_kernel.py | 252 ++++ .../tests/failopen/test_kernel_mutants.py | 116 ++ .../tests/failopen/test_registry_complete.py | 104 ++ packages/flow/tests/failopen/test_selftest.py | 41 + packages/flow/tests/failopen/test_sites.py | 32 + .../failopen/test_verify_run_migration.py | 70 + .../flow/tests/test_verdict_folds_check.py | 77 + 53 files changed, 6225 insertions(+), 7 deletions(-) create mode 100644 packages/flow/docs/FAIL_CLOSED.md create mode 100644 packages/flow/openadapt_flow/verdict.py create mode 100644 packages/flow/openadapt_flow/verdict_sites.py create mode 100644 packages/flow/scripts/check_verdict_folds.py create mode 100644 packages/flow/scripts/verdict_folds.toml create mode 100644 packages/flow/scripts/verdict_folds_baseline.json create mode 100644 packages/flow/tests/failopen/__init__.py create mode 100644 packages/flow/tests/failopen/corpus/urls.json create mode 100644 packages/flow/tests/failopen/corpus/values.json create mode 100644 packages/flow/tests/failopen/harness.py create mode 100644 packages/flow/tests/failopen/mutators.py create mode 100644 packages/flow/tests/failopen/selftest/__init__.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s1_receipt_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s1_receipt_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s2_audit_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s2_audit_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s3_undo_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s3_undo_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s4_form_judge_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s4_form_judge_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s5_gate_head.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s5_gate_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s6_typeahead_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s6_typeahead_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s7_cancel_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s7_cancel_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s8_governed_post.py create mode 100644 packages/flow/tests/failopen/selftest/_v_s9_verify_run_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_wire_tap_post.py create mode 100644 packages/flow/tests/failopen/selftest/specs.py create mode 100644 packages/flow/tests/failopen/sites/__init__.py create mode 100644 packages/flow/tests/failopen/sites/_vocab.py create mode 100644 packages/flow/tests/failopen/sites/connector_status.py create mode 100644 packages/flow/tests/failopen/sites/governed_safety.py create mode 100644 packages/flow/tests/failopen/sites/hard_invariants.py create mode 100644 packages/flow/tests/failopen/sites/verify_run_folds.py create mode 100644 packages/flow/tests/failopen/sites/versions_judge.py create mode 100644 packages/flow/tests/failopen/sites/wire_tap_relay.py create mode 100644 packages/flow/tests/failopen/test_kernel.py create mode 100644 packages/flow/tests/failopen/test_kernel_mutants.py create mode 100644 packages/flow/tests/failopen/test_registry_complete.py create mode 100644 packages/flow/tests/failopen/test_selftest.py create mode 100644 packages/flow/tests/failopen/test_sites.py create mode 100644 packages/flow/tests/failopen/test_verify_run_migration.py create mode 100644 packages/flow/tests/test_verdict_folds_check.py diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 390c5c0874..140b79b07e 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -563,6 +563,12 @@ jobs: # App knowledge lives in profiles, contracts and fixtures (CONTRIBUTING: # "App knowledge lives in data"); the denylist is scripts/generality.toml. run: python scripts/check_engine_generality.py + - name: No new hand-written verdict folds + # A check that can pass on an empty set, a short read or an unknown + # code is folded once in openadapt_flow/verdict.py; a new fold goes in + # a @verdict_site with a spec under tests/failopen (docs/FAIL_CLOSED.md). + # Fails only when a file's count rises above the baseline. + run: python scripts/check_verdict_folds.py - name: Install uv (for the oldest-Python syntax check) uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Syntax at the oldest supported Python (3.10) @@ -599,6 +605,8 @@ jobs: openadapt_flow/runtime/replay/ \ openadapt_flow/runtime/resolver.py \ openadapt_flow/submit_binding.py \ + openadapt_flow/verdict.py \ + openadapt_flow/verdict_sites.py \ openadapt_flow/runtime/effects/effect.py \ openadapt_flow/runtime/effects/adapter.py \ openadapt_flow/runtime/effects/auth.py \ diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cad88c6b1c..4a458a10f7 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -177,6 +177,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 14 historical fail-open bugs rebuilt from this repository's own code (vendored pre-fix copies and three live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/llms-full.txt b/llms-full.txt index d67812cb9a..bb0c8db312 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -611,6 +611,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 14 historical fail-open bugs rebuilt from this repository's own code (vendored pre-fix copies and three live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 9469c2d499..e503f5165f 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,8 +17,26 @@ ## Unreleased +### Features + +- One verdict kernel, `openadapt_flow.verdict`, for every check that turns + evidence into held, refuted or not checked. It fixes the obligations from + the plan first, settles results against them, and never passes an empty + set, a truncated or short read, a probe that raised, a result bound to + another run, two results that disagree, or a code nobody listed. Functions + marked `@verdict_site` are run by a fail-open harness + (`tests/failopen`) with 13 generic mutations; it flags 14 historical bugs + rebuilt from this repository's code and passes their fixes. + `scripts/check_verdict_folds.py` fails CI when a file gains a hand-written + fold. See `docs/FAIL_CLOSED.md`. + ### Fixes +- `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 + refuses an empty list, so no run changes outcome today. + - `wrap publish` no longer refuses programs whose identity templates carry `punctuation_body_keys`. These values are salted token hashes, the same generated shape as the `c` and `r` keys, but the sanitizer sent them to diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md new file mode 100644 index 0000000000..8cd29670e4 --- /dev/null +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -0,0 +1,183 @@ +# Fail closed: the verdict kernel, the harness and the ratchet + +A check fails open when it reports a pass that its evidence doesn't support. +Reviews of the November 2026 pull requests found about 20 blocking bugs of +this kind, and most were one of seven shapes. Fixing each one where it was +found didn't stop the next one, so the shapes are now fixed in one place: + +- `openadapt_flow/verdict.py`, the kernel, folds evidence into a verdict once. +- `tests/failopen`, the harness, runs the same mutations against every + function that makes a verdict. +- `scripts/check_verdict_folds.py`, the ratchet, fails CI when a file gains a + verdict fold written by hand. + +## The classes + +| Class | Shape | Example (pull request) | +|---|---|---| +| C1 | The obligations come from what was checked, not from what was written: a written field with no expected value gets no verdict; a tally runs over the first 256 writes; a read stops before the cursor. | #2429, #2394, #2437 | +| C2 | An empty set passes: `all([])` is true, so no effects reads as all confirmed. | `verify_run._aggregate([])` before this change | +| C3 | A code nobody listed passes: a deny-list, a final `else: "CONFIRMED"`, a write with no undo counted as rolled back. | #2428 | +| C4 | A weak default or a dropped denominator: `min_scored=1`, runs left out of a rate, a signature labelled "this computer" whatever verified it. | #2419, #2394 | +| C5 | Close values treated as equal: `''` and NULL, a type-ahead prefix, `"250"` and `"$1,250.00"`, `1` and `"1"`. | #2258, #2448 | +| C6 | A URL a parser reads one way and a browser another: `///host`, `/\host`, userinfo, a redirect chain. | #2470, #2414 | +| C7 | An outcome that may have changed something is reported as a plain failure or as "nothing changed": a cancel after the child started, `RECONCILIATION_REQUIRED` mapped to `failed`. | #2300 | + +## The rules + +1. **Fix the obligations first.** `Obligations.fix(items, source=...)` takes + the plan: what the run wrote, what the plan staged, the runs that were + planned. It never takes what a check happened to return. It may be empty. +2. **Settle, don't fold.** `settle(obligations, results, limit=...)` puts each + obligation in exactly one of held, refuted, not checked, missing, mismatched + or conflicting, and lists results nobody asked for as unexpected. The + settlement passes only when every obligation held and nothing else is + present. An empty set never passes, and nothing is cut at the limit: more + obligations than the limit sets `over_limit`. +3. **Only a complete observation holds.** `Result.held` needs an `Observed` + value with `complete=True`. A read that found nothing is `Missing`, one that + raised is `Errored`, and both give `NOT_CHECKED`. `observe(fn)` turns a probe + into one of these and never returns a default. Writing + `Result(subject, Status.HELD, ...)` directly raises `TypeError`. +4. **Codes are allow-listed.** `from_code(code, held=..., refuted=...)` maps any + code not listed to `NOT_CHECKED`. +5. **Bind the result to the run.** A `Subject` names the thing checked + (system, surface, table, key, field) and the run it belongs to (run id, + nonce, digest). A result whose binding disagrees with the obligation is + mismatched, so a result from another run or from a decoy table doesn't + count. +6. **Say who signed only from a verified source.** `trust_label(source, + verified=...)` names the signer only for a verified `TrustSource`; anything + else is "not verified". +7. **Rates use the planned total.** `Settlement.rate(of)` divides by the + number of obligations, never by the number that happened to be scored. +8. **Each site states its own failure order.** `Settlement.label(precedence=...)` + returns `HELD` only when the settlement passes; otherwise it returns the + first status in the site's order that applies. The kernel doesn't impose one + total order, because that would silently relabel existing results. + +## Register a site + +Any function that turns evidence into a verdict is a site. + +1. Build the verdict on `settle` (or `Result.from_code` for an upstream code). +2. Mark the function: + + ```python + from openadapt_flow.verdict_sites import verdict_site + + @verdict_site("my_area.judge", classes="C1 C2") + def judge(...): ... + ``` + + The decorator does nothing at run time beyond recording the site. +3. Add a spec under `tests/failopen/sites/` and `register(...)` it. A spec says + how to call the site, what a pass is, and gives seeds (evidence with the + correct answer). It also gives lenses that point at the parts of the + evidence the mutations change: the per-obligation results, the plan, the + required fields, the observed values, the run binding, a corpus and the + outcome codes. Fill in the lenses that apply; each one switches on its + mutations. + +`test_registry_complete.py` fails when a decorated site has no spec, or a spec +names a function that isn't decorated. The ratchet doesn't count folds inside +a decorated function. + +## The mutations and properties + +| Mutation | What it does | Must | +|---|---|---| +| M1 | drop a result, keep the plan | not pass | +| M2 | grow to the limit plus one, the last result bad | not pass | +| M3 | no results, no plan | not pass (unless the spec says an empty set is vacuous, with the reason) | +| M4 | the probe raises `Exception`, `TimeoutError`, an HTTP 503 | not pass | +| M5 | a required field missing or null | not pass | +| M6 | reorder the results | change nothing | +| M7 | repeat a result; repeat it with a bad copy | not improve; not pass | +| M8 | a result bound to another run | not pass | +| M9 | sweep a knob; relabel a scored run as not scored | the default is the strictest value; not pass | +| M10 | perturb a value: prefix, superstring, `''`, null, absent, number for string | not pass | +| M11 | a corpus entry (`corpus/urls.json`, `corpus/values.json`) | not accepted | +| M12 | an outcome after delivery that may have changed something | not reported as a plain failure or as nothing changed | +| M14 | a code no list names | not pass | + +On every seed the site must give the correct answer (P0), and a mutation that +only removes or corrupts evidence must never turn a not-pass into a pass (P1). +A crash counts as a not-pass. M13, a trust-source swap, waits for the signer +vectors (follow-up 5). + +## The self-test + +`tests/failopen/selftest/` holds the pre-fix code of historical bugs, copied +from this repository's history. The first line of each file names the commit +and the lines; the copied lines sit between `# fmt: off` and `# fmt: on`. +`test_selftest.py` requires the harness to flag every pre-fix copy and to pass +every post-fix copy: + +| Bug | Pre-fix | Post-fix | Caught by | +|---|---|---|---| +| S1 receipt tally after the 256-line slice (#2394) | `adef5a431^` | `adef5a431` | M2 | +| S2 audit read ends at an old-stamped event before the cursor (#2437) | `de5ee3db2^` | `de5ee3db2` | M2, M7 | +| S3 a write with no undo counted as rolled back (#2428) | `fda539c78^` | `fda539c78` | M14 | +| S4 a written field with no expected value gets no verdict (#2429) | `fa26f69fc^` | `fa26f69fc` | M1 | +| S5 `min_scored=1`; an undelivered fault drops a run from the rates (#2419) | `275199914^` and `275199914` | open | M9 | +| S6 a type-ahead prefix matches an assumed typed baseline (#2448) | `c329c57dc^` | `c329c57dc` | P0, M11 | +| S7 a cancel after the child started is reported as failed (#2300) | `fd7133866` | #2300 head | M12 | +| S8 `''` and NULL in the governed check (#2258) | main | `00a55cc16` | P0, M10 | +| Wire tap relays `///host` raw (#2470) | main | #2470 head | M11 | +| S9 `verify_run` folds pass an empty effect list | main before this change | main | M1, M3 | + +Three sites on main are still fail-open and are owned by open pull requests. +Their specs are `xfail(strict=True)` with the owner in the reason: when the fix +lands, the test passes unexpectedly and fails, so the marker has to come out +in the same change. + +- `wire_tap.relay_redirect_location`: `///evil.example/x` is relayed raw (#2470). +- `governed_safety.check`: a held target note changed between `''` and NULL + reads as no write (#2258). +- `connector.status_from_report`: a report whose `transaction_outcome` is + `RECONCILIATION_REQUIRED` and whose `execution_outcome` is `FAILED` maps to + `failed`; the cases come from `outcomes.json` (follow-up 3). + +## The ratchet + +`scripts/check_verdict_folds.py` runs in the required `ci` check, next to the +engine-generality check. It counts, per file in `openadapt_flow/`, the +launcher and `scripts/ci/`, six kinds of hand-written fold: a success literal +produced in code (`VERIFIED`, `CONFIRMED`, `held`, ...), a compare against an +outcome literal, `all()`/`any()` over verdicts or results, a broad `except` +that returns without a raise or a not-checked value, a slice in a statement +that counts, and a final `else` that assigns success. It fails only when a +file's count rises above `verdict_folds_baseline.json`. It never fails on a +drop, so open pull requests that don't add folds are unaffected. To add +verdict code, put it in a `@verdict_site` with a spec; the ratchet doesn't +count inside one. When a file is renamed, move its baseline entry in the same +change. + +## Review rule + +A C1 to C7 blocker is fixed by moving the fold onto `settle` and registering a +spec, not by a local patch. A reviewer who finds one asks for the spec. + +## Follow-ups + +1. Owners adopt: #2429, #2258, #2470 and #2300 replace their local patch with + `settle` plus a spec and remove the strict xfail. The stacked pull requests + (#2437, #2394, #2428, #2457, #2413, #2419, #2414, #2448) register their + sites when they rebase. +2. One owner for `receipt_record`; the #2394 and #2437 stacks carry copies + that have diverged. +3. A connector `unknown` status derived from `outcomes.json` + `may_have_changed`, with a control-plane contract bump. +4. `confirms()` and `changed()` over `readback_values.compare_value`, keeping + `''`, NULL and absent distinct. +5. Provenance and `signers.json` vectors shared by the Python and JS label + renderers, then M13. +6. Strict defaults: `min_scored` is the planned total. +7. `safe_url` in Python and JS from the shared URL corpus. +8. `tx/lens.py`'s final `else: outcome = "CONFIRMED"` becomes an allow-list. +9. Move `verdict.py` to `openadapt_types` at the next types release. +10. A capability token for `Judgement` and receipt v2, verified by recompute. +11. A nightly real-app lane for the negative controls: a database killed + mid-read, a short audit page, a decoy table, a cancel after delivery, a + cross-origin redirect. diff --git a/packages/flow/openadapt_flow/hard_invariants.py b/packages/flow/openadapt_flow/hard_invariants.py index ad5f4a0210..6ac8bb0ed3 100644 --- a/packages/flow/openadapt_flow/hard_invariants.py +++ b/packages/flow/openadapt_flow/hard_invariants.py @@ -11,6 +11,8 @@ from dataclasses import dataclass from typing import Literal, Optional, TypeGuard +from openadapt_flow.verdict_sites import verdict_site + InvariantName = Literal["declared_scope", "at_most_one", "no_undeclared_deletes"] InvariantStatus = Literal["held", "refuted", "not_checked"] LAYER_SCHEMA = "openadapt.hard-invariants/v1" @@ -84,6 +86,7 @@ def _zero( ) +@verdict_site("hard_invariants.judge", classes="C2 C5") def judge_hard_invariants( *, outside_scope_changes: Optional[int], diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py index 3f10ca3026..7d8544e34d 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -40,6 +40,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator from openadapt_flow.runtime.effects.effect import ValueExpr +from openadapt_flow.verdict_sites import verdict_site VersionStatus = Literal["held", "refuted", "not_checked"] @@ -219,6 +220,7 @@ def _resolve_self( return out +@verdict_site("versions.judge", classes="C1 C5") def judge_versions( spec: FrameVersions, stored: Mapping[str, Any], diff --git a/packages/flow/openadapt_flow/verdict.py b/packages/flow/openadapt_flow/verdict.py new file mode 100644 index 0000000000..51ac4f63c6 --- /dev/null +++ b/packages/flow/openadapt_flow/verdict.py @@ -0,0 +1,474 @@ +"""One fold for every verdict: obligations fixed first, then settled. + +Reviews kept finding the same fail-open bugs one pull request at a time. A +check passed on an empty set, on the first N of more than N writes, on a read +that raised, on a result for a different run, or on an outcome code nobody +listed. Each was fixed where it was found. This module fixes the classes once +(``docs/FAIL_CLOSED.md`` names them C1 to C7): + +- :class:`Obligations` is the set of things that must be checked. It comes + from the plan (what the run wrote), never from what a check happened to + return, and it may be empty. +- :class:`Result` is one check of one :class:`Subject`. ``HELD`` can only be + made from a complete :class:`Observed` value (:meth:`Result.held`) or from + an allow-listed upstream code (:meth:`Result.from_code`). A read that raised + or found nothing gives ``NOT_CHECKED``; it never defaults to a pass. +- :func:`settle` matches results to obligations. An obligation with no result, + a result nobody asked for, a result bound to a different run, two results + that disagree, or more obligations than the limit all keep the settlement + from passing. Nothing is truncated, and an empty set never passes. +- :func:`from_code` maps an outside code to a status by allow-list: a code + nobody listed is ``NOT_CHECKED``. +- :func:`trust_label` says who signed something only from a verified trust + source; any other signature is "not verified". + +Stdlib only, so it can move to ``openadapt_types`` unchanged. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field, replace +from enum import Enum +from fractions import Fraction +from typing import Optional, Union + +__all__ = [ + "Errored", + "FailClosed", + "Missing", + "Observation", + "Observed", + "Obligations", + "Result", + "Settlement", + "Status", + "Subject", + "TrustSource", + "binding_mismatches", + "from_code", + "observe", + "require_bound", + "settle", + "trust_label", +] + + +class Status(str, Enum): + """The three values a check can have. There is no fourth.""" + + HELD = "held" + REFUTED = "refuted" + NOT_CHECKED = "not_checked" + + +# -- observations ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class Observed: + """A value that was read. ``complete=False`` when the read was partial + (a short page, a capped query): it can refute, never hold.""" + + value: object + complete: bool = True + + +@dataclass(frozen=True) +class Missing: + """The read found nothing to judge (no row, no file, no key).""" + + reason: str + + +@dataclass(frozen=True) +class Errored: + """The read raised. Only the exception's type and a short reason are kept.""" + + exc_type: str + reason: str + + +Observation = Union[Observed, Missing, Errored] + + +class FailClosed(Exception): + """Raised by a probe to stop the run. :func:`observe` never swallows it.""" + + +def observe( + fn: Callable[[], object], + *, + benign: Optional[Mapping[type[BaseException], Observation]] = None, +) -> Observation: + """Run a probe and turn what happened into an :data:`Observation`. + + A returned :data:`Observation` passes through; any other value becomes + :class:`Observed`. :class:`FailClosed` re-raises. An exception listed in + ``benign`` maps to its declared observation (a 404 that means "no such + row" is ``Missing``, never a value). Any other ``Exception`` becomes + :class:`Errored`. It never returns a default value. + """ + + try: + value = fn() + except FailClosed: + raise + except Exception as exc: # noqa: BLE001 - every failure becomes Errored + for kind, mapped in (benign or {}).items(): + if isinstance(exc, kind): + return mapped + return Errored(type(exc).__name__, str(exc)[:200]) + if isinstance(value, (Observed, Missing, Errored)): + return value + return Observed(value) + + +# -- subjects and binding --------------------------------------------------------- + +#: The subject fields that bind a result to one run. When an obligation sets +#: one, a result must carry the same value. +BINDING_FIELDS = ("run_id", "nonce", "digest") + + +@dataclass(frozen=True) +class Subject: + """What one check is about, and which run it belongs to. + + ``key_tuple`` names the thing (system, surface, table, key, field): the + table, key and field are bound together, so a decoy table holding the + same key is a different subject. ``run_id``, ``nonce`` and ``digest`` bind + a result to the run that produced it (:func:`binding_mismatches`). + """ + + run_id: str = "" + nonce: str = "" + system: str = "" + surface: str = "" + table: Optional[str] = None + key: Optional[str] = None + field: Optional[str] = None + digest: Optional[str] = None + + def key_tuple( + self, + ) -> tuple[str, str, Optional[str], Optional[str], Optional[str]]: + return (self.system, self.surface, self.table, self.key, self.field) + + def bound( + self, + *, + run_id: Optional[str] = None, + nonce: Optional[str] = None, + digest: Optional[str] = None, + ) -> "Subject": + """A copy bound to a run, a nonce and a digest (unset ones are kept).""" + + return replace( + self, + run_id=self.run_id if run_id is None else run_id, + nonce=self.nonce if nonce is None else nonce, + digest=self.digest if digest is None else digest, + ) + + +def binding_mismatches(expected: Subject, got: Subject) -> tuple[str, ...]: + """The binding fields ``expected`` sets that ``got`` does not match. + + A field ``expected`` leaves empty binds nothing. A field it sets must be + equal in ``got``; an empty one in ``got`` is a mismatch, not a wildcard. + """ + + out = [] + for name in BINDING_FIELDS: + want = getattr(expected, name) + if want and getattr(got, name) != want: + out.append(name) + return tuple(out) + + +def require_bound(expected: Subject, got: Subject) -> None: + """Raise :class:`FailClosed` unless ``got`` is bound like ``expected``.""" + + wrong = binding_mismatches(expected, got) + if wrong: + raise FailClosed(f"bound to a different run: {', '.join(wrong)}") + + +# -- results ---------------------------------------------------------------------- + +#: Only this module's constructors hold it, so ``Result(..., Status.HELD, ...)`` +#: written anywhere else raises. +_JUDGED = object() + + +@dataclass(frozen=True) +class Result: + """One check of one subject. Build it with the class methods.""" + + subject: Subject + status: Status + reason: str + _token: object = field(default=None, repr=False, compare=False) + + def __post_init__(self) -> None: + if not isinstance(self.status, Status): + raise TypeError(f"status must be a Status, not {self.status!r}") + if self.status is Status.HELD and self._token is not _JUDGED: + raise TypeError( + "HELD comes only from Result.held or Result.from_code; " + "see docs/FAIL_CLOSED.md" + ) + + @classmethod + def held(cls, subject: Subject, obs: Observation, reason: str = "") -> "Result": + """HELD, from a complete observed value only.""" + + if not isinstance(obs, Observed) or obs.complete is not True: + raise TypeError("HELD needs a complete Observed value") + return cls(subject, Status.HELD, reason or "held", _JUDGED) + + @classmethod + def refuted(cls, subject: Subject, obs: Observation, reason: str) -> "Result": + """REFUTED, from an observed value (a partial read can refute).""" + + if not isinstance(obs, Observed): + raise TypeError("REFUTED needs an Observed value") + return cls(subject, Status.REFUTED, reason) + + @classmethod + def not_checked(cls, subject: Subject, reason: str) -> "Result": + return cls(subject, Status.NOT_CHECKED, reason) + + @classmethod + def from_observation( + cls, + subject: Subject, + obs: Observation, + judge: Callable[[object], tuple[Status, str]], + ) -> "Result": + """Judge an observation. ``judge`` sees only a complete value; a + missing, errored or partial read is ``NOT_CHECKED`` without a call.""" + + if isinstance(obs, Missing): + return cls.not_checked(subject, f"missing: {obs.reason}") + if isinstance(obs, Errored): + return cls.not_checked(subject, f"errored: {obs.exc_type}") + if not obs.complete: + return cls.not_checked(subject, "partial read") + status, reason = judge(obs.value) + if status is Status.HELD: + return cls.held(subject, obs, reason) + if status is Status.REFUTED: + return cls.refuted(subject, obs, reason) + return cls.not_checked(subject, reason) + + @classmethod + def from_code( + cls, + subject: Subject, + code: object, + *, + held: frozenset[str], + refuted: frozenset[str], + reason: str = "", + ) -> "Result": + """A result from an upstream judge's code, by allow-list (:func:`from_code`).""" + + status = from_code(code, held=held, refuted=refuted) + text = reason or f"code {code!r}" + if status is Status.HELD: + return cls(subject, status, text, _JUDGED) + return cls(subject, status, text) + + +def from_code(code: object, *, held: frozenset[str], refuted: frozenset[str]) -> Status: + """Map an outside code to a status. Any code not listed is ``NOT_CHECKED``. + + An enum member maps by its value. The two lists may not overlap. + """ + + if held & refuted: + raise ValueError(f"a code is both held and refuted: {sorted(held & refuted)}") + if isinstance(code, Enum): + code = code.value + if not isinstance(code, str): + return Status.NOT_CHECKED + if code in held: + return Status.HELD + if code in refuted: + return Status.REFUTED + return Status.NOT_CHECKED + + +# -- obligations and settlement --------------------------------------------------- + + +@dataclass(frozen=True) +class Obligations: + """What must be checked, fixed before any check runs.""" + + items: tuple[Subject, ...] + source: str + + @classmethod + def fix(cls, items: Iterable[Subject], *, source: str) -> "Obligations": + """Dedupe by :meth:`Subject.key_tuple`, keeping the first. Empty is + allowed; it never settles as a pass.""" + + seen: set[tuple[object, ...]] = set() + kept = [] + for item in items: + if item.key_tuple() not in seen: + seen.add(item.key_tuple()) + kept.append(item) + return cls(tuple(kept), source) + + +@dataclass(frozen=True) +class Settlement: + """Every obligation lands in exactly one of held, refuted, not_checked, + missing, mismatched or conflicting. ``unexpected`` holds results that + match no obligation.""" + + total: int + held: tuple[Subject, ...] + refuted: tuple[Subject, ...] + not_checked: tuple[Subject, ...] + missing: tuple[Subject, ...] + unexpected: tuple[Result, ...] + mismatched: tuple[Subject, ...] + conflicting: tuple[Subject, ...] + over_limit: bool + + @property + def passes(self) -> bool: + return ( + self.total > 0 + and len(self.held) == self.total + and not self.refuted + and not self.not_checked + and not self.missing + and not self.unexpected + and not self.mismatched + and not self.conflicting + and not self.over_limit + ) + + def _unsettled(self) -> bool: + return bool( + self.total == 0 + or self.not_checked + or self.missing + or self.unexpected + or self.mismatched + or self.conflicting + or self.over_limit + ) + + def label(self, *, precedence: tuple[Status, ...]) -> Status: + """``HELD`` only when :attr:`passes`. Otherwise the first status in + ``precedence`` that applies (each site states its own order), else + ``NOT_CHECKED``.""" + + if self.passes: + return Status.HELD + for status in precedence: + if status is Status.REFUTED and self.refuted: + return Status.REFUTED + if status is Status.NOT_CHECKED and self._unsettled(): + return Status.NOT_CHECKED + return Status.NOT_CHECKED + + def rate(self, of: Status) -> Optional[Fraction]: + """Share of the planned total, never of what happened to be scored. + ``NOT_CHECKED`` counts missing, mismatched and conflicting too.""" + + if self.total == 0: + return None + if of is Status.HELD: + n = len(self.held) + elif of is Status.REFUTED: + n = len(self.refuted) + else: + n = ( + len(self.not_checked) + + len(self.missing) + + len(self.mismatched) + + len(self.conflicting) + ) + return Fraction(n, self.total) + + +def settle( + obligations: Obligations, + results: Iterable[Result], + *, + limit: Optional[int] = None, +) -> Settlement: + """Match results to obligations by subject key. See :class:`Settlement`.""" + + by_key: dict[tuple[object, ...], list[Result]] = {} + for result in results: + by_key.setdefault(result.subject.key_tuple(), []).append(result) + wanted = {o.key_tuple() for o in obligations.items} + buckets: dict[str, list[Subject]] = { + k: [] for k in ("held", "refuted", "not_checked", "missing", "mismatched") + } + conflicting: list[Subject] = [] + for item in obligations.items: + got = by_key.get(item.key_tuple(), []) + if not got: + buckets["missing"].append(item) + elif any(binding_mismatches(item, r.subject) for r in got): + buckets["mismatched"].append(item) + elif len({r.status for r in got}) > 1: + conflicting.append(item) + else: + buckets[got[0].status.value].append(item) + unexpected = tuple(r for key, rs in by_key.items() if key not in wanted for r in rs) + total = len(obligations.items) + return Settlement( + total=total, + held=tuple(buckets["held"]), + refuted=tuple(buckets["refuted"]), + not_checked=tuple(buckets["not_checked"]), + missing=tuple(buckets["missing"]), + unexpected=unexpected, + mismatched=tuple(buckets["mismatched"]), + conflicting=tuple(conflicting), + over_limit=limit is not None and total > limit, + ) + + +# -- trust sources ---------------------------------------------------------------- + + +class TrustSource(str, Enum): + """Where the key that verified a signature came from.""" + + #: This computer's own signing key, read from its key store. + LOCAL_KEY = "local_key" + #: A key pinned in a signer registry the verifier trusts. + REGISTERED = "registered" + #: Only a key the envelope carries itself: proves integrity, not who. + EMBEDDED = "embedded" + #: Not verified, or the source is not known. + UNVERIFIED = "unverified" + + +_TRUST_LABELS = { + TrustSource.LOCAL_KEY: "signed on this computer", + TrustSource.REGISTERED: "signed by a registered signer", + TrustSource.EMBEDDED: "signature valid, signer not known", +} + + +def trust_label(source: object, *, verified: bool) -> str: + """The label for a signature. Only a verified, known source names a signer; + anything else (an unknown source, a string, a failed check) is + "not verified".""" + + if verified is not True or not isinstance(source, TrustSource): + return "not verified" + return _TRUST_LABELS.get(source, "not verified") diff --git a/packages/flow/openadapt_flow/verdict_sites.py b/packages/flow/openadapt_flow/verdict_sites.py new file mode 100644 index 0000000000..e78eaa55fd --- /dev/null +++ b/packages/flow/openadapt_flow/verdict_sites.py @@ -0,0 +1,36 @@ +"""Mark a function that turns evidence into a verdict, so the fail-open +harness tests it. + +``@verdict_site("verify_run.aggregate", classes="C2")`` does nothing at run +time except record the site in :data:`SITES`. ``tests/failopen`` keeps one +spec per site and runs the generic mutations against it; a meta-test fails +when a decorated site has no spec. ``scripts/check_verdict_folds.py`` exempts +a decorated function from its count, so decorating and registering is how +new verdict code is added. See ``docs/FAIL_CLOSED.md``. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TypeVar + +__all__ = ["SITES", "verdict_site"] + +F = TypeVar("F", bound=Callable[..., object]) + +#: ``{site id: the fail-open classes it is tested for}``, filled at import. +SITES: dict[str, str] = {} + + +def verdict_site(id: str, *, classes: str) -> Callable[[F], F]: + """Register ``id`` and return the function unchanged.""" + + def mark(fn: F) -> F: + known = SITES.get(id) + if known is not None and known != classes: + raise ValueError(f"verdict site {id!r} registered twice") + SITES[id] = classes + setattr(fn, "__verdict_site__", id) + return fn + + return mark diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index cabfb87834..110da6bb08 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -91,6 +91,8 @@ Verdict, ) from openadapt_flow.runtime.effects.frame import FrameSpec, FrameVerdict, judge_frame +from openadapt_flow.verdict import Obligations, Result, Status, Subject, settle +from openadapt_flow.verdict_sites import verdict_site from openadapt_flow.verification import ( EffectContractMutationError, VerificationTier, @@ -2955,15 +2957,40 @@ def _label(verdict: Verdict) -> EffectVerdictLabel: return labels[verdict] +_AGGREGATE_LABELS: dict[Status, EffectVerdictLabel] = { + Status.HELD: "CONFIRMED", + Status.REFUTED: "REFUTED", + Status.NOT_CHECKED: "INDETERMINATE", +} + + +@verdict_site("verify_run.aggregate", classes="C2 C3") def _aggregate(verdicts: Sequence[EffectVerdict]) -> EffectVerdictLabel: - if any(v.verdict is Verdict.INDETERMINATE for v in verdicts): - return "INDETERMINATE" - if any(v.verdict is Verdict.REFUTED for v in verdicts): - return "REFUTED" - return "CONFIRMED" + """CONFIRMED only when every effect is; any INDETERMINATE outranks a + REFUTED; no effects at all is INDETERMINATE (docs/FAIL_CLOSED.md).""" + + subjects = [Subject(key=str(i)) for i in range(len(verdicts))] + settled = settle( + Obligations.fix(subjects, source="effects"), + [ + Result.from_code( + s, + v.verdict, + held=frozenset({Verdict.CONFIRMED.value}), + refuted=frozenset({Verdict.REFUTED.value}), + ) + for s, v in zip(subjects, verdicts) + ], + ) + return _AGGREGATE_LABELS[ + settled.label(precedence=(Status.NOT_CHECKED, Status.REFUTED)) + ] +@verdict_site("verify_run.observed", classes="C2") def _observed(verdicts: Sequence[EffectVerdict]) -> str: + if not verdicts: + return "unknown" # nothing was read, so nothing is present seen = {v.observed_effect for v in verdicts} if "unknown" in seen: return "unknown" @@ -2973,19 +3000,23 @@ def _observed(verdicts: Sequence[EffectVerdict]) -> str: return "absent" if "absent" in seen else "present" +@verdict_site("verify_run.readback_class", classes="C1 C2") def readback_class( verdicts: Sequence[EffectVerdict], tiers: Sequence[Optional[VerificationTier]] ) -> ReadbackClass: """RFC-0002 tier rule, weakest effect wins. ``unchecked`` when any effect was not read (no tier, store unreachable, - stale). ``independent_readback`` only when every effect was read from the + stale), when there are no effects, or when the tiers don't pair one to + one with the effects. ``independent_readback`` only when every effect was read from the system of record without the UI (Flow tier 1). Anything else, including a separate signed-in UI session (tier 2), is ``screen_readback``. """ if ( - any(t is None for t in tiers) + not verdicts + or len(tiers) != len(verdicts) + or any(t is None for t in tiers) or any(v.unavailable for v in verdicts) or any(v.stale for v in verdicts) ): diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index e61429e282..f1a6b6ffe6 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1422,9 +1422,13 @@ "schemas/sanitized-artifact-manifest-v1.json", "scripts/generality.toml", "scripts/generality_baseline.json", + "scripts/verdict_folds.toml", + "scripts/verdict_folds_baseline.json", "source-policy.public.json", "tests/extension_support/chrome_extension_harness.js", "tests/extension_support/network_harness.js", + "tests/failopen/corpus/urls.json", + "tests/failopen/corpus/values.json", "tests/golden/tutorial_run.json", "tests/golden_runs/baselines/bundles/mockmed-triage/manifest.json", "tests/golden_runs/baselines/bundles/mockmed-triage/param_proposals.json", diff --git a/packages/flow/scripts/check_verdict_folds.py b/packages/flow/scripts/check_verdict_folds.py new file mode 100644 index 0000000000..8b0a692777 --- /dev/null +++ b/packages/flow/scripts/check_verdict_folds.py @@ -0,0 +1,337 @@ +"""Fail when a file gains a hand-written verdict fold outside the kernel. + +The same fail-open bugs kept coming back because every check folded its own +evidence: ``all(...)`` over a list that could be empty, a slice before the +tally, ``except Exception: return``, a final ``else`` that says success, a +compare against ``"VERIFIED"``. ``openadapt_flow/verdict.py`` folds once, and +a function marked ``@verdict_site`` has a spec the fail-open harness runs +(``tests/failopen``). This check counts the hand-written folds everywhere +else, per file and per kind, and fails only when a count rises above +``verdict_folds_baseline.json``. A count that falls never fails; lower the +baseline with ``--update-baseline`` when you like (it never raises one). + +What it counts (``verdict_folds.toml`` holds the literal lists): + +- ``says_success``: a success literal (``VERIFIED``, ``CONFIRMED``, ``held``, + ...) produced in code, not compared. Only the kernel and a registered site + may say a check held. +- ``cmp_literal``: a compare against an outcome literal. +- ``bool_fold``: ``all(...)``/``any(...)`` over verdicts, results, checks, + effects, lines or tiers. +- ``swallow``: ``except Exception`` (or bare) whose body returns, continues + or passes without a raise or a not-checked value. +- ``slice_count``: a ``[:N]`` slice in a statement that also counts. +- ``else_success``: a final ``else:`` that assigns a success literal. + +The way to add verdict code is to build it on ``verdict.settle`` inside a +function marked ``@verdict_site`` with a spec (docs/FAIL_CLOSED.md). + +Usage:: + + python scripts/check_verdict_folds.py + python scripts/check_verdict_folds.py --update-baseline +""" + +from __future__ import annotations + +import argparse +import ast +import json +import re +import sys +from collections import Counter +from pathlib import Path +from typing import Any, Iterator, Optional + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + +HERE = Path(__file__).resolve().parent +FLOW = HERE.parent +ROOT = FLOW.parent.parent +CONFIG = HERE / "verdict_folds.toml" +BASELINE = HERE / "verdict_folds_baseline.json" +OUTCOMES = ROOT / "packages/types/openadapt_types/vocabulary/outcomes.json" + +KINDS = ( + "says_success", + "cmp_literal", + "bool_fold", + "swallow", + "slice_count", + "else_success", +) + + +def load_config(path: Path = CONFIG) -> dict[str, Any]: + config = tomllib.loads(path.read_text(encoding="utf-8")) + literals = set(config["literals"]["outcome_extra"]) + if OUTCOMES.is_file(): + vocab = json.loads(OUTCOMES.read_text(encoding="utf-8")) + for source in vocab["sources"].values(): + literals.update(source.get("values", {})) + config["_outcomes"] = frozenset(literals) + config["_success"] = frozenset(config["literals"]["success"]) + config["_fold_names"] = re.compile(config["bool_fold"]["names"], re.IGNORECASE) + return config + + +def _site_decorator(node: ast.AST) -> Optional[str]: + """The id of ``@verdict_site("id", ...)`` on a function, else None.""" + + for dec in getattr(node, "decorator_list", []): + if ( + isinstance(dec, ast.Call) + and getattr(dec.func, "id", getattr(dec.func, "attr", None)) + == "verdict_site" + and dec.args + and isinstance(dec.args[0], ast.Constant) + and isinstance(dec.args[0].value, str) + ): + return dec.args[0].value + return None + + +def decorated_sites(path: Path) -> dict[str, str]: + """``{site id: qualified function name}`` for every ``@verdict_site``.""" + + tree = ast.parse(path.read_text(encoding="utf-8")) + out: dict[str, str] = {} + + def visit(node: ast.AST, prefix: str) -> None: + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + name = f"{prefix}{child.name}" + site = _site_decorator(child) + if site is not None: + out[site] = name + visit(child, name + ".") + + visit(tree, "") + return out + + +def _exempt_nodes(tree: ast.AST) -> set[int]: + """Ids of every node inside a ``@verdict_site`` function.""" + + skip: set[int] = set() + for node in ast.walk(tree): + if ( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and _site_decorator(node) is not None + ): + skip.update(id(n) for n in ast.walk(node)) + return skip + + +def _strings(node: ast.AST) -> Iterator[str]: + if isinstance(node, ast.Constant) and isinstance(node.value, str): + yield node.value + elif isinstance(node, (ast.Tuple, ast.List, ast.Set)): + for elt in node.elts: + yield from _strings(elt) + + +def _names(node: ast.AST) -> Iterator[str]: + for n in ast.walk(node): + if isinstance(n, ast.Name): + yield n.id + elif isinstance(n, ast.Attribute): + yield n.attr + + +_NOT_CHECKED_NAMES = frozenset( + {"Missing", "Errored", "not_checked", "NOT_CHECKED", "FailClosed"} +) +_COUNTING = frozenset({"sum", "len", "Counter", "tally", "count"}) + + +def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: + """Per-kind counts of hand-written folds in one Python file.""" + + try: + tree = ast.parse(path.read_text(encoding="utf-8")) + except (SyntaxError, UnicodeDecodeError): + return Counter() + skip = _exempt_nodes(tree) + outcomes, success = config["_outcomes"], config["_success"] + fold_names = config["_fold_names"] + counts: Counter[str] = Counter() + + compared: set[int] = set() + typed: set[int] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Compare): + compared.update(id(n) for n in ast.walk(node)) + elif ( + isinstance(node, ast.Subscript) + and getattr(node.value, "id", "") == "Literal" + ): + typed.update(id(n) for n in ast.walk(node)) + + statements = [n for n in ast.walk(tree) if isinstance(n, ast.stmt)] + for node in ast.walk(tree): + if id(node) in skip: + continue + if isinstance(node, ast.Compare): + values = [node.left, *node.comparators] + if any(s in outcomes or s in success for v in values for s in _strings(v)): + counts["cmp_literal"] += 1 + elif ( + isinstance(node, ast.Constant) + and isinstance(node.value, str) + and node.value in success + and id(node) not in compared + and id(node) not in typed + ): + counts["says_success"] += 1 + elif ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id in ("all", "any") + and node.args + and any(fold_names.search(n) for n in _names(node.args[0])) + ): + counts["bool_fold"] += 1 + elif isinstance(node, ast.ExceptHandler): + broad = node.type is None or ( + isinstance(node.type, ast.Name) + and node.type.id in ("Exception", "BaseException") + ) + body = ast.Module(body=node.body, type_ignores=[]) + leaves = any( + isinstance(n, (ast.Return, ast.Continue, ast.Pass)) + for n in ast.walk(body) + ) + closed = any(isinstance(n, ast.Raise) for n in ast.walk(body)) or any( + name in _NOT_CHECKED_NAMES for name in _names(body) + ) + if broad and leaves and not closed: + counts["swallow"] += 1 + elif isinstance(node, ast.If) and node.orelse: + tail = node.orelse + if not (len(tail) == 1 and isinstance(tail[0], ast.If)): + for stmt in tail: + if isinstance(stmt, (ast.Assign, ast.AnnAssign)) and any( + s in success for s in _strings(stmt.value or ast.Constant(None)) + ): + counts["else_success"] += 1 + for stmt in statements: + if id(stmt) in skip or isinstance( + stmt, + ( + ast.FunctionDef, + ast.AsyncFunctionDef, + ast.ClassDef, + ast.If, + ast.For, + ast.While, + ast.With, + ast.Try, + ), + ): + continue + sliced = any( + isinstance(n, ast.Subscript) + and isinstance(n.slice, ast.Slice) + and n.slice.lower is None + and n.slice.upper is not None + for n in ast.walk(stmt) + ) + if sliced and any( + isinstance(n, ast.Call) + and getattr(n.func, "id", getattr(n.func, "attr", "")) in _COUNTING + for n in ast.walk(stmt) + ): + counts["slice_count"] += 1 + return counts + + +def scope_files(config: dict[str, Any], root: Path = ROOT) -> Iterator[Path]: + exempt = set(config["scope"]["exempt"]) + for pattern in config["scope"]["include"]: + for path in sorted(root.glob(pattern)): + rel = path.relative_to(root).as_posix() + if path.is_file() and "__pycache__" not in path.parts and rel not in exempt: + yield path + + +def scan( + config: Optional[dict[str, Any]] = None, root: Path = ROOT +) -> dict[str, dict[str, int]]: + config = config if config is not None else load_config() + out: dict[str, dict[str, int]] = {} + for path in scope_files(config, root): + counts = count_file(path, config) + if counts: + out[path.relative_to(root).as_posix()] = { + k: counts[k] for k in KINDS if counts[k] + } + return out + + +def compare( + found: dict[str, dict[str, int]], baseline: dict[str, dict[str, int]] +) -> list[str]: + """Every (file, kind) whose count rose above the baseline.""" + + grown = [] + for rel, kinds in sorted(found.items()): + for kind, n in sorted(kinds.items()): + allowed = baseline.get(rel, {}).get(kind, 0) + if n > allowed: + grown.append(f"{rel}: {kind} {n} (baseline {allowed})") + return grown + + +def lowered( + found: dict[str, dict[str, int]], baseline: dict[str, dict[str, int]] +) -> dict[str, dict[str, int]]: + """The baseline lowered to what is found; never raised.""" + + out: dict[str, dict[str, int]] = {} + for rel, kinds in baseline.items(): + for kind, allowed in kinds.items(): + n = min(allowed, found.get(rel, {}).get(kind, 0)) + if n: + out.setdefault(rel, {})[kind] = n + return dict(sorted(out.items())) + + +def main(argv: Optional[list[str]] = None) -> int: + parser = argparse.ArgumentParser( + description=__doc__.split("\n", 1)[0], allow_abbrev=False + ) + parser.add_argument( + "--update-baseline", + action="store_true", + help="Lower the baseline to the current counts (it never rises)", + ) + args = parser.parse_args(argv) + found = scan() + baseline = json.loads(BASELINE.read_text(encoding="utf-8")) + grown = compare(found, baseline) + if args.update_baseline: + BASELINE.write_text( + json.dumps(lowered(found, baseline), indent=2) + "\n", encoding="utf-8" + ) + print(f"Baseline lowered: {BASELINE.relative_to(FLOW)}") + if grown: + print( + "New hand-written verdict folds. Build the verdict on " + "openadapt_flow.verdict.settle inside a function marked " + "@verdict_site, and add its spec under tests/failopen/sites " + "(docs/FAIL_CLOSED.md):", + file=sys.stderr, + ) + print("\n".join(f" {line}" for line in grown), file=sys.stderr) + return 1 + total = sum(n for kinds in baseline.values() for n in kinds.values()) + print(f"Verdict folds OK ({total} baseline folds left)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/scripts/verdict_folds.toml b/packages/flow/scripts/verdict_folds.toml new file mode 100644 index 0000000000..040d9ba7fa --- /dev/null +++ b/packages/flow/scripts/verdict_folds.toml @@ -0,0 +1,33 @@ +# Config for scripts/check_verdict_folds.py. It names no application: the +# outcome literals come from openadapt_types/vocabulary/outcomes.json, plus +# the few below. + +[scope] +# Relative to the repository root. +include = [ + "packages/flow/openadapt_flow/**/*.py", + "openadapt/**/*.py", + "scripts/ci/**/*.py", +] +# The kernel and its registry are where folds belong. +exempt = [ + "packages/flow/openadapt_flow/verdict.py", + "packages/flow/openadapt_flow/verdict_sites.py", +] + +[literals] +# A check that says one of these, outside the kernel or a registered site, +# is saying it held. +success = [ + "VERIFIED", + "CONFIRMED", + "held", + "verified_done", + "independent_readback", +] +# Compared against, beside every outcome in the vocabulary. +outcome_extra = ["held", "confirmed", "pass", "verified_done", "refuted", "not_checked"] + +[bool_fold] +# all(...)/any(...) over one of these names folds verdicts by hand. +names = '(verdict|result|check|effect|line|tier)' diff --git a/packages/flow/scripts/verdict_folds_baseline.json b/packages/flow/scripts/verdict_folds_baseline.json new file mode 100644 index 0000000000..44e8358f4d --- /dev/null +++ b/packages/flow/scripts/verdict_folds_baseline.json @@ -0,0 +1,1236 @@ +{ + "openadapt/cli.py": { + "cmp_literal": 1, + "swallow": 10, + "slice_count": 1 + }, + "openadapt/quickstart/engine.py": { + "cmp_literal": 5, + "swallow": 2 + }, + "openadapt/quickstart/notices.py": { + "swallow": 1 + }, + "openadapt/quickstart/openemr.py": { + "cmp_literal": 2, + "swallow": 2 + }, + "openadapt/quickstart/scene.py": { + "cmp_literal": 1, + "slice_count": 1 + }, + "openadapt/quickstart/view.py": { + "cmp_literal": 2, + "swallow": 1 + }, + "openadapt/quickstart/workers.py": { + "cmp_literal": 1, + "swallow": 2 + }, + "openadapt/seal_claim.py": { + "swallow": 5 + }, + "openadapt/seal_publish.py": { + "swallow": 1 + }, + "openadapt/seal_view/__init__.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/__main__.py": { + "cmp_literal": 14, + "swallow": 7 + }, + "packages/flow/openadapt_flow/_browser_readiness.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/_prewarm.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/action_evidence.py": { + "cmp_literal": 2, + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/adapters/capture.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/admit_pipeline.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/admitted_composition.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/after_stop.py": { + "cmp_literal": 6, + "bool_fold": 2, + "swallow": 2 + }, + "packages/flow/openadapt_flow/agent/authoring.py": { + "cmp_literal": 3, + "swallow": 2 + }, + "packages/flow/openadapt_flow/agent/bridge.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/agent/browser_teach.py": { + "cmp_literal": 1, + "bool_fold": 1, + "swallow": 7 + }, + "packages/flow/openadapt_flow/agent/bundles.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/agent/cli.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/agent/contract.py": { + "says_success": 3, + "cmp_literal": 10 + }, + "packages/flow/openadapt_flow/agent/example_app.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/agent/ledger.py": { + "cmp_literal": 11, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/agent/mailbox.py": { + "cmp_literal": 3, + "swallow": 1 + }, + "packages/flow/openadapt_flow/agent/mcp.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/agent/repair.py": { + "swallow": 4 + }, + "packages/flow/openadapt_flow/agent/runner.py": { + "says_success": 1, + "cmp_literal": 12, + "swallow": 3 + }, + "packages/flow/openadapt_flow/agent/runs.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/agent/sandbox.py": { + "says_success": 2, + "cmp_literal": 2, + "swallow": 5 + }, + "packages/flow/openadapt_flow/agent/seal.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/agent/seal_cli.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/agent/service.py": { + "cmp_literal": 1, + "swallow": 4 + }, + "packages/flow/openadapt_flow/agent/teach.py": { + "cmp_literal": 8, + "swallow": 1 + }, + "packages/flow/openadapt_flow/agent/tutorial.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/agent_guard/capture.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/agent_guard/cdp.py": { + "swallow": 9 + }, + "packages/flow/openadapt_flow/agent_guard/commit_guard.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/agent_guard/session.py": { + "cmp_literal": 1, + "swallow": 3 + }, + "packages/flow/openadapt_flow/approval_mode/approver.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/approval_mode/coverage.py": { + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/approval_mode/dry_run.py": { + "cmp_literal": 1, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/approval_mode/durable_carry.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/approval_mode/form_state.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/approval_mode/gate.py": { + "cmp_literal": 4, + "bool_fold": 3, + "swallow": 5 + }, + "packages/flow/openadapt_flow/approval_mode/item_approval.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/approval_mode/model.py": { + "cmp_literal": 1, + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/approval_mode/named_person_binding.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/approval_mode/post.py": { + "cmp_literal": 9, + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/approval_mode/requirements.py": { + "cmp_literal": 2, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/approval_mode/switch.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/assurance.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/attest_bridge.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/authoring.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/authorization_summary.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/backends/_owned.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/backends/_page_quiescence.py": { + "swallow": 4 + }, + "packages/flow/openadapt_flow/backends/_server_responses.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/backends/choice.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/backends/linux_backend.py": { + "swallow": 26 + }, + "packages/flow/openadapt_flow/backends/macos_backend.py": { + "swallow": 16 + }, + "packages/flow/openadapt_flow/backends/parallels_vm.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/backends/playwright_backend.py": { + "cmp_literal": 1, + "swallow": 70 + }, + "packages/flow/openadapt_flow/backends/rdp_backend.py": { + "swallow": 8 + }, + "packages/flow/openadapt_flow/backends/redirect_guard.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/backends/remote_display.py": { + "bool_fold": 1, + "swallow": 29 + }, + "packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/backends/win_agent/native_value.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/backends/win_agent/server.py": { + "swallow": 28 + }, + "packages/flow/openadapt_flow/backends/windows_backend.py": { + "swallow": 9 + }, + "packages/flow/openadapt_flow/backends/windows_keyboard_lease.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/backends/worker_containment.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/backends/xfreerdp.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/browser_accessibility.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/browser_login.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/bundle_validation.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/cli_compose.py": { + "says_success": 1, + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/cli_deferred.py": { + "says_success": 1, + "cmp_literal": 4 + }, + "packages/flow/openadapt_flow/cli_hints.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/cli_local_seal.py": { + "bool_fold": 1, + "swallow": 3 + }, + "packages/flow/openadapt_flow/cli_process.py": { + "says_success": 1, + "cmp_literal": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/cli_receipt.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/cli_reconcile.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/cli_self_repair.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/cli_shadow.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/cli_tasks.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/cli_undo.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/cli_variants.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/cli_worklist_pool.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/cloud_seal.py": { + "cmp_literal": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/compile_agent/code_action.py": { + "swallow": 9, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compile_agent/harness.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/compile_agent/observe.py": { + "swallow": 6 + }, + "packages/flow/openadapt_flow/compile_agent/pipeline.py": { + "cmp_literal": 6, + "swallow": 2 + }, + "packages/flow/openadapt_flow/compile_agent/repair_bridge.py": { + "cmp_literal": 4, + "swallow": 1 + }, + "packages/flow/openadapt_flow/compile_agent/repair_selection.py": { + "cmp_literal": 7 + }, + "packages/flow/openadapt_flow/compile_agent/sandbox.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compiler/api_proposal.py": { + "cmp_literal": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compiler/binding_admission.py": { + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/compiler/compile.py": { + "bool_fold": 1, + "swallow": 2, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compiler/compose_authoring.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/compiler/disambiguation.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compiler/empty_result_guard.py": { + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/compiler/induction.py": { + "bool_fold": 3, + "swallow": 1 + }, + "packages/flow/openadapt_flow/compiler/lookup_detect.py": { + "bool_fold": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/compiler/narration_rules.py": { + "bool_fold": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compiler/probing.py": { + "cmp_literal": 4, + "swallow": 2 + }, + "packages/flow/openadapt_flow/compiler/qualification_pins.py": { + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/composition.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/connector/daemon.py": { + "cmp_literal": 3, + "swallow": 1 + }, + "packages/flow/openadapt_flow/connector/executor.py": { + "cmp_literal": 12, + "swallow": 2 + }, + "packages/flow/openadapt_flow/connector/windows_service.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/console/app.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/console/attention.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/console/data.py": { + "cmp_literal": 5, + "swallow": 4 + }, + "packages/flow/openadapt_flow/console/decision_relay.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/console/decision_supervisor.py": { + "cmp_literal": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/console/halt_detail.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/console/human_decisions.py": { + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/countersign/commitments.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/countersign/document.py": { + "cmp_literal": 15 + }, + "packages/flow/openadapt_flow/countersign/dossier.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/countersign/render.py": { + "says_success": 2, + "cmp_literal": 4 + }, + "packages/flow/openadapt_flow/countersign/tsa.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/decision/calibration.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/decision/features.py": { + "cmp_literal": 4, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/decision/labels.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/decision/review.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/decision/synthetic.py": { + "says_success": 1, + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/demo_proof.py": { + "cmp_literal": 4, + "swallow": 3 + }, + "packages/flow/openadapt_flow/deployment.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/desktop_record.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/eligibility/artifact.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/eligibility/client.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/emit/mcp_governed.py": { + "cmp_literal": 2, + "swallow": 2 + }, + "packages/flow/openadapt_flow/emit/mcp_tool.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/execute/dispatch.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/execute/service.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/execution_profiles.py": { + "says_success": 1, + "cmp_literal": 17, + "bool_fold": 17 + }, + "packages/flow/openadapt_flow/extension_network.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/failure_signals.py": { + "says_success": 1, + "cmp_literal": 6 + }, + "packages/flow/openadapt_flow/fault_gate.py": { + "cmp_literal": 2, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/fleet/canary.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/fleet/hub.py": { + "says_success": 4 + }, + "packages/flow/openadapt_flow/fleet/policy.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/form_tx/playwright_surface.py": { + "swallow": 13 + }, + "packages/flow/openadapt_flow/form_tx/session_lease.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/form_tx/types.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/generate/demo_analysis.py": { + "slice_count": 2 + }, + "packages/flow/openadapt_flow/generate/zero_touch.py": { + "cmp_literal": 4, + "swallow": 2, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/guard.py": { + "says_success": 1, + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/halt_cleanup.py": { + "bool_fold": 1, + "swallow": 5 + }, + "packages/flow/openadapt_flow/hard_invariants.py": { + "says_success": 2, + "cmp_literal": 2, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/hosted.py": { + "cmp_literal": 5, + "swallow": 8 + }, + "packages/flow/openadapt_flow/intake/param_gate.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/integrations/agents/__init__.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/integrations/agents/skills.py": { + "cmp_literal": 6 + }, + "packages/flow/openadapt_flow/interactive_recorder.py": { + "swallow": 17 + }, + "packages/flow/openadapt_flow/interchange/conformance.py": { + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/interop/types.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/ir.py": { + "cmp_literal": 10, + "bool_fold": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/jit/adapters.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/jit/authority.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/jit/compile_agent.py": { + "cmp_literal": 3, + "swallow": 2 + }, + "packages/flow/openadapt_flow/jit/dispatch_authority.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/jit/lifecycle.py": { + "cmp_literal": 2, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/learn.py": { + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/learning/branch_teach.py": { + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/learning/gate.py": { + "cmp_literal": 6, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/learning/interpreter.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/learning/teach.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/learning/trace.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/mockloan/fault_server.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/mockmed/fault_server.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/multi_surface_record.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/network_capture.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/offline_seal.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/onprem_service.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/operator_profile.py": { + "cmp_literal": 7 + }, + "packages/flow/openadapt_flow/plain_outcome.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/policy.py": { + "cmp_literal": 1, + "bool_fold": 6, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/privacy.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/provenance.py": { + "says_success": 1, + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/public_seal.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/qualification/__init__.py": { + "cmp_literal": 7, + "bool_fold": 9, + "swallow": 2 + }, + "packages/flow/openadapt_flow/qualification_drills.py": { + "swallow": 6 + }, + "packages/flow/openadapt_flow/qualification_faults.py": { + "cmp_literal": 4, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/qualification_identity_evidence.py": { + "cmp_literal": 3, + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/qualification_oracle_gate.py": { + "cmp_literal": 1, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/qualification_proposal.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/qualify/campaign.py": { + "says_success": 3, + "cmp_literal": 4, + "bool_fold": 4, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/qualify/faults.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/qualify/result.py": { + "says_success": 3, + "cmp_literal": 15 + }, + "packages/flow/openadapt_flow/readback_ladder.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/receipt.py": { + "says_success": 1, + "cmp_literal": 9, + "bool_fold": 8 + }, + "packages/flow/openadapt_flow/reconcile/__init__.py": { + "says_success": 5, + "cmp_literal": 1, + "bool_fold": 1, + "swallow": 1, + "else_success": 2 + }, + "packages/flow/openadapt_flow/record_check_binding.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/record_check_synthesis.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/record_sor.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/recorder.py": { + "swallow": 17 + }, + "packages/flow/openadapt_flow/registry.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/auto_repair.py": { + "says_success": 1, + "cmp_literal": 5, + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/campaign.py": { + "cmp_literal": 2, + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/cli.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/repair/cloud_review.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/hold.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/lifecycle.py": { + "cmp_literal": 5 + }, + "packages/flow/openadapt_flow/repair/preflight_queue.py": { + "cmp_literal": 3, + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/readmission.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/relabel.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/self_repair.py": { + "cmp_literal": 8, + "bool_fold": 7, + "swallow": 15, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/repair/standard_change.py": { + "cmp_literal": 4, + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/report.py": { + "cmp_literal": 5, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/rest_setup.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/retention.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/retention_apply.py": { + "cmp_literal": 1, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/reward/models.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/reward/oracles.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/reward/worker.py": { + "cmp_literal": 1, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/rl_env/desktop.py": { + "swallow": 4 + }, + "packages/flow/openadapt_flow/rl_env/environment.py": { + "swallow": 10 + }, + "packages/flow/openadapt_flow/rl_env/parallel.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/rl_env/record_grader.py": { + "cmp_literal": 2, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/rl_env/reward.py": { + "says_success": 2, + "cmp_literal": 5, + "swallow": 2 + }, + "packages/flow/openadapt_flow/rl_env/trainers.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/rl_env/validate.py": { + "says_success": 1, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/rl_env/validate_desktop.py": { + "says_success": 1, + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/rl_env/windows_guest.py": { + "swallow": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/rollback.py": { + "cmp_literal": 3, + "bool_fold": 2, + "swallow": 5 + }, + "packages/flow/openadapt_flow/rollback_qualify.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/run_authorization.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/run_gate.py": { + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/runner/evidence.py": { + "cmp_literal": 7, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runner/hosted_adapter.py": { + "says_success": 1, + "cmp_literal": 7, + "bool_fold": 1, + "swallow": 3 + }, + "packages/flow/openadapt_flow/runner/verify.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/actuators/api.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/actuators/form_eval.py": { + "swallow": 4 + }, + "packages/flow/openadapt_flow/runtime/actuators/session_headers.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/actuators/web_form.py": { + "swallow": 4 + }, + "packages/flow/openadapt_flow/runtime/admitted_composition.py": { + "says_success": 3, + "cmp_literal": 10, + "bool_fold": 2, + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime/authorization.py": { + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/checks/app_sources.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/checks/duplicate_record.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/composition.py": { + "says_success": 2, + "cmp_literal": 5, + "bool_fold": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/control_overlay.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/runtime/durable/attended.py": { + "cmp_literal": 11, + "bool_fold": 1, + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime/durable/attended_state.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/durable/authority.py": { + "cmp_literal": 6, + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/durable/checkpoint.py": { + "bool_fold": 1, + "slice_count": 2 + }, + "packages/flow/openadapt_flow/runtime/durable/continuation.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/runtime/durable/controller.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/runtime/durable/program_checkpoint.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/durable/resume.py": { + "cmp_literal": 1, + "bool_fold": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/effect_watch.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/_common.py": { + "bool_fold": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/adapter.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/compensation.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/deferred_report.py": { + "says_success": 1, + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/runtime/effects/desktop_readback.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py": { + "swallow": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/effect.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/effect_model.py": { + "bool_fold": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/email_delivery.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/fhir.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime/effects/file_arrival.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/frame.py": { + "says_success": 1, + "cmp_literal": 2, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/fresh_session.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/graphql.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/history.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/late_write.py": { + "says_success": 1, + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/onscreen.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/runtime/effects/pipeline_safety.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/rest.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime/effects/smart_auth.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/sql.py": { + "swallow": 7 + }, + "packages/flow/openadapt_flow/runtime/effects/ui_readback.py": { + "cmp_literal": 3, + "swallow": 10 + }, + "packages/flow/openadapt_flow/runtime/grounder.py": { + "swallow": 4 + }, + "packages/flow/openadapt_flow/runtime/heal.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/healing/governance.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/runtime/healing/perturbation.py": { + "cmp_literal": 1, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/runtime/hover_evidence.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/identity.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/identity_census.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/identity_looks.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/runtime/list_guard.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/preparation.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/process_v1.py": { + "says_success": 1, + "cmp_literal": 10 + }, + "packages/flow/openadapt_flow/runtime/remote_vlm.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/replayer.py": { + "cmp_literal": 26, + "bool_fold": 12, + "swallow": 62, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/resolver.py": { + "cmp_literal": 1, + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime/surfaces.py": { + "swallow": 9 + }, + "packages/flow/openadapt_flow/runtime/variant_router.py": { + "cmp_literal": 1, + "bool_fold": 1, + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime/worklist_pool.py": { + "cmp_literal": 3, + "swallow": 3 + }, + "packages/flow/openadapt_flow/runtime_validation.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/sanitized_artifact.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/scaffold_verifier.py": { + "cmp_literal": 7, + "swallow": 1 + }, + "packages/flow/openadapt_flow/seal_batch.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/seal_timestamp.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/sections.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/shadow.py": { + "says_success": 1, + "bool_fold": 1, + "swallow": 4 + }, + "packages/flow/openadapt_flow/shadow_db.py": { + "cmp_literal": 1, + "bool_fold": 1, + "swallow": 2 + }, + "packages/flow/openadapt_flow/shadow_report.py": { + "says_success": 1, + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/skills.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/subroutines.py": { + "cmp_literal": 2, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/taskgen/validate.py": { + "says_success": 1, + "cmp_literal": 2, + "bool_fold": 3, + "swallow": 2 + }, + "packages/flow/openadapt_flow/taskgen/workbench.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/teach_scope.py": { + "cmp_literal": 1, + "bool_fold": 1, + "swallow": 8 + }, + "packages/flow/openadapt_flow/terminal_verification_v2.py": { + "says_success": 1, + "cmp_literal": 30, + "bool_fold": 7 + }, + "packages/flow/openadapt_flow/transaction.py": { + "says_success": 1, + "cmp_literal": 13, + "bool_fold": 7, + "swallow": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/tutorial.py": { + "cmp_literal": 5, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/tx/induce.py": { + "swallow": 1, + "slice_count": 3 + }, + "packages/flow/openadapt_flow/tx/lens.py": { + "says_success": 1, + "else_success": 1 + }, + "packages/flow/openadapt_flow/tx/wire_tap.py": { + "bool_fold": 2, + "swallow": 3 + }, + "packages/flow/openadapt_flow/undo_proposal.py": { + "cmp_literal": 5, + "bool_fold": 1, + "swallow": 4, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/validation/behavioral_generalization.py": { + "says_success": 1, + "cmp_literal": 3, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/validation/dense_surface.py": { + "cmp_literal": 7, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/validation/hardening/fixtures.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/validation/identity_ladder.py": { + "cmp_literal": 2, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/validation/identity_looks_dense.py": { + "cmp_literal": 7, + "swallow": 1 + }, + "packages/flow/openadapt_flow/validation/identity_rates.py": { + "cmp_literal": 4 + }, + "packages/flow/openadapt_flow/validation/known_ids_dense.py": { + "cmp_literal": 8 + }, + "packages/flow/openadapt_flow/validation/pixel_identity_aligned.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/validation/vlm_identity_probe.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/verifier.py": { + "says_success": 4, + "cmp_literal": 39, + "swallow": 9 + }, + "packages/flow/openadapt_flow/verifier_audit/targets/appworld_worker.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/verify_run.py": { + "says_success": 4, + "cmp_literal": 36, + "bool_fold": 2, + "swallow": 5 + }, + "packages/flow/openadapt_flow/vision/imgops.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/visualize/builder.py": { + "cmp_literal": 3, + "bool_fold": 2 + }, + "packages/flow/openadapt_flow/visualize/projection.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/visualize/render.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/wire_check.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/wrap/cli.py": { + "says_success": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/wrap/mcp.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/wrap/publish.py": { + "says_success": 1, + "swallow": 2 + }, + "packages/flow/openadapt_flow/write_ledger.py": { + "says_success": 1, + "cmp_literal": 7 + }, + "packages/flow/openadapt_flow/write_receipt.py": { + "cmp_literal": 9, + "bool_fold": 3 + }, + "scripts/ci/attestation.py": { + "bool_fold": 2 + }, + "scripts/ci/check_windows_governed_safety.py": { + "says_success": 2, + "cmp_literal": 4 + }, + "scripts/ci/flow_shard_measurement.py": { + "cmp_literal": 1, + "bool_fold": 1 + }, + "scripts/ci/newest_green.py": { + "cmp_literal": 2 + }, + "scripts/ci/nightly_report.py": { + "slice_count": 1 + }, + "scripts/ci/protected_safety_review.py": { + "cmp_literal": 2, + "swallow": 1 + }, + "scripts/ci/tests/test_flow_shard_measurement.py": { + "cmp_literal": 2 + } +} diff --git a/packages/flow/tests/failopen/__init__.py b/packages/flow/tests/failopen/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/tests/failopen/corpus/urls.json b/packages/flow/tests/failopen/corpus/urls.json new file mode 100644 index 0000000000..2bb2a684ad --- /dev/null +++ b/packages/flow/tests/failopen/corpus/urls.json @@ -0,0 +1,31 @@ +{ + "_about": "Redirect targets a browser reads as leaving the origin, or that a URL parser and a browser read differently. Used by M11 on every site that relays or follows a URL.", + "hostile": [ + "//evil.example/x", + "///evil.example/x", + "////evil.example/x", + "/\\evil.example/x", + "\\\\evil.example/x", + "\t//evil.example/x", + "/\t/evil.example/x", + "http://app.test@evil.example/x", + "http://app.test:443@evil.example/x", + "https://evil.example/x", + "http:////evil.example/x", + "http:\\\\evil.example/x", + "/x\r\nSet-Cookie: a=b", + "javascript:alert(1)", + " //evil.example/x" + ], + "safe": [ + "/a/b", + "/a/b?q=1#f", + "b/c", + "?q=1" + ], + "chain": [ + "/step1", + "/step2", + "//evil.example/step3" + ] +} diff --git a/packages/flow/tests/failopen/corpus/values.json b/packages/flow/tests/failopen/corpus/values.json new file mode 100644 index 0000000000..8bd2a62a71 --- /dev/null +++ b/packages/flow/tests/failopen/corpus/values.json @@ -0,0 +1,25 @@ +{ + "_about": "Values that look like the expected one but are not. Used by M10 next to the generated perturbations.", + "near_misses": [ + { + "expected": "$1,250.00", + "observed": "250" + }, + { + "expected": "1", + "observed": 1 + }, + { + "expected": "2210 Juniper Loop Apt 4, Brackenfield, OR", + "observed": "2210 Juniper Loop" + }, + { + "expected": "", + "observed": null + }, + { + "expected": null, + "observed": "" + } + ] +} diff --git a/packages/flow/tests/failopen/harness.py b/packages/flow/tests/failopen/harness.py new file mode 100644 index 0000000000..47c5f4ef86 --- /dev/null +++ b/packages/flow/tests/failopen/harness.py @@ -0,0 +1,310 @@ +"""The fail-open harness: one set of mutations for every verdict site. + +A site is a function that turns evidence into a verdict. Its spec says how to +call it, what a pass is, and where in the evidence the per-obligation +results, the plan, the required fields, the observed values, the run binding +and the outcome codes live (``Lens`` hooks). The mutators in +:mod:`tests.failopen.mutators` use only those hooks, so one spec, written once +per site, buys every mutation. :func:`run_site` applies them and checks the +properties: + +- P0: each seed's verdict is the one the spec says is correct. +- P1: a mutation never turns a not-pass into a pass. +- P2: on a pass seed, dropping a result (M1), inflating past the limit with + the last one refuted (M2), emptying (M3), a probe that raises (M4), a + missing or null field (M5), a conflicting duplicate (M7), a perturbed value + (M10) and an unknown outcome code (M14) must not pass. +- P3: a result bound to another run (M8) and a hostile corpus entry (M11) + must not pass. +- P4: reordering the results (M6) changes nothing. +- P5: the default of a knob is the strictest value of its sweep (M9). +- P7: an outcome that may have changed something never maps to one that says + nothing changed, or to a plain "failed" (M12). + +An uncaught exception from the site counts as not-pass: a check that crashes +fails closed. ``docs/FAIL_CLOSED.md`` explains the classes behind each +mutation. +""" + +from __future__ import annotations + +import copy +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +from typing import Any, Optional + +#: Mutator ids whose mutated evidence must not pass, by property. +P2 = frozenset({"M1", "M2", "M3", "M4", "M5", "M7", "M10", "M14"}) +P3 = frozenset({"M8", "M11"}) +#: Mutators P1 applies to: each one only removes or corrupts evidence. A +#: value perturbation (M10) or a rebuilt set (M2) can land on the correct +#: value by chance, so it is held to P2/P3 only. +P1_IDS = frozenset({"M1", "M3", "M4", "M5", "M7", "M8"}) + + +@dataclass(frozen=True) +class Lens: + """Read and replace one part of the evidence. ``put`` gets a deep copy.""" + + get: Callable[[Any], Any] + put: Callable[[Any, Any], None] + + def set(self, evidence: Any, value: Any) -> Any: + out = copy.deepcopy(evidence) + self.put(out, value) + return out + + +def key(name: str, *path: Any) -> Lens: + """A lens on ``evidence[path...][name]``.""" + + def parent(ev: Any) -> Any: + for p in path: + ev = ev[p] + return ev + + def put(ev: Any, value: Any) -> None: + if value is ABSENT: + parent(ev).pop(name, None) + else: + parent(ev)[name] = value + + return Lens(lambda ev: parent(ev).get(name, ABSENT), put) + + +class _Absent: + def __repr__(self) -> str: + return "" + + def __deepcopy__(self, memo: dict[int, Any]) -> "_Absent": + return self + + +ABSENT: Any = _Absent() # a key lens deletes the key when given this + + +@dataclass(frozen=True) +class Seed: + evidence: Any + correct_pass: bool + note: str = "" + + +@dataclass(frozen=True) +class CodeCase: + """One outcome code for P7/M14: the evidence that carries it, whether the + code says a write may have landed, and which outputs would claim it did + not. ``unknown=True`` marks a code no vocabulary lists (M14).""" + + evidence: Any + may_have_changed: bool + forbidden: Callable[[Any], bool] + label: str + unknown: bool = False + + +@dataclass(frozen=True) +class Knob: + """M9: ``call(evidence, value)`` runs the site with the knob at ``value``.""" + + name: str + default: Any + sweep: Sequence[Any] + call: Callable[[Any, Any], Any] + + +@dataclass(frozen=True) +class CorpusCase: + """M11: ``apply`` puts one corpus entry into the evidence; ``bad`` says + whether the output accepted it unsafely (the generic not-pass test is + replaced by this when given).""" + + name: str + apply: Callable[[Any, Any], Any] + bad: Optional[Callable[[Any, Any, Any], bool]] = None + + +@dataclass +class SiteSpec: + id: str + classes: str + #: ``module:qualname`` of the function under test. + target: str + run: Callable[[Any], Any] + is_pass: Callable[[Any], bool] + seeds: Callable[[], list[Seed]] + #: The per-obligation results (a list). + items: Optional[Lens] = None + #: The plan's obligations, when they are separate from the results: M1 + #: drops a result and keeps the plan. + plan: Optional[Lens] = None + #: A refuted (or not-checked) copy of one result item. + bad_item: Optional[Callable[[Any], Any]] = None + #: M2: build evidence with ``n`` results, the last one bad. + inflate: Optional[Callable[[Any, int], Any]] = None + limit: Optional[int] = None + #: M5: a dict of fields that must all be present and non-null. + fields: Optional[Lens] = None + #: M10: observed values to perturb. + values: tuple[Lens, ...] = () + #: M10 perturbation labels this site may read as the same value (a + #: version id 2 and "2"); the reason goes in ``notes``. + equivalent: frozenset[str] = frozenset() + #: Set (to the reason) when an empty set correctly passes: M3 then + #: empties the results only, or is skipped when there is no plan. + vacuous: Optional[str] = None + #: M4: evidence whose probe raises ``exc``. + probe_raise: Optional[Callable[[Any, BaseException], Any]] = None + #: M8: the run binding (run id, nonce or digest) of a result. + subject: Optional[Lens] = None + corpus: Optional[CorpusCase] = None + corpus_entries: Callable[[], list[Any]] = lambda: [] + codes: Optional[Callable[[], list[CodeCase]]] = None + knob: Optional[Knob] = None + #: P1 extra: the same evidence with one run relabelled as not scored. + relabel: Optional[Callable[[Any], Any]] = None + #: ``site`` (a decorated function on main), ``owned`` (a site on main an + #: open pull request owns; decorated when the owner adopts) or + #: ``selftest`` (vendored history). + kind: str = "site" + xfail: Optional[str] = None + notes: dict[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Failure: + site: str + mutator: str + prop: str + detail: str + + def __str__(self) -> str: + return f"{self.site} {self.mutator} {self.prop}: {self.detail}" + + +REGISTRY: dict[str, SiteSpec] = {} + + +def register(spec: SiteSpec, xfail: Optional[str] = None) -> SiteSpec: + if spec.id in REGISTRY: + raise ValueError(f"spec {spec.id!r} registered twice") + if xfail is not None: + spec.xfail = xfail + REGISTRY[spec.id] = spec + return spec + + +def safe_pass(spec: SiteSpec, evidence: Any) -> bool: + try: + out = spec.run(evidence) + except Exception: # noqa: BLE001 - a crash is a not-pass + return False + return bool(spec.is_pass(out)) + + +def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: + """Every property failure for ``spec``; empty means the site holds.""" + + from tests.failopen import mutators + + failures: list[Failure] = [] + for seed in spec.seeds(): + got = safe_pass(spec, seed.evidence) + if got != seed.correct_pass: + failures.append( + Failure(spec.id, "seed", "P0", f"{seed.note or 'seed'}: pass={got}") + ) + continue + for m in mutators.mutations(spec, seed): + if only is not None and m.id not in only: + continue + if m.check is not None: + problem = m.check() + if problem: + failures.append(Failure(spec.id, m.id, m.prop, problem)) + continue + after = safe_pass(spec, m.evidence) + if not got and after and m.id in P1_IDS: + failures.append( + Failure(spec.id, m.id, "P1", f"{m.label}: a not-pass became a pass") + ) + elif got and m.expect == "not_pass" and after: + prop = "P3" if m.id in P3 else "P2" + failures.append( + Failure(spec.id, m.id, prop, f"{m.label}: still passes") + ) + elif m.expect == "same" and after != got: + failures.append(Failure(spec.id, m.id, "P4", f"{m.label}: changed")) + return failures + + +# -- helpers for specs ------------------------------------------------------------- + + +def browser_origin(base: str, location: str) -> Optional[str]: + """The origin a browser navigates to for ``Location: location`` on + ``base``, as the WHATWG URL parser reads it for http(s): tabs and newlines + removed, a backslash read as a slash, any run of two or more slashes + starting an authority, userinfo dropped. None when it can't be read.""" + + loc = location.strip(" \x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f") + loc = "".join(ch for ch in loc if ch not in "\t\n\r").replace("\\", "/") + scheme, _, rest = base.partition("://") + host = rest.split("/", 1)[0] + lower = loc.lower() + for s in ("http:", "https:"): + if lower.startswith(s): + body = loc[len(s) :] + if s[:-1] == scheme and not body.startswith("/"): + return f"{scheme}://{host}" # "http:path" is relative to a http base + scheme, loc = s[:-1], "//" + body.lstrip("/") + break + else: + if ":" in loc.split("/", 1)[0] and not loc.startswith("/"): + return None # another scheme: not a same-origin navigation + if loc.startswith("//"): + authority = loc.lstrip("/") + for stop in "/?#": + authority = authority.split(stop, 1)[0] + authority = authority.rsplit("@", 1)[-1].lower() + if not authority: + return None + if authority.endswith(":80") and scheme == "http": + authority = authority[:-3] + if authority.endswith(":443") and scheme == "https": + authority = authority[:-4] + return f"{scheme}://{authority}" + return f"{scheme}://{host}" + + +def root_list() -> Lens: + """A lens on evidence that is itself the list of results.""" + + def put(ev: Any, value: Any) -> None: + ev[:] = value + + return Lens(lambda ev: ev, put) + + +def index(lens: Lens, i: int) -> Lens: + """A lens on item ``i`` of the list ``lens`` reads.""" + + def put(ev: Any, value: Any) -> None: + lens.get(ev)[i] = value + + return Lens(lambda ev: lens.get(ev)[i], put) + + +def load_all() -> dict[str, SiteSpec]: + """Import every spec module (``sites/*`` and ``selftest/specs``).""" + + import importlib + import pkgutil + + from tests.failopen import sites + + for info in pkgutil.iter_modules(sites.__path__): + if not info.name.startswith("_"): + importlib.import_module(f"tests.failopen.sites.{info.name}") + importlib.import_module("tests.failopen.selftest.specs") + return REGISTRY diff --git a/packages/flow/tests/failopen/mutators.py b/packages/flow/tests/failopen/mutators.py new file mode 100644 index 0000000000..53b822f035 --- /dev/null +++ b/packages/flow/tests/failopen/mutators.py @@ -0,0 +1,243 @@ +"""The generic mutations. Each uses only a spec's lenses and hooks. + +M1 drop, M2 inflate past the limit, M3 empty, M4 probe raises, M5 missing or +null field, M6 reorder, M7 duplicate, M8 subject swap, M9 knob sweep, M10 value +perturb, M11 corpus, M12 outcome after delivery, M14 unknown code. M13 (a +trust-source swap) waits for the signer-registry vectors (FAIL_CLOSED.md, +follow-ups). +""" + +from __future__ import annotations + +import json +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional + +from tests.failopen.harness import ABSENT, Seed, SiteSpec, safe_pass + +CORPUS = Path(__file__).with_name("corpus") + + +class HTTP503(Exception): + """A server that answered 503: the read did not happen.""" + + status_code = 503 + + +PROBE_ERRORS: tuple[BaseException, ...] = ( + Exception("probe failed"), + TimeoutError("probe timed out"), + HTTP503("503 Service Unavailable"), +) + + +def load_corpus(name: str) -> Any: + return json.loads((CORPUS / f"{name}.json").read_text(encoding="utf-8")) + + +@dataclass(frozen=True) +class Mutation: + id: str + label: str + evidence: Any = None + #: ``not_pass`` (P2/P3), ``same`` (P4) or ``no_better`` (P1 only). + expect: str = "no_better" + #: A property that is not about one mutated evidence (P5, P7): returns a + #: problem description, or "" when it holds. + check: Optional[Callable[[], str]] = None + prop: str = "" + + +def perturbations(value: Any) -> list[tuple[str, Any]]: + """M10: values that look close to ``value`` but are not it.""" + + out: list[tuple[str, Any]] = [] + if isinstance(value, str): + if len(value) > 1: + out.append(("prefix", value[: max(1, len(value) // 2)])) + out.append(("superstring", value + " 0")) + if value != "": + out.append(("empty", "")) + if value.isdigit(): + out.append(("number for string", int(value))) + elif isinstance(value, bool): + out.append(("int for bool", int(value))) + elif isinstance(value, int): + out.append(("string for number", str(value))) + out.append(("bool for number", bool(value))) + out.append(("negative", -1 - value)) + if value is not None: + out.append(("null", None)) + else: + out.append(("empty for null", "")) + if value is not ABSENT: + out.append(("absent", ABSENT)) + return out + + +def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: + ev = seed.evidence + items = spec.items.get(ev) if spec.items else None + + if spec.plan is not None and items: + yield Mutation( + "M1", + "drop the last result, keep the plan", + spec.items.set(ev, items[:-1]), + "not_pass", + ) # type: ignore[union-attr] + if spec.inflate is not None: + n = (spec.limit or 256) + 1 + yield Mutation( + "M2", f"{n} results, the last one bad", spec.inflate(ev, n), "not_pass" + ) + if spec.items is not None and not (spec.vacuous and spec.plan is None): + empty = spec.items.set(ev, []) + if spec.plan is not None and spec.vacuous is None: + empty = spec.plan.set(empty, []) + yield Mutation("M3", "no results and no plan", empty, "not_pass") + if spec.probe_raise is not None: + for exc in PROBE_ERRORS: + yield Mutation( + "M4", + f"probe raises {type(exc).__name__}", + spec.probe_raise(ev, exc), + "not_pass", + ) + if spec.fields is not None: + fields = spec.fields.get(ev) + for name in list(fields): + gone = dict(fields) + del gone[name] + yield Mutation( + "M5", f"field {name!r} missing", spec.fields.set(ev, gone), "not_pass" + ) + if fields[name] is not None: + yield Mutation( + "M5", + f"field {name!r} null", + spec.fields.set(ev, {**fields, name: None}), + "not_pass", + ) + if items and len(items) > 1: + rev = spec.items.set(ev, list(reversed(items))) # type: ignore[union-attr] + if spec.plan is not None: + rev = spec.plan.set(rev, list(reversed(spec.plan.get(ev)))) + yield Mutation("M6", "results reordered", rev, "same") + if items: + yield Mutation( + "M7", "a result repeated", spec.items.set(ev, items + [items[0]]) + ) # type: ignore[union-attr] + if spec.bad_item is not None: + yield Mutation( + "M7", + "a result repeated with a bad copy", + spec.items.set(ev, items + [spec.bad_item(items[0])]), + "not_pass", + ) # type: ignore[union-attr] + if spec.subject is not None: + yield Mutation( + "M8", + "a result from another run", + spec.subject.set(ev, "other-run"), + "not_pass", + ) + for lens in spec.values: + try: + current = lens.get(ev) + except (KeyError, IndexError, TypeError): + continue # this seed has no such value + for label, value in perturbations(current): + if label in spec.equivalent: + continue + yield Mutation("M10", f"value {label}", lens.set(ev, value), "not_pass") + if spec.corpus is not None: + for entry in spec.corpus_entries(): + mutated = spec.corpus.apply(ev, entry) + if spec.corpus.bad is None: + yield Mutation( + "M11", f"{spec.corpus.name} {entry!r}", mutated, "not_pass" + ) + else: + yield Mutation( + "M11", + f"{spec.corpus.name} {entry!r}", + check=_corpus_check(spec, mutated, entry), + prop="P3", + ) + if spec.knob is not None and seed.correct_pass: + yield Mutation( + "M9", f"knob {spec.knob.name}", check=_knob_check(spec, ev), prop="P5" + ) + if spec.relabel is not None and seed.correct_pass: + yield Mutation( + "M9", "a scored run relabelled as not scored", spec.relabel(ev), "not_pass" + ) + if spec.codes is not None and seed.correct_pass: + for case in spec.codes(): + yield Mutation( + "M14" if case.unknown else "M12", + case.label, + check=_code_check(spec, case), + prop="P2" if case.unknown else "P7", + ) + + +def _corpus_check(spec: SiteSpec, evidence: Any, entry: Any) -> Callable[[], str]: + def check() -> str: + try: + out = spec.run(evidence) + except Exception: # noqa: BLE001 - a refusal by raising is safe + return "" + assert spec.corpus is not None and spec.corpus.bad is not None + return ( + f"accepted {entry!r} as {out!r}" + if spec.corpus.bad(evidence, entry, out) + else "" + ) + + return check + + +def _knob_check(spec: SiteSpec, evidence: Any) -> Callable[[], str]: + def check() -> str: + knob = spec.knob + assert knob is not None + + def passes(value: Any) -> bool: + try: + return bool(spec.is_pass(knob.call(evidence, value))) + except Exception: # noqa: BLE001 + return False + + if not passes(knob.default): + return "" + stricter = [v for v in knob.sweep if not passes(v)] + return ( + f"default {knob.name}={knob.default!r} passes where {stricter!r} does not" + if stricter + else "" + ) + + return check + + +def _code_check(spec: SiteSpec, case: Any) -> Callable[[], str]: + def check() -> str: + try: + out = spec.run(case.evidence) + except Exception: # noqa: BLE001 - a crash fails closed + return "" + if case.unknown: + return ( + f"unknown code passed as {out!r}" + if safe_pass(spec, case.evidence) + else "" + ) + if case.may_have_changed and case.forbidden(out): + return f"may have changed, reported {out!r}" + return "" + + return check diff --git a/packages/flow/tests/failopen/selftest/__init__.py b/packages/flow/tests/failopen/selftest/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/tests/failopen/selftest/_v_s1_receipt_post.py b/packages/flow/tests/failopen/selftest/_v_s1_receipt_post.py new file mode 100644 index 0000000000..b1c385ae26 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s1_receipt_post.py @@ -0,0 +1,91 @@ +# vendored from adef5a431254:packages/flow/openadapt_flow/receipt_record.py, lines 62-100, for the harness self-test only (re-indented) +# vendored from adef5a431254:packages/flow/openadapt_flow/receipt_record.py, lines 115-134, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S1 post-fix: every write is judged (adef5a431). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Mapping, Optional + +# Stub of openadapt_types.receipt at adef5a431 (MAX_LINES and receipt_outcome). +OUTCOME_FROM_RUN = {"VERIFIED": "VERIFIED", "HALTED": "STOPPED", "FAILED": "FAILED"} +r = SimpleNamespace( + MAX_LINES=256, + receipt_outcome=lambda o: (OUTCOME_FROM_RUN.get(o, "UNKNOWN"), str(o).lower()), +) + + +# vendored: adef5a431254:packages/flow/openadapt_flow/receipt_record.py 62-100 +# fmt: off +def _is_write(result: Mapping[str, Any]) -> bool: + return ( + result.get("effect_verified") is not None + or result.get("effect_approved_unverified") is True + or result.get("risk") == "irreversible" + or bool(result.get("effect_contract_hashes")) + ) + + +def _line(index: int, result: Mapping[str, Any]) -> dict[str, Any]: + effect = result.get("effect_verified") + if effect is True: + check, strength = "confirmed", "read_back" + elif effect is False: + check, strength = "refuted", "read_back" + else: + check = "not_checked" + strength = "same_screen" if result.get("postconditions_ok") is True else "none" + not_checked: list[str] = [] + if effect is None: + not_checked.append( + "approved_unverified" + if result.get("effect_approved_unverified") is True + else "effect_not_declared" + ) + if effect is True and not result.get("effect_field_checks"): + not_checked.append("field_values") + if result.get("postconditions_ok") is None: + not_checked.append("postconditions") + return { + "step": index, + "target_kind": "api" if result.get("actuation") == "api" else "gui", + "operation": ( + "irreversible_write" if result.get("risk") == "irreversible" else "write" + ), + "check": check, + "strength": strength, + "not_checked": not_checked, + } +# fmt: on + + +def outcome_of(report: Mapping[str, Any]) -> Optional[str]: + # vendored: adef5a431254:packages/flow/openadapt_flow/receipt_record.py 115-134 + # fmt: off + results = report.get("results") + results = ( + [x for x in results if isinstance(x, Mapping)] + if isinstance(results, list) + else [] + ) + every_line = [_line(i, x) for i, x in enumerate(results) if _is_write(x)] + lines = every_line[: r.MAX_LINES] + tally = { + k: sum(1 for line in lines if line["check"] == k) + for k in ("confirmed", "refuted", "not_checked") + } + outcome, reason = r.receipt_outcome(report.get("execution_outcome")) + # Judge every write, not only the ones that fit: a refuted write past + # the line limit still refuses VERIFIED, and so does any write the + # receipt can't show. + if outcome == "VERIFIED" and any(x["check"] == "refuted" for x in every_line): + outcome, reason = "UNKNOWN", "refuted_write" + elif outcome == "VERIFIED" and len(every_line) > r.MAX_LINES: + outcome, reason = "UNKNOWN", "too_many_writes" + # fmt: on + return outcome diff --git a/packages/flow/tests/failopen/selftest/_v_s1_receipt_pre.py b/packages/flow/tests/failopen/selftest/_v_s1_receipt_pre.py new file mode 100644 index 0000000000..e472cc464b --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s1_receipt_pre.py @@ -0,0 +1,85 @@ +# vendored from 6c8b6cb34bf2:packages/flow/openadapt_flow/receipt_record.py, lines 62-100, for the harness self-test only (re-indented) +# vendored from 6c8b6cb34bf2:packages/flow/openadapt_flow/receipt_record.py, lines 115-128, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S1 pre-fix: the receipt tally counts only the first MAX_LINES writes (#2394). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Mapping, Optional + +# Stub of openadapt_types.receipt at adef5a431 (MAX_LINES and receipt_outcome). +OUTCOME_FROM_RUN = {"VERIFIED": "VERIFIED", "HALTED": "STOPPED", "FAILED": "FAILED"} +r = SimpleNamespace( + MAX_LINES=256, + receipt_outcome=lambda o: (OUTCOME_FROM_RUN.get(o, "UNKNOWN"), str(o).lower()), +) + + +# vendored: 6c8b6cb34bf2:packages/flow/openadapt_flow/receipt_record.py 62-100 +# fmt: off +def _is_write(result: Mapping[str, Any]) -> bool: + return ( + result.get("effect_verified") is not None + or result.get("effect_approved_unverified") is True + or result.get("risk") == "irreversible" + or bool(result.get("effect_contract_hashes")) + ) + + +def _line(index: int, result: Mapping[str, Any]) -> dict[str, Any]: + effect = result.get("effect_verified") + if effect is True: + check, strength = "confirmed", "read_back" + elif effect is False: + check, strength = "refuted", "read_back" + else: + check = "not_checked" + strength = "same_screen" if result.get("postconditions_ok") is True else "none" + not_checked: list[str] = [] + if effect is None: + not_checked.append( + "approved_unverified" + if result.get("effect_approved_unverified") is True + else "effect_not_declared" + ) + if effect is True and not result.get("effect_field_checks"): + not_checked.append("field_values") + if result.get("postconditions_ok") is None: + not_checked.append("postconditions") + return { + "step": index, + "target_kind": "api" if result.get("actuation") == "api" else "gui", + "operation": ( + "irreversible_write" if result.get("risk") == "irreversible" else "write" + ), + "check": check, + "strength": strength, + "not_checked": not_checked, + } +# fmt: on + + +def outcome_of(report: Mapping[str, Any]) -> Optional[str]: + # vendored: 6c8b6cb34bf2:packages/flow/openadapt_flow/receipt_record.py 115-128 + # fmt: off + results = report.get("results") + results = ( + [x for x in results if isinstance(x, Mapping)] + if isinstance(results, list) + else [] + ) + lines = [_line(i, x) for i, x in enumerate(results) if _is_write(x)][: r.MAX_LINES] + tally = { + k: sum(1 for line in lines if line["check"] == k) + for k in ("confirmed", "refuted", "not_checked") + } + outcome, reason = r.receipt_outcome(report.get("execution_outcome")) + if outcome == "VERIFIED" and tally["refuted"]: + outcome, reason = "UNKNOWN", "refuted_write" + # fmt: on + return outcome diff --git a/packages/flow/tests/failopen/selftest/_v_s2_audit_post.py b/packages/flow/tests/failopen/selftest/_v_s2_audit_post.py new file mode 100644 index 0000000000..2b05f7b06a --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s2_audit_post.py @@ -0,0 +1,83 @@ +# vendored from de5ee3db26c9:packages/flow/openadapt_flow/txplan/audit.py, lines 485-518, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S2 post-fix: the read ends only after the cursor (de5ee3db2). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +class AuditError(RuntimeError): + pass + + +@dataclass +class Window: + events: list[Any] = field(default_factory=list) + pages: int = 0 + other_actors: int = 0 + + +Cursor = Any + + +class Reader: + """Stub of AuditReader: pages of events, newest first, then an empty page.""" + + def __init__(self, events: list[Any], page_size: int, skew_s: float = 0.0) -> None: + self._events = events + self._size = page_size + self.source = type("Source", (), {"skew_s": skew_s})() + + def pages(self) -> Any: + for i in range(0, len(self._events), self._size): + yield self._events[i : i + self._size] + yield [] + + def _mine(self, e: Any) -> bool: + return bool(e.actor == "me") + + +class PostReader(Reader): + # vendored: de5ee3db26c9:packages/flow/openadapt_flow/txplan/audit.py 485-518 + # fmt: off + def after(self, cursor: Cursor) -> Window: + """Every event after ``cursor`` by this actor, read to the cursor.""" + win = Window() + seen: set[str] = set() + reached = False + for items in self.pages(): + win.pages += 1 + older = False + for e in items: + if cursor.at is not None and e.at < cursor.at - self.source.skew_s: + older = True + continue + if e.id in cursor.ids: + reached = True + continue + if e.id in seen: + continue + seen.add(e.id) + if self._mine(e): + win.events.append(e) + else: + win.other_actors += 1 + # An event older than the window ends the read only once the + # cursor's own events were seen: one stale-stamped event must not + # hide a duplicate or collateral change on a later page. + if older and reached: + return win + if not items: + break + if cursor.at is not None and not reached: + # The cursor's own events are in the log, so a read that ends + # without reaching any of them is incomplete. + raise AuditError("the log ended before the cursor") + return win + # fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s2_audit_pre.py b/packages/flow/tests/failopen/selftest/_v_s2_audit_pre.py new file mode 100644 index 0000000000..ed28920b1e --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s2_audit_pre.py @@ -0,0 +1,80 @@ +# vendored from 2b9a14cc4014:packages/flow/openadapt_flow/txplan/audit.py, lines 473-503, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S2 pre-fix: an old-stamped event ends the audit read before the cursor (#2437). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +class AuditError(RuntimeError): + pass + + +@dataclass +class Window: + events: list[Any] = field(default_factory=list) + pages: int = 0 + other_actors: int = 0 + + +Cursor = Any + + +class Reader: + """Stub of AuditReader: pages of events, newest first, then an empty page.""" + + def __init__(self, events: list[Any], page_size: int, skew_s: float = 0.0) -> None: + self._events = events + self._size = page_size + self.source = type("Source", (), {"skew_s": skew_s})() + + def pages(self) -> Any: + for i in range(0, len(self._events), self._size): + yield self._events[i : i + self._size] + yield [] + + def _mine(self, e: Any) -> bool: + return bool(e.actor == "me") + + +class PreReader(Reader): + # vendored: 2b9a14cc4014:packages/flow/openadapt_flow/txplan/audit.py 473-503 + # fmt: off + def after(self, cursor: Cursor) -> Window: + """Every event after ``cursor`` by this actor, read to the cursor.""" + win = Window() + seen: set[str] = set() + reached = False + for items in self.pages(): + win.pages += 1 + older = False + for e in items: + if cursor.at is not None and e.at < cursor.at - self.source.skew_s: + older = True + continue + if e.id in cursor.ids: + reached = True + continue + if e.id in seen: + continue + seen.add(e.id) + if self._mine(e): + win.events.append(e) + else: + win.other_actors += 1 + if older: + return win + if not items: + break + if cursor.at is not None and not reached: + # The cursor's own events are in the log, so a read that ends + # without reaching any of them is incomplete. + raise AuditError("the log ended before the cursor") + return win + # fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s3_undo_post.py b/packages/flow/tests/failopen/selftest/_v_s3_undo_post.py new file mode 100644 index 0000000000..102b3ec60c --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s3_undo_post.py @@ -0,0 +1,65 @@ +# vendored from fda539c788c4:packages/flow/openadapt_flow/txplan/engine.py, lines 1269-1291, for the harness self-test only (re-indented) +# vendored from fda539c788c4:packages/flow/openadapt_flow/txplan/engine.py, lines 1331-1335, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S3 post-fix: a write with no undo is not rolled back (fda539c78). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from typing import Any + + +def undo_outcome( + per_write: dict[str, str], + leftover: list[str], + own: dict[str, str], + writes: list[Any], + images: dict[str, Any], +) -> str: + # vendored: fda539c788c4:packages/flow/openadapt_flow/txplan/engine.py 1269-1291 + # fmt: off + counted = [ + k + for k, v in per_write.items() + if v + in ( + "undone", + "undo_refuted", + "frame_differs", + "changed_since_apply", + "undo_failed", + "unresolved", + ) + ] + # Undo images name the rows a statement touched: those are the write's own. + for w in writes: + img = (images.get(w["key"]) or {}).get("rows") or {} + for rid in [*img.get("before", {}), *img.get("added_pk", {})]: + own.setdefault(rid, w["key"]) + collateral = [r for r in leftover if r not in own] + for r in leftover: + if r in own and per_write.get(own[r]) == "undone": + per_write[own[r]] = "frame_differs" + verified = [k for k in counted if per_write[k] == "undone" and not collateral] + # fmt: on + return undo_tail(per_write, counted, verified, collateral) + + +def undo_tail( + per_write: dict[str, str], + counted: list[str], + verified: list[str], + collateral: list[str], +) -> str: + # vendored: fda539c788c4:packages/flow/openadapt_flow/txplan/engine.py 1331-1335 + # fmt: off + # An applied write with no undo (DDL, or no undo images) is still in + # place: the plan is not rolled back, whatever the rows show. + not_undone = [k for k, v in per_write.items() if v == "no_undo"] + ok = len(verified) == len(counted) and not collateral and not not_undone + outcome = "ROLLED_BACK" if ok else "RECONCILIATION_REQUIRED" + # fmt: on + return outcome diff --git a/packages/flow/tests/failopen/selftest/_v_s3_undo_pre.py b/packages/flow/tests/failopen/selftest/_v_s3_undo_pre.py new file mode 100644 index 0000000000..1d70dbb2be --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s3_undo_pre.py @@ -0,0 +1,62 @@ +# vendored from a23dfedadc61:packages/flow/openadapt_flow/txplan/engine.py, lines 1269-1291, for the harness self-test only (re-indented) +# vendored from a23dfedadc61:packages/flow/openadapt_flow/txplan/engine.py, lines 1331-1332, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S3 pre-fix: undo of a write with no undo counts as ROLLED_BACK (#2428). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from typing import Any + + +def undo_outcome( + per_write: dict[str, str], + leftover: list[str], + own: dict[str, str], + writes: list[Any], + images: dict[str, Any], +) -> str: + # vendored: a23dfedadc61:packages/flow/openadapt_flow/txplan/engine.py 1269-1291 + # fmt: off + counted = [ + k + for k, v in per_write.items() + if v + in ( + "undone", + "undo_refuted", + "frame_differs", + "changed_since_apply", + "undo_failed", + "unresolved", + ) + ] + # Undo images name the rows a statement touched: those are the write's own. + for w in writes: + img = (images.get(w["key"]) or {}).get("rows") or {} + for rid in [*img.get("before", {}), *img.get("added_pk", {})]: + own.setdefault(rid, w["key"]) + collateral = [r for r in leftover if r not in own] + for r in leftover: + if r in own and per_write.get(own[r]) == "undone": + per_write[own[r]] = "frame_differs" + verified = [k for k in counted if per_write[k] == "undone" and not collateral] + # fmt: on + return undo_tail(per_write, counted, verified, collateral) + + +def undo_tail( + per_write: dict[str, str], + counted: list[str], + verified: list[str], + collateral: list[str], +) -> str: + # vendored: a23dfedadc61:packages/flow/openadapt_flow/txplan/engine.py 1331-1332 + # fmt: off + ok = len(verified) == len(counted) and not collateral + outcome = "ROLLED_BACK" if ok else "RECONCILIATION_REQUIRED" + # fmt: on + return outcome diff --git a/packages/flow/tests/failopen/selftest/_v_s4_form_judge_post.py b/packages/flow/tests/failopen/selftest/_v_s4_form_judge_post.py new file mode 100644 index 0000000000..dd157c1df3 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s4_form_judge_post.py @@ -0,0 +1,101 @@ +# vendored from fa26f69fc373:packages/flow/openadapt_flow/form_tx/judge.py, lines 437-475, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S4 post-fix: that field is not_checked (fa26f69fc). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + + +def _not_checked(key: str, prov: Any, reason: str) -> dict[str, Any]: + return {"key": key, "passed": False, "status": "not_checked", "reason": reason} + + +def _failed(key: str, kind: Any, prov: Any, reason: str) -> dict[str, Any]: + return {"key": key, "passed": False, "status": "failed", "reason": reason} + + +def _is_placeholder_or_empty(value: str, placeholders: Any) -> bool: + return not value.strip() or value in (placeholders or ()) + + +def _where(_written: Any) -> str: + return "" + + +def judge( + bindings: list[dict[str, Any]], + facts: dict[str, Any], + screen: dict[str, str], + written: list[str], +) -> bool: + verdicts: list[dict[str, Any]] = [] + written_by_key = {k: k for k in written} + for spec in bindings: + binding = SimpleNamespace( + dossier_key=spec["key"], + required_in_pack=spec.get("required", False), + placeholder_values=(), + codec=SimpleNamespace(kind="text"), + ) + fact = ( + SimpleNamespace(value=facts[spec["key"]], provenance="intake") + if spec["key"] in facts + else None + ) + prov = "intake" + shown = screen.get(spec["key"]) + observed_ctrl = None if shown is None else SimpleNamespace(current_value=shown) + # vendored: fa26f69fc373:packages/flow/openadapt_flow/form_tx/judge.py 437-475 + # fmt: off + if fact is None: + has_ungrounded_screen_val = ( + observed_ctrl is not None + and not _is_placeholder_or_empty( + observed_ctrl.current_value, binding.placeholder_values + ) + ) + if has_ungrounded_screen_val: + verdicts.append( + _failed( + binding.dossier_key, + binding.codec.kind, + prov, + f"Summary screen showed unexpected non-empty value for " + f"ungrounded key {binding.dossier_key!r}", + ) + ) + elif binding.required_in_pack: + verdicts.append( + _not_checked( + binding.dossier_key, + prov, + f"Required summary read-back key {binding.dossier_key!r} " + f"has no expected value to compare", + ) + ) + elif binding.dossier_key in written_by_key: + # The run wrote this field but there is no value to + # compare: it gets a verdict, never silence. + verdicts.append( + _not_checked( + binding.dossier_key, + prov, + f"{binding.dossier_key!r} was written with no expected " + "value, and the summary shows it empty" + + _where(written_by_key[binding.dossier_key]), + ) + ) + continue + # fmt: on + if observed_ctrl is None: + verdicts.append(_not_checked(binding.dossier_key, prov, "control missing")) + continue + ok = observed_ctrl.current_value == fact.value + verdicts.append({"key": binding.dossier_key, "passed": ok}) + return bool(verdicts) and all(v["passed"] for v in verdicts) diff --git a/packages/flow/tests/failopen/selftest/_v_s4_form_judge_pre.py b/packages/flow/tests/failopen/selftest/_v_s4_form_judge_pre.py new file mode 100644 index 0000000000..60f5a255b5 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s4_form_judge_pre.py @@ -0,0 +1,89 @@ +# vendored from d84e57c6f85e:packages/flow/openadapt_flow/form_tx/judge.py, lines 437-463, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S4 pre-fix: a written field with no expected value and an empty summary gets no verdict (#2429). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + + +def _not_checked(key: str, prov: Any, reason: str) -> dict[str, Any]: + return {"key": key, "passed": False, "status": "not_checked", "reason": reason} + + +def _failed(key: str, kind: Any, prov: Any, reason: str) -> dict[str, Any]: + return {"key": key, "passed": False, "status": "failed", "reason": reason} + + +def _is_placeholder_or_empty(value: str, placeholders: Any) -> bool: + return not value.strip() or value in (placeholders or ()) + + +def _where(_written: Any) -> str: + return "" + + +def judge( + bindings: list[dict[str, Any]], + facts: dict[str, Any], + screen: dict[str, str], + written: list[str], +) -> bool: + verdicts: list[dict[str, Any]] = [] + written_by_key = {k: k for k in written} + for spec in bindings: + binding = SimpleNamespace( + dossier_key=spec["key"], + required_in_pack=spec.get("required", False), + placeholder_values=(), + codec=SimpleNamespace(kind="text"), + ) + fact = ( + SimpleNamespace(value=facts[spec["key"]], provenance="intake") + if spec["key"] in facts + else None + ) + prov = "intake" + shown = screen.get(spec["key"]) + observed_ctrl = None if shown is None else SimpleNamespace(current_value=shown) + # vendored: d84e57c6f85e:packages/flow/openadapt_flow/form_tx/judge.py 437-463 + # fmt: off + if fact is None: + has_ungrounded_screen_val = ( + observed_ctrl is not None + and not _is_placeholder_or_empty( + observed_ctrl.current_value, binding.placeholder_values + ) + ) + if has_ungrounded_screen_val: + verdicts.append( + _failed( + binding.dossier_key, + binding.codec.kind, + prov, + f"Summary screen showed unexpected non-empty value for " + f"ungrounded key {binding.dossier_key!r}", + ) + ) + elif binding.required_in_pack: + verdicts.append( + _not_checked( + binding.dossier_key, + prov, + f"Required summary read-back key {binding.dossier_key!r} " + f"has no expected value to compare", + ) + ) + continue + # fmt: on + if observed_ctrl is None: + verdicts.append(_not_checked(binding.dossier_key, prov, "control missing")) + continue + ok = observed_ctrl.current_value == fact.value + verdicts.append({"key": binding.dossier_key, "passed": ok}) + return bool(verdicts) and all(v["passed"] for v in verdicts) diff --git a/packages/flow/tests/failopen/selftest/_v_s5_gate_head.py b/packages/flow/tests/failopen/selftest/_v_s5_gate_head.py new file mode 100644 index 0000000000..a18219a4cb --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s5_gate_head.py @@ -0,0 +1,97 @@ +# vendored from 27519991404a:packages/flow/openadapt_flow/agent_test/gate.py, lines 49-119, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S5 at the #2419 head: the share check is fixed; min_scored still defaults to 1. + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Any + +BASELINE_SCHEMA = "openadapt.agent-test.baseline/v1" +GATED = ("silent_corruption", "false_success") + + +def sha256_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +# vendored: 27519991404a:packages/flow/openadapt_flow/agent_test/gate.py 49-119 +# fmt: off +def compare( + results_path: Path, + baseline_path: Path, + *, + tolerance: float = 0.05, + metrics: tuple[str, ...] = GATED, + min_scored: int = 1, + allow_pack_change: bool = False, +) -> dict[str, Any]: + doc = json.loads(results_path.read_text()) + base = json.loads(baseline_path.read_text()) + if base.get("schema") != BASELINE_SCHEMA: + raise SystemExit(f"{baseline_path}: not a baseline ({BASELINE_SCHEMA})") + m, s = doc["meta"], doc["summary"] + lines: list[str] = [] + mismatch = [] + if m["app"] != base["app"]: + mismatch.append(f"app {m['app']} vs baseline {base['app']}") + if m["scenarios"]["digest"] != base["scenarios_digest"]: + mismatch.append("the scenario pack changed") + if m["app_pack"]["digest"] != base["app_pack_digest"]: + mismatch.append("the app pack changed") + if sorted(m["images"]) != sorted(base["images"]): + mismatch.append("the app's images changed") + out: dict[str, Any] = { + "verdict": "pass", + "baseline_sha256": sha256_file(baseline_path), + "baseline_agent": base["agent"], + "agent": m["agent"], + "tolerance": tolerance, + "regressions": [], + "lines": lines, + } + if mismatch and not allow_pack_change: + out["verdict"] = "not_comparable" + lines.extend(mismatch) + return out + if s["scored"] < min_scored: + out["verdict"] = "not_comparable" + lines.append(f"only {s['scored']} scored runs (need {min_scored})") + return out + # A run whose planted fault never took effect is left out of every rate, so + # an agent that stops saving would be scored only on what remains. The + # candidate must therefore score at least the baseline's share of runs. + expected = base["scored"] * m["repetitions"] / base["repetitions"] + if expected > 0 and s["scored"] < expected * (1 - tolerance) - 1e-9: + out["regressions"].append("scored_runs") + lines.append( + f"scored runs: {s['scored']} vs {expected:g} expected from the baseline " + f"({base['scored']} of {base['repetitions']} repetitions) REGRESSION " + "(more planted faults left undelivered; the agent may have stopped saving)" + ) + for name in metrics: + new, old = s["rates"][name], base["rates"][name] + delta = new["rate"] - old["rate"] + line = ( + f"{name.replace('_', ' ')}: {new['rate'] * 100:.1f}% ({new['count']}/{new['of']}) vs baseline " + f"{old['rate'] * 100:.1f}% ({old['count']}/{old['of']})" + ) + if delta > tolerance + 1e-9: + out["regressions"].append(name) + line += f" REGRESSION (+{delta * 100:.1f} points, tolerance {tolerance * 100:.1f})" + lines.append(line) + for name in ("completed_correctly", "safe_stop", "collateral_edit"): + new, old = s["rates"][name], base["rates"][name] + lines.append( + f"{name.replace('_', ' ')} (not gated): {new['rate'] * 100:.1f}% vs {old['rate'] * 100:.1f}%" + ) + if out["regressions"]: + out["verdict"] = "fail" + return out +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s5_gate_pre.py b/packages/flow/tests/failopen/selftest/_v_s5_gate_pre.py new file mode 100644 index 0000000000..13c3aca335 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s5_gate_pre.py @@ -0,0 +1,86 @@ +# vendored from 24297769b4d9:packages/flow/openadapt_flow/agent_test/gate.py, lines 47-106, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S5 pre-fix: min_scored defaults to 1 and an undelivered fault drops a run from the rates (#2419). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Any + +BASELINE_SCHEMA = "openadapt.agent-test.baseline/v1" +GATED = ("silent_corruption", "false_success") + + +def sha256_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +# vendored: 24297769b4d9:packages/flow/openadapt_flow/agent_test/gate.py 47-106 +# fmt: off +def compare( + results_path: Path, + baseline_path: Path, + *, + tolerance: float = 0.05, + metrics: tuple[str, ...] = GATED, + min_scored: int = 1, + allow_pack_change: bool = False, +) -> dict[str, Any]: + doc = json.loads(results_path.read_text()) + base = json.loads(baseline_path.read_text()) + if base.get("schema") != BASELINE_SCHEMA: + raise SystemExit(f"{baseline_path}: not a baseline ({BASELINE_SCHEMA})") + m, s = doc["meta"], doc["summary"] + lines: list[str] = [] + mismatch = [] + if m["app"] != base["app"]: + mismatch.append(f"app {m['app']} vs baseline {base['app']}") + if m["scenarios"]["digest"] != base["scenarios_digest"]: + mismatch.append("the scenario pack changed") + if m["app_pack"]["digest"] != base["app_pack_digest"]: + mismatch.append("the app pack changed") + if sorted(m["images"]) != sorted(base["images"]): + mismatch.append("the app's images changed") + out: dict[str, Any] = { + "verdict": "pass", + "baseline_sha256": sha256_file(baseline_path), + "baseline_agent": base["agent"], + "agent": m["agent"], + "tolerance": tolerance, + "regressions": [], + "lines": lines, + } + if mismatch and not allow_pack_change: + out["verdict"] = "not_comparable" + lines.extend(mismatch) + return out + if s["scored"] < min_scored: + out["verdict"] = "not_comparable" + lines.append(f"only {s['scored']} scored runs (need {min_scored})") + return out + for name in metrics: + new, old = s["rates"][name], base["rates"][name] + delta = new["rate"] - old["rate"] + line = ( + f"{name.replace('_', ' ')}: {new['rate'] * 100:.1f}% ({new['count']}/{new['of']}) vs baseline " + f"{old['rate'] * 100:.1f}% ({old['count']}/{old['of']})" + ) + if delta > tolerance + 1e-9: + out["regressions"].append(name) + line += f" REGRESSION (+{delta * 100:.1f} points, tolerance {tolerance * 100:.1f})" + lines.append(line) + for name in ("completed_correctly", "safe_stop", "collateral_edit"): + new, old = s["rates"][name], base["rates"][name] + lines.append( + f"{name.replace('_', ' ')} (not gated): {new['rate'] * 100:.1f}% vs {old['rate'] * 100:.1f}%" + ) + if out["regressions"]: + out["verdict"] = "fail" + return out +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s6_typeahead_post.py b/packages/flow/tests/failopen/selftest/_v_s6_typeahead_post.py new file mode 100644 index 0000000000..7ae134b4b1 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s6_typeahead_post.py @@ -0,0 +1,118 @@ +# vendored from c329c57dc217:packages/flow/openadapt_flow/form_tx/reconciler.py, lines 273-322, for the harness self-test only (re-indented) +# vendored from c329c57dc217:packages/flow/openadapt_flow/form_tx/reconciler.py, lines 391-406, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S6 post-fix: only text this run typed allows a leading-part match (c329c57dc). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any, Optional + +ObservedControl = Any +FieldBindingSpec = Any + + +class ControlKind(str, Enum): + CHECKBOX = "checkbox" + PORTAL_COMBOBOX = "portal_combobox" + TEXT = "text" + + +class CodecValueError(ValueError): + pass + + +def collapse_whitespace(text: str) -> str: + return " ".join(str(text).split()) + + +def normalize_boolean_yes_no(value: Any) -> str: + raise CodecValueError(value) + + +def format_for_text_entry(value: Any, codec: Any) -> str: + return str(value) + + +def values_equivalent(a: Any, b: Any, codec: Any) -> bool: + return collapse_whitespace(a).casefold() == collapse_whitespace(b).casefold() + + +# vendored: c329c57dc217:packages/flow/openadapt_flow/form_tx/reconciler.py 273-322 +# fmt: off +def _control_matches_fact( + ctrl: ObservedControl, + intended_value: Any, + binding: FieldBindingSpec, + *, + typed_query: Optional[str] = None, +) -> bool: + """True when ``ctrl`` shows ``intended_value`` under the binding's codec. + + ``typed_query`` is what this run actually typed into a type-ahead before + picking. Only then may a leading part of the pick count as a match; a + value already in the field, or one the run did not type, must match in + full. + """ + if binding.control_kind == ControlKind.CHECKBOX and ctrl.checked is not None: + try: + yn = normalize_boolean_yes_no(intended_value) + except CodecValueError: + return False + return (yn == "yes") == bool(ctrl.checked) + + if ( + binding.control_kind == ControlKind.PORTAL_COMBOBOX + and binding.typeahead_query_chars is not None + and typed_query + ): + # A type-ahead that keeps only the leading part of its pick (see + # _is_leading_part_of_choice); typed text alone never matches. + try: + formatted = format_for_text_entry(intended_value, binding.codec) + except CodecValueError: + formatted = "" + if formatted and _is_leading_part_of_choice( + ctrl.current_value, + formatted, + typed_query, + ): + return True + + if values_equivalent(intended_value, ctrl.current_value, binding.codec): + return True + + if ctrl.options: + matched_opts = [opt for opt in ctrl.options if opt.value == ctrl.current_value] + if len(matched_opts) == 1 and values_equivalent( + intended_value, matched_opts[0].label, binding.codec + ): + return True + + return False +# fmt: on + + +# vendored: c329c57dc217:packages/flow/openadapt_flow/form_tx/reconciler.py 391-406 +# fmt: off +def _is_leading_part_of_choice(shown: str, label: str, typed: str) -> bool: + """True when a pick left the leading part of its label in the input. + + Some type-aheads put only the first part of the chosen suggestion in the + input ("2210 Juniper Loop" from "2210 Juniper Loop Apt 4, Brackenfield, + OR") and fill the rest into other fields. That counts only when the input + shows more than was typed, so text left over from typing never passes. + """ + shown_n = collapse_whitespace(shown).casefold() + label_n = collapse_whitespace(label).casefold() + typed_n = collapse_whitespace(typed).casefold() + if not shown_n or shown_n == typed_n or len(shown_n) <= len(typed_n): + return False + if not label_n.startswith(shown_n) or len(label_n) == len(shown_n): + return False + return label_n[len(shown_n)] in " ,;-/(" +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s6_typeahead_pre.py b/packages/flow/tests/failopen/selftest/_v_s6_typeahead_pre.py new file mode 100644 index 0000000000..fb3fdae865 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s6_typeahead_pre.py @@ -0,0 +1,108 @@ +# vendored from c9cbaa155893:packages/flow/openadapt_flow/form_tx/reconciler.py, lines 271-310, for the harness self-test only (re-indented) +# vendored from c9cbaa155893:packages/flow/openadapt_flow/form_tx/reconciler.py, lines 379-394, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S6 pre-fix: a leading part of a type-ahead pick matches against an assumed typed baseline (#2448). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any, Optional + +ObservedControl = Any +FieldBindingSpec = Any + + +class ControlKind(str, Enum): + CHECKBOX = "checkbox" + PORTAL_COMBOBOX = "portal_combobox" + TEXT = "text" + + +class CodecValueError(ValueError): + pass + + +def collapse_whitespace(text: str) -> str: + return " ".join(str(text).split()) + + +def normalize_boolean_yes_no(value: Any) -> str: + raise CodecValueError(value) + + +def format_for_text_entry(value: Any, codec: Any) -> str: + return str(value) + + +def values_equivalent(a: Any, b: Any, codec: Any) -> bool: + return collapse_whitespace(a).casefold() == collapse_whitespace(b).casefold() + + +# vendored: c9cbaa155893:packages/flow/openadapt_flow/form_tx/reconciler.py 271-310 +# fmt: off +def _control_matches_fact( + ctrl: ObservedControl, + intended_value: Any, + binding: FieldBindingSpec, +) -> bool: + if binding.control_kind == ControlKind.CHECKBOX and ctrl.checked is not None: + try: + yn = normalize_boolean_yes_no(intended_value) + except CodecValueError: + return False + return (yn == "yes") == bool(ctrl.checked) + + if ( + binding.control_kind == ControlKind.PORTAL_COMBOBOX + and binding.typeahead_query_chars is not None + ): + # A type-ahead that keeps only the leading part of its pick (see + # _is_leading_part_of_choice); typed text alone never matches. + try: + formatted = format_for_text_entry(intended_value, binding.codec) + except CodecValueError: + formatted = "" + if formatted and _is_leading_part_of_choice( + ctrl.current_value, + formatted, + formatted[: binding.typeahead_query_chars], + ): + return True + + if values_equivalent(intended_value, ctrl.current_value, binding.codec): + return True + + if ctrl.options: + matched_opts = [opt for opt in ctrl.options if opt.value == ctrl.current_value] + if len(matched_opts) == 1 and values_equivalent( + intended_value, matched_opts[0].label, binding.codec + ): + return True + + return False +# fmt: on + + +# vendored: c9cbaa155893:packages/flow/openadapt_flow/form_tx/reconciler.py 379-394 +# fmt: off +def _is_leading_part_of_choice(shown: str, label: str, typed: str) -> bool: + """True when a pick left the leading part of its label in the input. + + Some type-aheads put only the first part of the chosen suggestion in the + input ("2210 Juniper Loop" from "2210 Juniper Loop Apt 4, Brackenfield, + OR") and fill the rest into other fields. That counts only when the input + shows more than was typed, so text left over from typing never passes. + """ + shown_n = collapse_whitespace(shown).casefold() + label_n = collapse_whitespace(label).casefold() + typed_n = collapse_whitespace(typed).casefold() + if not shown_n or shown_n == typed_n or len(shown_n) <= len(typed_n): + return False + if not label_n.startswith(shown_n) or len(label_n) == len(shown_n): + return False + return label_n[len(shown_n)] in " ,;-/(" +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s7_cancel_post.py b/packages/flow/tests/failopen/selftest/_v_s7_cancel_post.py new file mode 100644 index 0000000000..077f985a4f --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s7_cancel_post.py @@ -0,0 +1,70 @@ +# vendored from 6d7e32b12990:packages/flow/openadapt_flow/connector/executor.py, lines 332-339, for the harness self-test only (re-indented) +# vendored from 6d7e32b12990:packages/flow/openadapt_flow/connector/executor.py, lines 885-909, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S7 post-fix: with no terminal report it halts for reconciliation (#2300 head). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Optional + + +# vendored: 6d7e32b12990:packages/flow/openadapt_flow/connector/executor.py 332-339 +# fmt: off +def _reported_terminal_outcome(report: dict[str, Any]) -> bool: + """True when the child's report records how its run ended.""" + return bool(report) and ( + report.get("execution_outcome") is not None + or report.get("terminal_outcome") is not None + or report.get("halt") is not None + or isinstance(report.get("success"), bool) + ) +# fmt: on + + +def child_status( + status: str, + report: dict[str, Any], + cancelled_flag: bool, + target_kind_ok: bool = True, +) -> str: + job = SimpleNamespace(lease_job_id="job", target_kind="kind") + report_target_kind = "kind" if target_kind_ok else "other" + + def job_cancelled(_job_id: str) -> bool: + return cancelled_flag + + error_code: Optional[str] = None + # vendored: 6d7e32b12990:packages/flow/openadapt_flow/connector/executor.py 885-909 + # fmt: off + cancelled = job_cancelled(job.lease_job_id) + if cancelled and not _reported_terminal_outcome(report): + # The cancel terminated a child that had already started, and it + # left no terminal report: a write may have landed. That is not a + # failure (a re-run could repeat the write); it stops for + # reconciliation, like a child whose outcome never came back. + status = "halt" + error_code = "child_outcome_unknown" + outcome_error = ( + "cancelled by the control plane while running; the governed " + "child left no terminal report, so a write may have landed" + ) + elif report_target_kind != job.target_kind: + status = "failed" + error_code = "target_kind_mismatch" + outcome_error = ( + "governed child report execution_target_kind does not match " + "the signed dispatch target_kind (fail closed)" + ) + else: + # A cancel that arrived after the child reported does not change + # what the child did: its own outcome stands. + outcome_error = None + if status == "failed": + error_code = "governed_run_failed" + # fmt: on + return status diff --git a/packages/flow/tests/failopen/selftest/_v_s7_cancel_pre.py b/packages/flow/tests/failopen/selftest/_v_s7_cancel_pre.py new file mode 100644 index 0000000000..b1c7f1b77b --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s7_cancel_pre.py @@ -0,0 +1,46 @@ +# vendored from fd71338669ee:packages/flow/openadapt_flow/connector/executor.py, lines 875-889, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S7 pre-fix: a cancel after the child started is reported as failed (#2300). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Optional + + +def child_status( + status: str, + report: dict[str, Any], + cancelled_flag: bool, + target_kind_ok: bool = True, +) -> str: + job = SimpleNamespace(lease_job_id="job", target_kind="kind") + report_target_kind = "kind" if target_kind_ok else "other" + + def job_cancelled(_job_id: str) -> bool: + return cancelled_flag + + error_code: Optional[str] = None + # vendored: fd71338669ee:packages/flow/openadapt_flow/connector/executor.py 875-889 + # fmt: off + if job_cancelled(job.lease_job_id): + status = "failed" + error_code = "cancelled_by_control_plane" + outcome_error = "cancelled by the control plane while running" + elif report_target_kind != job.target_kind: + status = "failed" + error_code = "target_kind_mismatch" + outcome_error = ( + "governed child report execution_target_kind does not match " + "the signed dispatch target_kind (fail closed)" + ) + else: + outcome_error = None + if status == "failed": + error_code = "governed_run_failed" + # fmt: on + return status diff --git a/packages/flow/tests/failopen/selftest/_v_s8_governed_post.py b/packages/flow/tests/failopen/selftest/_v_s8_governed_post.py new file mode 100644 index 0000000000..2a44f4a3c0 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s8_governed_post.py @@ -0,0 +1,255 @@ +# vendored from 00a55cc16312:scripts/ci/check_windows_governed_safety.py, lines 34-274, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S8 post-fix: governed rows are diffed against the seed (#2258). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + + +# vendored: 00a55cc16312:scripts/ci/check_windows_governed_safety.py 34-274 +# fmt: off +import json +import os +import sys +from pathlib import Path +from typing import Any + +PHASES = ("approved", "held", "resumed") +# Every column of a record row. Only the target's note may change, and only +# in a phase that may write; every other value must equal the seed exactly, +# so a note changed from '' to NULL is a write too. +COLUMNS = ("first", "last", "dob", "note") +WRITING_PHASES = ("approved", "resumed") + + +def _approved(phase: str, record: dict[str, Any], evidence: dict[str, Any]) -> bool: + if record.get("approval_decision") == "approved": + return True + # A resumed item's approval is the person's signed answer to the held + # request, which the test records on the held phase. + if phase == "resumed": + answers = (evidence.get("held") or {}).get("answer") or [] + return any(a.get("decision") == "approve" for a in answers) + return False + + +def _diff_from_seed( + phase: str, rows: list[Any], seed: list[Any], target: Any +) -> list[str]: + """The ways ``rows`` differ from ``seed``, other than the target's note in + a phase that may write it (its value is checked against the expected + note separately).""" + + problems: list[str] = [] + by_id = {r.get("id"): r for r in rows if isinstance(r, dict)} + seed_by_id = {r.get("id"): r for r in seed if isinstance(r, dict)} + missing = sorted(set(seed_by_id) - set(by_id), key=str) + added = sorted(set(by_id) - set(seed_by_id), key=str) + if missing: + problems.append(f"{phase}: seeded rows {missing} are gone") + if added: + problems.append(f"{phase}: rows {added} are not in the seed") + for row_id, row in by_id.items(): + seeded = seed_by_id.get(row_id) + if seeded is None: + continue + changed = [ + c + for c in COLUMNS + if row.get(c) != seeded.get(c) + and not (c == "note" and row_id == target and phase in WRITING_PHASES) + ] + if changed: + problems.append(f"{phase}: row {row_id} changed {changed}") + return problems + + +def check(evidence: Any) -> list[str]: + """Return the safety violations in ``evidence``; empty means safe.""" + + if not isinstance(evidence, dict): + return ["the evidence is not a JSON object"] + target = evidence.get("target_id") + expected = evidence.get("expected_note") + phases = evidence.get("phases") + if target is None or not expected or not isinstance(phases, list): + return ["the evidence names no target, expected note or phases"] + problems: list[str] = [] + seed = evidence.get("seed_rows") + if phases and (not isinstance(seed, list) or not seed): + problems.append("the evidence has no seed rows; cannot diff the full rows") + seed = None + for phase in phases: + if phase not in PHASES: + problems.append(f"unknown phase {phase!r}") + continue + record = evidence.get(phase) + rows = record.get("rows") if isinstance(record, dict) else None + if not isinstance(rows, list) or not rows: + problems.append(f"{phase}: no record rows; cannot confirm what was written") + continue + assert isinstance(record, dict) + if seed is not None: + problems.extend(_diff_from_seed(phase, rows, seed, target)) + seed_by_id = ( + {r.get("id"): r for r in seed if isinstance(r, dict)} + if isinstance(seed, list) + else {} + ) + target_row = next( + (r for r in rows if isinstance(r, dict) and r.get("id") == target), + None, + ) + target_seed = seed_by_id.get(target) + if target_row is not None: + if target_seed is not None: + target_note_changed = target_row.get("note") != target_seed.get("note") + else: + target_note_changed = bool(target_row.get("note")) + else: + target_note_changed = False + + written = [r for r in rows if isinstance(r, dict) and r.get("note")] + siblings = [r["id"] for r in written if r.get("id") != target] + if siblings: + problems.append(f"{phase}: non-target rows {siblings} have a note") + outcome = record.get("outcome") + if phase == "held": + if written or target_note_changed: + problems.append("held: the held run wrote") + if outcome == "VERIFIED": + problems.append("held: reported VERIFIED while held") + continue + if target_note_changed: + note = target_row.get("note") if target_row is not None else None + if note != expected: + problems.append(f"{phase}: the target holds an unexpected note") + if outcome != "VERIFIED": + problems.append( + f"{phase}: the target was written but the outcome is {outcome!r}" + ) + if not _approved(phase, record, evidence): + problems.append(f"{phase}: the target was written without an approval") + elif outcome == "VERIFIED": + problems.append(f"{phase}: reported VERIFIED but nothing was written") + return problems + + +def _halt_reason(record: dict[str, Any]) -> str | None: + halts = record.get("halts") + if isinstance(halts, list): + for halt in halts: + if isinstance(halt, dict) and (halt.get("category") or halt.get("error")): + return str(halt.get("category") or halt.get("error")) + return None + + +def coverage(evidence: Any) -> dict[str, Any]: + """What the governed run reached. Reported only, never gated on.""" + + phases = evidence.get("phases") if isinstance(evidence, dict) else None + if not isinstance(phases, list): + phases = [] + reached = [p for p in phases if p in PHASES] + outcomes: dict[str, Any] = {} + for phase in reached: + record = evidence.get(phase) + record = record if isinstance(record, dict) else {} + outcomes[phase] = { + "outcome": record.get("outcome"), + "halt": _halt_reason(record), + } + return { + "phases": reached, + "outcomes": outcomes, + "held_ran": "held" in reached, + "resumed_ran": "resumed" in reached, + } + + +def coverage_line(cov: dict[str, Any]) -> str: + """One line for the step summary, e.g. + ``approved: HALTED_BEFORE_EFFECT form_changed_after_approval``.""" + + if not cov["phases"]: + return "governed coverage: no phase ran" + parts = [] + for phase in PHASES: + if phase not in cov["outcomes"]: + parts.append(f"{phase}: not run") + continue + entry = cov["outcomes"][phase] + text = f"{phase}: {entry['outcome']}" + if entry["halt"]: + text += f" {entry['halt']}" + parts.append(text) + return "governed coverage: " + "; ".join(parts) + + +def _report_coverage(path: Path, evidence: Any) -> None: + cov = coverage(evidence) + line = coverage_line(cov) + print(line) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + try: + with open(summary, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + except OSError as exc: + print( + f"governed safety: cannot write the step summary: {exc}", + file=sys.stderr, + ) + if isinstance(evidence, dict): + evidence["coverage"] = cov + try: + path.write_text( + json.dumps(evidence, indent=2, default=str), encoding="utf-8" + ) + except OSError as exc: + print( + f"governed safety: cannot record coverage in {path}: {exc}", + file=sys.stderr, + ) + + +def main(argv: list[str]) -> int: + if len(argv) != 1: + print(__doc__, file=sys.stderr) + return 2 + path = Path(argv[0]) + try: + evidence = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + print(f"governed safety: cannot read {path}: {exc}", file=sys.stderr) + return 1 + _report_coverage(path, evidence) + problems = check(evidence) + for problem in problems: + print(f"governed safety: {problem}", file=sys.stderr) + if problems: + return 1 + if not evidence["phases"]: + print("governed safety: no phase ran") + return 0 + summary = { + p: { + "outcome": (evidence.get(p) or {}).get("outcome"), + "written": [ + r["id"] + for r in (evidence.get(p) or {}).get("rows", []) + if r.get("note") + ], + } + for p in evidence["phases"] + } + print(f"governed safety: no unsafe write ({json.dumps(summary)})") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_s9_verify_run_pre.py b/packages/flow/tests/failopen/selftest/_v_s9_verify_run_pre.py new file mode 100644 index 0000000000..1b7725bc15 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s9_verify_run_pre.py @@ -0,0 +1,61 @@ +# vendored from 576f87b41483:packages/flow/openadapt_flow/verify_run.py, lines 2958-2995, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S9: verify_run's folds before this change; latent behind min_length=1. + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from typing import Any, Literal, Optional, Sequence + +from openadapt_flow.runtime.effects.effect import Verdict + +EffectVerdict = Any +VerificationTier = Any +EffectVerdictLabel = Literal["CONFIRMED", "REFUTED", "INDETERMINATE"] +ReadbackClass = Literal["independent_readback", "screen_readback", "unchecked"] + + +# vendored: 576f87b41483:packages/flow/openadapt_flow/verify_run.py 2958-2995 +# fmt: off +def _aggregate(verdicts: Sequence[EffectVerdict]) -> EffectVerdictLabel: + if any(v.verdict is Verdict.INDETERMINATE for v in verdicts): + return "INDETERMINATE" + if any(v.verdict is Verdict.REFUTED for v in verdicts): + return "REFUTED" + return "CONFIRMED" + + +def _observed(verdicts: Sequence[EffectVerdict]) -> str: + seen = {v.observed_effect for v in verdicts} + if "unknown" in seen: + return "unknown" + if "conflicting" in seen or seen == {"absent", "present"}: + # A wrong record, or some effects landed and others did not. + return "conflicting" + return "absent" if "absent" in seen else "present" + + +def readback_class( + verdicts: Sequence[EffectVerdict], tiers: Sequence[Optional[VerificationTier]] +) -> ReadbackClass: + """RFC-0002 tier rule, weakest effect wins. + + ``unchecked`` when any effect was not read (no tier, store unreachable, + stale). ``independent_readback`` only when every effect was read from the + system of record without the UI (Flow tier 1). Anything else, including a + separate signed-in UI session (tier 2), is ``screen_readback``. + """ + + if ( + any(t is None for t in tiers) + or any(v.unavailable for v in verdicts) + or any(v.stale for v in verdicts) + ): + return "unchecked" + if all(t is not None and t.reads_system_of_record() for t in tiers): + return "independent_readback" + return "screen_readback" +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_wire_tap_post.py b/packages/flow/tests/failopen/selftest/_v_wire_tap_post.py new file mode 100644 index 0000000000..1f377c8212 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_wire_tap_post.py @@ -0,0 +1,91 @@ +# vendored from 769525ff1077:packages/flow/openadapt_flow/tx/wire_tap.py, lines 91-164, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""Wire tap post-fix: '///host' is rebuilt on the tap's origin or refused (#2470). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from typing import Optional +from urllib.parse import urljoin, urlsplit + + +# vendored: 769525ff1077:packages/flow/openadapt_flow/tx/wire_tap.py 91-164 +# fmt: off +def _normalize_origin(url_or_origin: str) -> str: + try: + parts = urlsplit(url_or_origin.strip()) + if not parts.scheme or not parts.netloc: + return "" + scheme = parts.scheme.lower() + host = (parts.hostname or "").lower() + port = parts.port + except ValueError: + # A malformed port or bracketed host is no origin at all. + return "" + if ":" in host: + # Keep IPv6 brackets so a port can never read as part of the address. + host = f"[{host}]" + if ( + port is None + or (scheme == "http" and port == 80) + or (scheme == "https" and port == 443) + ): + return f"{scheme}://{host}" + return f"{scheme}://{host}:{port}" + + +def relay_redirect_location( + location: str, + *, + request_url: str, + allowed_origins: frozenset[str], + rewrite_from_origin: Optional[str] = None, + rewrite_to_origin: Optional[str] = None, +) -> Optional[str]: + """Return the ``Location`` to relay for a same-origin redirect, else ``None``. + + Reverse-proxy mode only: the client's next request comes back through the + tap, so every hop is checked again. Browser route mode refuses redirects. + + The tap never follows a redirect itself. It hands a redirect back to the + client only when the target, resolved against the request URL, stays on an + allowed origin, so the next request passes through the tap again. A + protocol-relative or absolute target on any other origin is refused. + ``rewrite_from_origin``/``rewrite_to_origin`` map an absolute upstream + target onto the tap's own origin in reverse-proxy mode. + """ + raw = location or "" + # Validate the header exactly as received. Browsers drop tabs and newlines + # inside a URL and read a backslash as a slash, so refuse any space, + # control character or backslash rather than guess how a client reads it. + if not raw or any(ord(ch) <= 0x20 or ord(ch) == 0x7F or ch == "\\" for ch in raw): + return None + try: + resolved = urljoin(request_url, raw) + origin = _normalize_origin(resolved) + parts = urlsplit(raw) + except ValueError: + return None + if not origin or origin not in allowed_origins: + return None + # Only a plain path relays as written. Anything with a scheme or an + # authority, including ``///host`` that urlsplit reads as a path but a + # browser reads as a host, is relayed only as the URL checked here, + # rebuilt on the tap's own origin. + if not parts.scheme and not parts.netloc and not raw.startswith("//"): + return raw + if rewrite_from_origin is None or rewrite_to_origin is None: + return None + if origin != rewrite_from_origin: + return None + target = urlsplit(resolved) + rewritten = rewrite_to_origin.rstrip("/") + (target.path or "/") + if target.query: + rewritten += "?" + target.query + if target.fragment: + rewritten += "#" + target.fragment + return rewritten +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/specs.py b/packages/flow/tests/failopen/selftest/specs.py new file mode 100644 index 0000000000..49c913f34d --- /dev/null +++ b/packages/flow/tests/failopen/selftest/specs.py @@ -0,0 +1,473 @@ +"""Self-test: the harness flags each historical bug and passes its fix. + +Each pair runs one spec, written against the bug class, on the vendored +pre-fix code (``_v_*_pre.py``, it must be flagged) and on the post-fix code +(``_v_*_post.py``, or main itself; it must not be). The vendored files carry +their commit and line range in their first lines. ``PAIRS`` maps a bug to +``(pre spec id, post spec id or None, the mutators expected to catch it)``. +""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Callable, Optional + +from tests.failopen.harness import ( + CodeCase, + CorpusCase, + Knob, + Seed, + SiteSpec, + key, + register, +) +from tests.failopen.mutators import load_corpus +from tests.failopen.selftest import ( + _v_s1_receipt_post, + _v_s1_receipt_pre, + _v_s2_audit_post, + _v_s2_audit_pre, + _v_s3_undo_post, + _v_s3_undo_pre, + _v_s4_form_judge_post, + _v_s4_form_judge_pre, + _v_s5_gate_head, + _v_s5_gate_pre, + _v_s6_typeahead_post, + _v_s6_typeahead_pre, + _v_s7_cancel_post, + _v_s7_cancel_pre, + _v_s8_governed_post, + _v_s9_verify_run_pre, + _v_wire_tap_post, +) +from tests.failopen.sites import governed_safety, verify_run_folds, wire_tap_relay + +PAIRS: dict[str, tuple[str, Optional[str], frozenset[str]]] = {} + + +def pair( + name: str, + make: Callable[[Any, str], SiteSpec], + pre: Any, + post: Any, + catches: set[str], + post_id: Optional[str] = None, +) -> None: + pre_id = f"selftest.{name}.pre" + register(make(pre, pre_id)) + if post is not None: + post_id = f"selftest.{name}.post" + register(make(post, post_id)) + PAIRS[name] = (pre_id, post_id, frozenset(catches)) + + +# -- S1 receipt tally (#2394, fixed by adef5a431) ---------------------------------- + + +def receipt_spec(mod: Any, id: str) -> SiteSpec: + ok, bad = {"effect_verified": True}, {"effect_verified": False} + return SiteSpec( + id=id, + classes="C1", + target="openadapt_flow.receipt_record:build_statement", + kind="selftest", + run=lambda ev: mod.outcome_of(ev), + is_pass=lambda out: out == "VERIFIED", + seeds=lambda: [ + Seed({"execution_outcome": "VERIFIED", "results": [ok, ok]}, True), + Seed({"execution_outcome": "VERIFIED", "results": [ok, bad]}, False), + ], + items=key("results"), + bad_item=lambda _r: dict(bad), + inflate=lambda ev, n: {**ev, "results": [ok] * (n - 1) + [bad]}, + limit=256, + vacuous="a run with no writes keeps its own outcome; the receipt never upgrades it", + ) + + +pair("S1_receipt_tally", receipt_spec, _v_s1_receipt_pre, _v_s1_receipt_post, {"M2"}) + + +# -- S2 audit read stops early (#2437, fixed by de5ee3db2) ------------------------- + + +def audit_spec(reader: Any, id: str) -> SiteSpec: + def run(ev: dict[str, Any]) -> Any: + log = [SimpleNamespace(**e) for e in ev["events"]] + log.append(SimpleNamespace(id="c1", at=100, actor="me")) + cursor = SimpleNamespace(ids={"c1"}, at=100) + return reader(log, ev["page_size"]).after(cursor) + + own = {"id": "own1", "at": 110, "actor": "me"} + stale = {"id": "s1", "at": 50, "actor": "me"} # another node's clock + return SiteSpec( + id=id, + classes="C1", + target="openadapt_flow.txplan.audit:AuditReader.after", + kind="selftest", + run=run, + is_pass=lambda w: len(w.events) == 1 and w.other_actors == 0, + seeds=lambda: [ + Seed({"events": [own, stale], "page_size": 2}, True), + Seed({"events": [own, {**own, "id": "own2"}], "page_size": 2}, False), + ], + items=key("events"), + bad_item=lambda e: {**e, "id": e["id"] + "-dup"}, + inflate=lambda ev, n: { + **ev, + "events": [own, stale] + + [{"id": f"x{i}", "at": 105, "actor": "other"} for i in range(n - 2)], + }, + ) + + +pair( + "S2_audit_short_read", + audit_spec, + _v_s2_audit_pre.PreReader, + _v_s2_audit_post.PostReader, + {"M2", "M7"}, +) + + +# -- S3 undo counted as rolled back (#2428, fixed by fda539c78) -------------------- + +UNDO_CODES = ( + "no_undo", + "undo_refuted", + "frame_differs", + "changed_since_apply", + "undo_failed", + "unresolved", +) + + +def undo_spec(mod: Any, id: str) -> SiteSpec: + def ev(*codes: str) -> dict[str, Any]: + return {"per_write": {f"w{i}": c for i, c in enumerate(codes)}, "leftover": []} + + return SiteSpec( + id=id, + classes="C3", + target="openadapt_flow.txplan.engine:undo_plan", + kind="selftest", + run=lambda e: mod.undo_outcome( + dict(e["per_write"]), list(e["leftover"]), {}, [], {} + ), + is_pass=lambda out: out == "ROLLED_BACK", + seeds=lambda: [ + Seed(ev("undone", "undone"), True), + Seed(ev("undone", "undo_refuted"), False), + ], + codes=lambda: [ + CodeCase( + ev(*prefix, code), + True, + lambda _o: False, + f"{code} after {prefix}", + unknown=True, + ) + for code in UNDO_CODES + for prefix in ((), ("undone",)) + ], + notes={ + "codes": "every per-write code undo_plan emits that is not 'undone'; the " + "neutral ones (cancelled, already_undone, not_this_plan, " + "irreversible_released) are left out" + }, + ) + + +pair("S3_undo_no_undo", undo_spec, _v_s3_undo_pre, _v_s3_undo_post, {"M14"}) + + +# -- S4 written field with no verdict (#2429, fixed by fa26f69fc) ------------------ + + +def form_judge_spec(mod: Any, id: str) -> SiteSpec: + def run(ev: dict[str, Any]) -> Any: + return mod.judge(ev["bindings"], dict(ev["facts"]), ev["screen"], ev["written"]) + + good = { + "bindings": [{"key": "name"}, {"key": "middle"}], + "facts": [["name", "Ada"], ["middle", ""]], + "screen": {"name": "Ada", "middle": ""}, + "written": ["name", "middle"], + } + return SiteSpec( + id=id, + classes="C1", + target="openadapt_flow.form_tx.judge:SummaryJudge.evaluate", + kind="selftest", + run=run, + is_pass=lambda out: out is True, + seeds=lambda: [ + Seed(good, True), + Seed({**good, "screen": {"name": "Ada", "middle": "Q"}}, False), + ], + items=key("facts"), + plan=key("written"), + bad_item=lambda f: [f[0], "Zed"], + ) + + +pair( + "S4_form_written_no_fact", + form_judge_spec, + _v_s4_form_judge_pre, + _v_s4_form_judge_post, + {"M1"}, +) + + +# -- S5 agent-test gate (#2419) ----------------------------------------------------- + +RATES = ( + "silent_corruption", + "false_success", + "completed_correctly", + "safe_stop", + "collateral_edit", +) + + +def _summary(scored: int) -> dict[str, Any]: + rates = {k: {"count": 0, "of": scored, "rate": 0.0} for k in RATES} + return {"scored": scored, "rates": rates} + + +def _meta(repetitions: int) -> dict[str, Any]: + return { + "app": "app", + "app_pack": {"digest": "a"}, + "scenarios": {"digest": "s"}, + "images": ["img"], + "agent": "agent", + "repetitions": repetitions, + } + + +def _gate_ev(scored: int) -> dict[str, Any]: + base = { + "schema": "openadapt.agent-test.baseline/v1", + "app": "app", + "app_pack_digest": "a", + "scenarios_digest": "s", + "images": ["img"], + "agent": "agent", + "repetitions": 10, + "scored": 10, + "rates": _summary(10)["rates"], + } + return { + "results": {"meta": _meta(10), "summary": _summary(scored)}, + "baseline": base, + } + + +def gate_spec(mod: Any, id: str) -> SiteSpec: + def call(ev: dict[str, Any], min_scored: Any = None) -> Any: + with tempfile.TemporaryDirectory() as tmp: + results, base = Path(tmp, "results.json"), Path(tmp, "baseline.json") + results.write_text(json.dumps(ev["results"])) + base.write_text(json.dumps(ev["baseline"])) + kwargs = {} if min_scored is None else {"min_scored": min_scored} + return mod.compare(results, base, **kwargs) + + return SiteSpec( + id=id, + classes="C4", + target="openadapt_flow.agent_test.gate:compare", + kind="selftest", + run=call, + is_pass=lambda out: out["verdict"] == "pass", + seeds=lambda: [Seed(_gate_ev(10), True)], + # Twenty runs were planned (two scenarios, ten repetitions). + knob=Knob("min_scored", None, (20,), call), + relabel=lambda ev: _gate_ev(9), + ) + + +pair("S5_gate_min_scored", gate_spec, _v_s5_gate_pre, None, {"M9"}) +pair("S5_gate_head", gate_spec, _v_s5_gate_head, None, {"M9"}) + + +# -- S6 type-ahead leading part (#2448, fixed by c329c57dc) ------------------------ + +ADDRESS = "2210 Juniper Loop Apt 4, Brackenfield, OR" + + +def typeahead_spec(mod: Any, id: str, typed_kw: bool) -> SiteSpec: + def run(ev: dict[str, Any]) -> Any: + ctrl = SimpleNamespace(checked=None, current_value=ev["shown"], options=[]) + binding = SimpleNamespace( + control_kind=mod.ControlKind.PORTAL_COMBOBOX, + typeahead_query_chars=4, + codec=None, + ) + kwargs = {"typed_query": ev["typed"]} if typed_kw else {} + return mod._control_matches_fact(ctrl, ev["intended"], binding, **kwargs) + + def near_misses() -> list[Any]: + rows = load_corpus("values")["near_misses"] + return [r for r in rows if isinstance(r["observed"], str) and r["expected"]] + + return SiteSpec( + id=id, + classes="C5", + target="openadapt_flow.form_tx.reconciler:_control_matches_fact", + kind="selftest", + run=run, + is_pass=lambda out: out is True, + seeds=lambda: [ + Seed({"shown": ADDRESS, "intended": ADDRESS, "typed": None}, True), + Seed( + {"shown": "2210 Juniper Loop", "intended": ADDRESS, "typed": "2210"}, + True, + ), + Seed( + {"shown": "2210 Juniper Loop", "intended": ADDRESS, "typed": None}, + False, + "prefilled", + ), + ], + corpus=CorpusCase( + "value", + apply=lambda ev, r: { + **ev, + "shown": r["observed"], + "intended": r["expected"], + "typed": None, + }, + ), + corpus_entries=near_misses, + ) + + +pair( + "S6_typeahead_prefix", + lambda m, i: typeahead_spec(m, i, m is _v_s6_typeahead_post), + _v_s6_typeahead_pre, + _v_s6_typeahead_post, + {"seed", "M11"}, +) + + +# -- S7 cancel after the child started (#2300) -------------------------------------- + + +def cancel_spec(mod: Any, id: str) -> SiteSpec: + def ev(status: str, report: dict[str, Any], cancelled: bool) -> dict[str, Any]: + return {"status": status, "report": report, "cancelled": cancelled} + + return SiteSpec( + id=id, + classes="C7", + target="openadapt_flow.connector.executor:FlowExecutor.execute", + kind="selftest", + run=lambda e: mod.child_status(e["status"], e["report"], e["cancelled"]), + is_pass=lambda out: out == "success", + seeds=lambda: [ + Seed( + ev( + "success", {"execution_outcome": "VERIFIED", "success": True}, False + ), + True, + ) + ], + codes=lambda: [ + CodeCase( + ev("failed", {}, True), + True, + lambda o: o == "failed", + "cancel, no report", + ), + CodeCase( + ev("halt", {"execution_outcome": "HALTED"}, True), + True, + lambda o: o == "failed", + "cancel after a HALTED report", + ), + ], + ) + + +pair("S7_cancel_after_start", cancel_spec, _v_s7_cancel_pre, _v_s7_cancel_post, {"M12"}) + + +# -- S8 governed '' vs NULL (#2258, fixed by 00a55cc16) ----------------------------- + + +def _governed(check: Any, id: str) -> SiteSpec: + spec = governed_safety.governed_spec(check, id, "selftest") + return spec + + +pair( + "S8_governed_note", + _governed, + governed_safety.load_check( + governed_safety.ROOT / "scripts/ci/check_windows_governed_safety.py" + ), + _v_s8_governed_post.check, + {"seed", "M10"}, +) + + +# -- wire tap '///host' (#2470) ------------------------------------------------------ + + +def _relay(fn: Any, id: str) -> SiteSpec: + return wire_tap_relay.relay_spec(fn, id, "selftest") + + +def _main_relay() -> Any: + from openadapt_flow.tx.wire_tap import relay_redirect_location + + return relay_redirect_location + + +pair( + "wire_tap_triple_slash", + _relay, + _main_relay(), + _v_wire_tap_post.relay_redirect_location, + {"M11"}, +) + + +# -- S9 verify_run folds before this change (latent C2) ----------------------------- + +from openadapt_flow import verify_run # noqa: E402 + +for _name, _factory, _pre, _post in ( + ( + "S9_aggregate_empty", + verify_run_folds.aggregate_spec, + _v_s9_verify_run_pre._aggregate, + verify_run._aggregate, + ), + ( + "S9_observed_empty", + verify_run_folds.observed_spec, + _v_s9_verify_run_pre._observed, + verify_run._observed, + ), + ( + "S9_readback_class_empty", + verify_run_folds.readback_spec, + _v_s9_verify_run_pre.readback_class, + verify_run.readback_class, + ), +): + pair( + _name, + lambda fn, i, f=_factory: f(fn, i, "selftest"), + _pre, + _post, + {"M3"} if _name != "S9_readback_class_empty" else {"M1", "M3"}, + ) diff --git a/packages/flow/tests/failopen/sites/__init__.py b/packages/flow/tests/failopen/sites/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/tests/failopen/sites/_vocab.py b/packages/flow/tests/failopen/sites/_vocab.py new file mode 100644 index 0000000000..603946f7ee --- /dev/null +++ b/packages/flow/tests/failopen/sites/_vocab.py @@ -0,0 +1,27 @@ +"""The outcome vocabulary (openadapt_types/vocabulary/outcomes.json) as P7 cases.""" + +from __future__ import annotations + +import json +from functools import lru_cache +from importlib import resources +from typing import Any + + +@lru_cache(maxsize=1) +def outcomes() -> dict[str, Any]: + text = ( + resources.files("openadapt_types") + .joinpath("vocabulary/outcomes.json") + .read_text(encoding="utf-8") + ) + return json.loads(text) + + +def rows(source: str) -> dict[str, dict[str, Any]]: + return outcomes()["sources"][source]["values"] + + +def result_of(source: str, value: Any) -> Any: + row = rows(source).get(value) + return row["result"] if row else None diff --git a/packages/flow/tests/failopen/sites/connector_status.py b/packages/flow/tests/failopen/sites/connector_status.py new file mode 100644 index 0000000000..0a993a8e15 --- /dev/null +++ b/packages/flow/tests/failopen/sites/connector_status.py @@ -0,0 +1,88 @@ +"""connector.status_from_report (C7): a report that says "check the record" +must not reach the control plane as a plain failure. + +The cases come from the vocabulary, not from this file: every +``transaction_outcome`` row, with each ``execution_outcome`` the row allows, +at exit codes 0 and 1. When the precise outcome's plain result is +``check_the_record``, the connector status must map to that result too. +On main a report with ``transaction_outcome: RECONCILIATION_REQUIRED`` and +``execution_outcome: FAILED`` maps to ``failed`` ("Didn't finish"): the +precise outcome is never read. Owned by the connector status work +(FAIL_CLOSED.md follow-up 3, the class of #2300). +""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.connector.executor import status_from_report +from tests.failopen.harness import CodeCase, Seed, SiteSpec, register +from tests.failopen.sites._vocab import result_of, rows + + +def _cases() -> list[CodeCase]: + out = [] + for tx, row in rows("transaction_outcome").items(): + for eo in row.get("execution_outcomes", []): + for rc in (0, 1): + must = row["result"] + out.append( + CodeCase( + evidence={ + "rc": rc, + "report": { + "execution_outcome": eo, + "transaction_outcome": tx, + "success": rc == 0 and tx == "VERIFIED", + }, + }, + may_have_changed=bool(row["may_have_changed"]), + forbidden=lambda status, must=must: ( + must == "check_the_record" + and result_of("connector_status", status) != must + ), + label=f"{tx}/{eo} rc={rc}", + ) + ) + out.append( + CodeCase( + evidence={ + "rc": 0, + "report": {"execution_outcome": "NOT_A_CODE", "success": True}, + }, + may_have_changed=True, + forbidden=lambda status: False, + label="unknown execution_outcome", + unknown=True, + ) + ) + return out + + +def _run(ev: dict[str, Any]) -> Any: + return status_from_report(ev["rc"], ev["report"]) + + +register( + SiteSpec( + id="connector.status_from_report", + classes="C7", + target="openadapt_flow.connector.executor:status_from_report", + kind="owned", + run=_run, + is_pass=lambda out: out == "success", + seeds=lambda: [ + Seed( + {"rc": 0, "report": {"execution_outcome": "VERIFIED", "success": True}}, + True, + ), + Seed({"rc": 1, "report": {"execution_outcome": "FAILED"}}, False), + ], + codes=_cases, + ), + xfail=( + "a report whose transaction_outcome says check the record maps to " + "'failed'; needs the connector status from the vocabulary " + "(FAIL_CLOSED.md follow-up 3, class of #2300)" + ), +) diff --git a/packages/flow/tests/failopen/sites/governed_safety.py b/packages/flow/tests/failopen/sites/governed_safety.py new file mode 100644 index 0000000000..299c51cf9a --- /dev/null +++ b/packages/flow/tests/failopen/sites/governed_safety.py @@ -0,0 +1,87 @@ +"""scripts/ci/check_windows_governed_safety.check (C5): '' and NULL are +different values. + +On main a held phase whose target note went from NULL to '' (or back) reports +no problem: ``written`` keeps rows whose note is truthy, so a write of '' is +no write. Fixed on #2258 by diffing every row against the seed; the post-fix +copy is ``selftest/s8_governed_note.py``. +""" + +from __future__ import annotations + +import copy +import importlib.util +from pathlib import Path +from typing import Any, Callable + +from tests.failopen.harness import Seed, SiteSpec, key, register + +ROOT = Path(__file__).resolve().parents[5] + + +def _rows(note1: Any, note2: Any = None) -> list[dict[str, Any]]: + return [ + {"id": 1, "first": "Ada", "last": "Ray", "dob": "1990-01-01", "note": note1}, + {"id": 2, "first": "Bo", "last": "Lee", "dob": "1991-02-02", "note": note2}, + ] + + +def _held(seed_note: Any, held_note: Any) -> dict[str, Any]: + return { + "target_id": 1, + "expected_note": "follow up", + "phases": ["held"], + "seed_rows": _rows(seed_note), + "held": {"rows": _rows(held_note), "outcome": "HALTED_BEFORE_EFFECT"}, + } + + +def _approved() -> dict[str, Any]: + return { + "target_id": 1, + "expected_note": "follow up", + "phases": ["approved"], + "seed_rows": _rows(None), + "approved": { + "rows": _rows("follow up"), + "outcome": "VERIFIED", + "approval_decision": "approved", + }, + } + + +def governed_spec(check: Callable[[Any], list[str]], id: str, kind: str) -> SiteSpec: + return SiteSpec( + id=id, + classes="C5", + target="scripts/ci/check_windows_governed_safety.py:check", + kind=kind, + run=lambda ev: check(copy.deepcopy(ev)), + is_pass=lambda out: out == [], + seeds=lambda: [ + Seed(_held(None, None), True, "held, untouched"), + Seed(_approved(), True, "approved write of the expected note"), + Seed(_held("", None), False, "held, '' became NULL"), + ], + values=(key("note", "held", "rows", 0), key("note", "approved", "rows", 0)), + equivalent=frozenset({"absent"}), + notes={"absent": "rows are full-row dumps; a missing column reads as NULL"}, + ) + + +def load_check(path: Path) -> Callable[[Any], list[str]]: + spec = importlib.util.spec_from_file_location(f"_vendored_{path.stem}", path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.check # type: ignore[no-any-return] + + +register( + governed_spec( + load_check(ROOT / "scripts/ci/check_windows_governed_safety.py"), + "governed_safety.check", + "owned", + ), + xfail="#2258: a held target note changed between '' and NULL reads as no write", +) diff --git a/packages/flow/tests/failopen/sites/hard_invariants.py b/packages/flow/tests/failopen/sites/hard_invariants.py new file mode 100644 index 0000000000..b941ab438c --- /dev/null +++ b/packages/flow/tests/failopen/sites/hard_invariants.py @@ -0,0 +1,50 @@ +"""hard_invariants.judge: a positive control. The fold is correct on main; +the harness must not flag it (kill criterion 2).""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.hard_invariants import judge_hard_invariants +from tests.failopen.harness import Seed, SiteSpec, key, register + +GOOD: dict[str, Any] = { + "outside_scope_changes": 0, + "undeclared_deletes": 0, + "before_matches": 0, + "after_matches": 1, + "history_matches": 1, + "scope_complete": True, + "deletes_complete": True, + "history_complete": True, + "search_complete": True, +} + + +def _fields() -> Any: + from tests.failopen.harness import Lens + + def put(ev: dict[str, Any], value: dict[str, Any]) -> None: + ev.clear() + ev.update(value) + + return Lens(lambda ev: ev, put) + + +register( + SiteSpec( + id="hard_invariants.judge", + classes="C2 C5", + target="openadapt_flow.hard_invariants:judge_hard_invariants", + run=lambda ev: judge_hard_invariants(**ev), + is_pass=lambda out: out.status == "held", + seeds=lambda: [ + Seed(dict(GOOD), True), + Seed({**GOOD, "outside_scope_changes": 2}, False), + Seed({**GOOD, "history_matches": 2, "after_matches": 2}, False), + Seed({**GOOD, "history_complete": False}, False), + ], + fields=_fields(), + values=tuple(key(name) for name in GOOD), + ) +) diff --git a/packages/flow/tests/failopen/sites/verify_run_folds.py b/packages/flow/tests/failopen/sites/verify_run_folds.py new file mode 100644 index 0000000000..6581fbdd9d --- /dev/null +++ b/packages/flow/tests/failopen/sites/verify_run_folds.py @@ -0,0 +1,109 @@ +"""verify_run's three folds over per-effect verdicts (C2: an empty set). + +Each factory takes the fold, so the self-test runs the same spec on the +pre-migration copies vendored from main (``selftest/s9_verify_run_folds.py``). +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Callable + +from openadapt_flow import verify_run +from openadapt_flow.runtime.effects.effect import Verdict +from tests.failopen.harness import Seed, SiteSpec, key, register, root_list + +C, R, I = "confirmed", "refuted", "indeterminate" + + +def _verdicts(codes: list[str]) -> list[Any]: + return [SimpleNamespace(verdict=Verdict(c)) for c in codes] + + +def aggregate_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSpec: + return SiteSpec( + id=id, + classes="C2 C3", + target="openadapt_flow.verify_run:_aggregate", + kind=kind, + run=lambda ev: fn(_verdicts(ev)), + is_pass=lambda out: out == "CONFIRMED", + seeds=lambda: [ + Seed([C], True), + Seed([C, C, C], True), + Seed([C, R], False), + Seed([C, I], False), + Seed([R, I], False), + ], + items=root_list(), + bad_item=lambda _c: R, + inflate=lambda _ev, n: [C] * (n - 1) + [R], + ) + + +def _observed(codes: list[str]) -> list[Any]: + return [SimpleNamespace(observed_effect=c) for c in codes] + + +def observed_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSpec: + return SiteSpec( + id=id, + classes="C2", + target="openadapt_flow.verify_run:_observed", + kind=kind, + run=lambda ev: fn(_observed(ev)), + is_pass=lambda out: out == "present", + seeds=lambda: [ + Seed(["present"], True), + Seed(["present", "present"], True), + Seed(["present", "absent"], False), + Seed(["unknown"], False), + ], + items=root_list(), + bad_item=lambda _c: "absent", + inflate=lambda _ev, n: ["present"] * (n - 1) + ["unknown"], + ) + + +class _Tier: + def __init__(self, sor: bool) -> None: + self.sor = sor + + def reads_system_of_record(self) -> bool: + return self.sor + + +def _readback(fn: Callable[..., Any], ev: dict[str, Any]) -> Any: + verdicts = [SimpleNamespace(unavailable=False, stale=False) for _ in ev["effects"]] + tiers = [None if t is None else _Tier(t == "sor") for t in ev["tiers"]] + return fn(verdicts, tiers) + + +def readback_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSpec: + return SiteSpec( + id=id, + classes="C1 C2", + target="openadapt_flow.verify_run:readback_class", + kind=kind, + run=lambda ev: _readback(fn, ev), + is_pass=lambda out: out == "independent_readback", + seeds=lambda: [ + Seed({"effects": ["e1"], "tiers": ["sor"]}, True), + Seed({"effects": ["e1", "e2"], "tiers": ["sor", "sor"]}, True), + Seed({"effects": ["e1", "e2"], "tiers": ["sor", "ui"]}, False), + Seed({"effects": ["e1"], "tiers": [None]}, False), + ], + # One tier per effect: the effects are the plan, the tiers the results. + items=key("tiers"), + plan=key("effects"), + bad_item=lambda _t: None, + inflate=lambda _ev, n: { + "effects": [f"e{i}" for i in range(n)], + "tiers": ["sor"] * (n - 1) + ["ui"], + }, + ) + + +register(aggregate_spec(verify_run._aggregate, "verify_run.aggregate")) +register(observed_spec(verify_run._observed, "verify_run.observed")) +register(readback_spec(verify_run.readback_class, "verify_run.readback_class")) diff --git a/packages/flow/tests/failopen/sites/versions_judge.py b/packages/flow/tests/failopen/sites/versions_judge.py new file mode 100644 index 0000000000..5e1c96502d --- /dev/null +++ b/packages/flow/tests/failopen/sites/versions_judge.py @@ -0,0 +1,67 @@ +"""versions.judge: a positive control (correct on main).""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.runtime.effects.versions import ( + FrameVersions, + judge_versions, + seal_versions, +) +from tests.failopen.harness import Seed, SiteSpec, key, register + +KEY = b"k" * 32 +SPEC = FrameVersions(read={}, record_field="rid", version_field="v") + + +def _run(ev: dict[str, Any]) -> Any: + stored = seal_versions(SPEC, ev["before"], KEY) + targets = [tuple(t) for t in ev["targets"]] + return judge_versions(SPEC, stored, ev["after"], targets, KEY) + + +def _good() -> dict[str, Any]: + return { + "before": [{"rid": "r1", "v": "1"}], + "after": [{"rid": "r1", "v": "1"}, {"rid": "r1", "v": "2"}], + "targets": [["r1", True, True]], + } + + +def _raise(ev: dict[str, Any], exc: BaseException) -> dict[str, Any]: + # The after-read failed: the caller passes None, as verify_run does. + return {**ev, "after": None} + + +register( + SiteSpec( + id="versions.judge", + classes="C1 C5", + target="openadapt_flow.runtime.effects.versions:judge_versions", + run=_run, + is_pass=lambda out: out.status == "held", + seeds=lambda: [ + Seed(_good(), True), + Seed( + { + **_good(), + "after": [{"rid": "r1", "v": "1"}, {"rid": "r1", "v": "3"}], + }, + False, + ), + Seed({**_good(), "after": [{"rid": "r1", "v": "1"}]}, False), + ], + items=key("after"), + plan=key("targets"), + vacuous=( + "no target existed before the write (all creates), so no earlier " + "version can be overwritten" + ), + bad_item=lambda row: {**row, "v": "9"}, + probe_raise=_raise, + values=(key("v", "after", 1),), + equivalent=frozenset({"number for string"}), + notes={"number for string": "a version id 2 and '2' name the same version"}, + ) +) diff --git a/packages/flow/tests/failopen/sites/wire_tap_relay.py b/packages/flow/tests/failopen/sites/wire_tap_relay.py new file mode 100644 index 0000000000..f8f0abeb90 --- /dev/null +++ b/packages/flow/tests/failopen/sites/wire_tap_relay.py @@ -0,0 +1,61 @@ +"""tx.wire_tap.relay_redirect_location (C6): a relayed Location must keep a +browser on an allowed origin. + +The corpus (corpus/urls.json) is read the way a browser reads it +(:func:`browser_origin`), not the way ``urlsplit`` does: on main +``///evil.example/x`` is relayed as written, and a browser goes to +``evil.example``. Fixed on #2470; the post-fix copy is in +``selftest/s10_wire_tap_relay.py``. +""" + +from __future__ import annotations + +from typing import Any, Callable + +from tests.failopen.harness import CorpusCase, Seed, SiteSpec, browser_origin, register +from tests.failopen.mutators import load_corpus + +BASE = "http://app.test/a/page" +ALLOWED = frozenset({"http://app.test"}) + + +def _entries() -> list[Any]: + urls = load_corpus("urls") + return list(urls["hostile"]) + list(urls["chain"]) + + +def _bad(ev: dict[str, Any], entry: Any, out: Any) -> bool: + return out is not None and browser_origin(BASE, out) not in ALLOWED + + +def relay_spec(fn: Callable[..., Any], id: str, kind: str) -> SiteSpec: + return SiteSpec( + id=id, + classes="C6", + target="openadapt_flow.tx.wire_tap:relay_redirect_location", + kind=kind, + run=lambda ev: fn(ev["location"], request_url=BASE, allowed_origins=ALLOWED), + is_pass=lambda out: out is not None, + seeds=lambda: [ + Seed({"location": "/a/b"}, True), + Seed({"location": "https://evil.example/"}, False), + ], + corpus=CorpusCase( + "url", apply=lambda ev, entry: {**ev, "location": entry}, bad=_bad + ), + corpus_entries=_entries, + ) + + +def _main() -> None: + from openadapt_flow.tx.wire_tap import relay_redirect_location + + register( + relay_spec( + relay_redirect_location, "wire_tap.relay_redirect_location", "owned" + ), + xfail="#2470: '///host' is relayed raw and a browser reads it as a host", + ) + + +_main() diff --git a/packages/flow/tests/failopen/test_kernel.py b/packages/flow/tests/failopen/test_kernel.py new file mode 100644 index 0000000000..9597aa2163 --- /dev/null +++ b/packages/flow/tests/failopen/test_kernel.py @@ -0,0 +1,252 @@ +"""Properties of openadapt_flow.verdict, the one fold.""" + +from __future__ import annotations + +from fractions import Fraction + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from openadapt_flow.verdict import ( + Errored, + FailClosed, + Missing, + Obligations, + Observed, + Result, + Status, + Subject, + TrustSource, + binding_mismatches, + from_code, + observe, + require_bound, + settle, + trust_label, +) + +PROFILE = settings(derandomize=True, max_examples=150, deadline=None) +CODES = st.sampled_from([s.value for s in Status]) + + +def _subjects(n: int) -> list[Subject]: + return [Subject(system="s", table="t", key=str(i), field="f") for i in range(n)] + + +def _result(subject: Subject, status: str) -> Result: + if status == "held": + return Result.held(subject, Observed(1)) + if status == "refuted": + return Result.refuted(subject, Observed(0), "no") + return Result.not_checked(subject, "no read") + + +@st.composite +def cases(draw: st.DrawFn) -> tuple[Obligations, list[Result]]: + n = draw(st.integers(0, 8)) + subjects = _subjects(n) + statuses = draw(st.lists(CODES, min_size=n, max_size=n)) + keep = draw(st.lists(st.booleans(), min_size=n, max_size=n)) + results = [_result(s, c) for s, c, k in zip(subjects, statuses, keep) if k] + return Obligations.fix(subjects, source="plan"), results + + +def test_an_empty_set_never_passes() -> None: + settled = settle(Obligations.fix([], source="plan"), []) + assert not settled.passes + assert settled.label(precedence=(Status.REFUTED,)) is Status.NOT_CHECKED + assert settled.rate(Status.HELD) is None + + +@PROFILE +@given(cases(), st.randoms(use_true_random=False)) +def test_order_does_not_matter( + case: tuple[Obligations, list[Result]], rnd: object +) -> None: + obligations, results = case + shuffled = list(results) + rnd.shuffle(shuffled) # type: ignore[attr-defined] + assert settle(obligations, results) == settle(obligations, shuffled) + + +@PROFILE +@given(cases(), CODES.filter(lambda c: c != "held")) +def test_a_non_held_result_never_makes_a_fail_pass( + case: tuple[Obligations, list[Result]], code: str +) -> None: + obligations, results = case + before = settle(obligations, results).passes + for subject in [*obligations.items, Subject(key="stranger")]: + after = settle(obligations, [*results, _result(subject, code)]).passes + assert after <= before + + +@PROFILE +@given(cases()) +def test_passes_only_when_every_obligation_held( + case: tuple[Obligations, list[Result]], +) -> None: + obligations, results = case + settled = settle(obligations, results) + held = {r.subject.key_tuple() for r in results if r.status is Status.HELD} + every = obligations.items and all(o.key_tuple() in held for o in obligations.items) + assert settled.passes == (bool(every) and len(results) == len(obligations.items)) + buckets = ( + settled.held, + settled.refuted, + settled.not_checked, + settled.missing, + settled.mismatched, + settled.conflicting, + ) + assert sum(len(b) for b in buckets) == settled.total + + +@PROFILE +@given(st.integers(1, 40), st.integers(0, 39)) +def test_nothing_is_truncated_at_the_limit(n: int, limit: int) -> None: + subjects = _subjects(n) + results = [_result(s, "held") for s in subjects[:-1]] + [ + _result(subjects[-1], "refuted") + ] + settled = settle(Obligations.fix(subjects, source="plan"), results, limit=limit) + assert not settled.passes + assert len(settled.refuted) == 1 + assert settled.over_limit == (n > limit) + + +def test_a_result_for_another_run_is_mismatched() -> None: + planned = Subject(run_id="run-1", nonce="n1", key="k") + other = Subject(run_id="run-2", nonce="n1", key="k") + settled = settle( + Obligations.fix([planned], source="plan"), [_result(other, "held")] + ) + assert settled.mismatched == (planned,) and not settled.passes + assert binding_mismatches(planned, other) == ("run_id",) + assert binding_mismatches(planned, Subject(key="k")) == ("run_id", "nonce") + with pytest.raises(FailClosed): + require_bound(planned, other) + require_bound(planned, planned.bound(digest="d")) + + +def test_a_decoy_table_is_a_different_subject() -> None: + real = Subject(system="db", table="orders", key="7", field="total") + decoy = Subject(system="db", table="orders_copy", key="7", field="total") + settled = settle(Obligations.fix([real], source="plan"), [_result(decoy, "held")]) + assert settled.missing == (real,) and len(settled.unexpected) == 1 + + +def test_disagreeing_duplicates_conflict() -> None: + (s,) = _subjects(1) + settled = settle( + Obligations.fix([s], source="plan"), [_result(s, "held"), _result(s, "refuted")] + ) + assert settled.conflicting == (s,) and not settled.passes + + +def test_rates_use_the_planned_total() -> None: + subjects = _subjects(4) + settled = settle( + Obligations.fix(subjects, source="plan"), [_result(subjects[0], "held")] + ) + assert settled.rate(Status.HELD) == Fraction(1, 4) + assert settled.rate(Status.NOT_CHECKED) == Fraction(3, 4) + + +def test_label_follows_the_site_precedence() -> None: + a, b = _subjects(2) + settled = settle( + Obligations.fix([a, b], source="plan"), + [_result(a, "refuted"), _result(b, "not_checked")], + ) + assert ( + settled.label(precedence=(Status.NOT_CHECKED, Status.REFUTED)) + is Status.NOT_CHECKED + ) + assert ( + settled.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) is Status.REFUTED + ) + + +@pytest.mark.parametrize( + "exc", [Exception("x"), TimeoutError(), KeyError("k"), OSError(5, "io")] +) +def test_observe_never_returns_observed_on_a_raise(exc: Exception) -> None: + def probe() -> object: + raise exc + + got = observe(probe) + assert isinstance(got, Errored) and got.exc_type == type(exc).__name__ + assert observe(probe, benign={KeyError: Missing("no row")}) == ( + Missing("no row") if isinstance(exc, KeyError) else got + ) + + +def test_observe_reraises_fail_closed() -> None: + def probe() -> object: + raise FailClosed("stop") + + with pytest.raises(FailClosed): + observe(probe, benign={Exception: Missing("x")}) + + +def test_held_needs_a_complete_observation() -> None: + (s,) = _subjects(1) + for obs in (Missing("x"), Errored("E", "x"), Observed(1, complete=False)): + with pytest.raises(TypeError): + Result.held(s, obs) + with pytest.raises(TypeError): + Result(s, Status.HELD, "forged") + with pytest.raises(TypeError): + Result.refuted(s, Missing("x"), "no") + + +def test_from_observation_never_judges_a_missing_read() -> None: + (s,) = _subjects(1) + + def judge(_value: object) -> tuple[Status, str]: + raise AssertionError("judge called") + + for obs in (Missing("x"), Errored("E", "x"), Observed(1, complete=False)): + assert Result.from_observation(s, obs, judge).status is Status.NOT_CHECKED + assert ( + Result.from_observation(s, Observed(1), lambda v: (Status.HELD, "ok")).status + is Status.HELD + ) + + +@pytest.mark.parametrize("code", ["unknown", "", None, 1, "CONFIRMED", "confirmed "]) +def test_from_code_is_an_allow_list(code: object) -> None: + status = from_code( + code, held=frozenset({"confirmed"}), refuted=frozenset({"refuted"}) + ) + assert status is Status.NOT_CHECKED + + +def test_from_code_refuses_overlapping_lists() -> None: + with pytest.raises(ValueError): + from_code("x", held=frozenset({"x"}), refuted=frozenset({"x"})) + + +def test_obligations_dedupe_by_subject_key() -> None: + a = Subject(key="1", run_id="r1") + assert Obligations.fix([a, Subject(key="1", run_id="r2")], source="p").items == (a,) + + +@pytest.mark.parametrize( + "source, verified, label", + [ + (TrustSource.LOCAL_KEY, True, "signed on this computer"), + (TrustSource.REGISTERED, True, "signed by a registered signer"), + (TrustSource.EMBEDDED, True, "signature valid, signer not known"), + (TrustSource.UNVERIFIED, True, "not verified"), + (TrustSource.LOCAL_KEY, False, "not verified"), + ("local_key", True, "not verified"), + (None, True, "not verified"), + ], +) +def test_trust_label_names_a_signer_only_from_a_verified_source( + source: object, verified: bool, label: str +) -> None: + assert trust_label(source, verified=verified) == label diff --git a/packages/flow/tests/failopen/test_kernel_mutants.py b/packages/flow/tests/failopen/test_kernel_mutants.py new file mode 100644 index 0000000000..fde998f4da --- /dev/null +++ b/packages/flow/tests/failopen/test_kernel_mutants.py @@ -0,0 +1,116 @@ +"""Each rule of the kernel is load-bearing: break it and a check fails. + +A hand-rolled mutant runner (no new dependency): each mutant rewrites one +rule of ``openadapt_flow/verdict.py`` in its source, loads the result as a +fresh module, and runs :func:`battery` on it. Every mutant must be killed; +the unmutated module must survive. A mutant whose source text is no longer +found fails the test, so the runner can't silently stop mutating. +""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path +from types import ModuleType + +import pytest + +SOURCE = Path(__file__).resolve().parents[2] / "openadapt_flow" / "verdict.py" + +MUTANTS: dict[str, tuple[str, str]] = { + "drop total>0": (" self.total > 0\n", " True\n"), + # ``passes`` checks both ``len(held) == total`` and ``not missing``, so + # deleting either one alone is an equivalent mutant. The rule is that an + # obligation with no result is never counted as held. + "missing counts as held": ( + ' buckets["missing"].append(item)\n', + ' buckets["held"].append(item)\n', + ), + "ignore unexpected": (" and not self.unexpected\n", "\n"), + "ignore mismatched": ( + " elif any(binding_mismatches(item, r.subject) for r in got):\n", + " elif False:\n", + ), + "keep last writer": ( + " elif len({r.status for r in got}) > 1:\n conflicting.append(item)\n" + " else:\n buckets[got[0].status.value].append(item)\n", + " else:\n buckets[got[-1].status.value].append(item)\n", + ), + "truncate at limit": ( + " for item in obligations.items:\n", + " obligations = Obligations(obligations.items[:limit], obligations.source)" + " if limit is not None else obligations\n for item in obligations.items:\n", + ), + "observe returns a default": ( + " return Errored(type(exc).__name__, str(exc)[:200])\n", + " return Observed(None)\n", + ), + "from_code deny-list": ( + " if code in refuted:\n return Status.REFUTED\n return Status.NOT_CHECKED\n", + " if code in refuted:\n return Status.REFUTED\n return Status.HELD\n", + ), +} + + +def _load(source: str, name: str) -> ModuleType: + spec = importlib.util.spec_from_loader(name, loader=None) + assert spec is not None + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module # dataclasses resolve annotations through it + try: + exec(compile(source, f"<{name}>", "exec"), module.__dict__) + finally: + sys.modules.pop(name, None) + return module + + +def battery(v: ModuleType) -> None: + """The kernel's rules as plain asserts, run on a (mutated) module.""" + + S, O, R = v.Subject, v.Obligations, v.Result + a, b = S(key="a"), S(key="b") + + def held(s: object) -> object: + return R.held(s, v.Observed(1)) + + def fix(*items: object) -> object: + return O.fix(list(items), source="plan") + + assert not v.settle(fix(), []).passes, "empty passes" + assert not v.settle(fix(a, b), [held(a)]).passes, "missing ignored" + assert not v.settle(fix(a), [held(a), held(b)]).passes, "unexpected ignored" + bound = S(key="a", run_id="run-1") + assert not v.settle(fix(bound), [held(S(key="a", run_id="run-2"))]).passes, ( + "run ignored" + ) + assert not v.settle(fix(a), [R.refuted(a, v.Observed(0), "x"), held(a)]).passes, ( + "last writer" + ) + many = [S(key=str(i)) for i in range(5)] + results = [held(s) for s in many[:-1]] + [R.refuted(many[-1], v.Observed(0), "x")] + settled = v.settle(fix(*many), results, limit=3) + assert len(settled.refuted) == 1 and settled.total == 5, "truncated" + + def boom() -> object: + raise TimeoutError + + assert not isinstance(v.observe(boom), v.Observed), "observe defaulted" + assert ( + v.from_code("new_code", held=frozenset({"ok"}), refuted=frozenset({"bad"})) + is v.Status.NOT_CHECKED + ), "deny-list" + + +def test_the_kernel_survives_its_battery() -> None: + battery(_load(SOURCE.read_text(encoding="utf-8"), "_verdict_original")) + + +@pytest.mark.parametrize("name", sorted(MUTANTS)) +def test_every_mutant_is_killed(name: str) -> None: + text = SOURCE.read_text(encoding="utf-8") + old, new = MUTANTS[name] + assert text.count(old) == 1, f"mutant {name!r}: its source text is gone" + mutant = _load(text.replace(old, new), f"_verdict_mutant_{abs(hash(name))}") + with pytest.raises(AssertionError): + battery(mutant) diff --git a/packages/flow/tests/failopen/test_registry_complete.py b/packages/flow/tests/failopen/test_registry_complete.py new file mode 100644 index 0000000000..e7e6d54744 --- /dev/null +++ b/packages/flow/tests/failopen/test_registry_complete.py @@ -0,0 +1,104 @@ +"""Every ``@verdict_site`` has a spec, and every spec names real code. + +A site on main is decorated where it is defined and has a ``site`` spec. A +site an open pull request owns has an ``owned`` spec with a strict xfail +until the owner adopts it, decorates it and turns the spec into a ``site``. +""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +from scripts.check_verdict_folds import ROOT, decorated_sites, load_config, scope_files +from tests.failopen.harness import load_all + +SPECS = load_all() + + +def _decorated() -> dict[str, tuple[str, str]]: + out: dict[str, tuple[str, str]] = {} + for path in scope_files(load_config()): + for site, qualname in decorated_sites(path).items(): + assert site not in out, f"{site} decorated twice" + out[site] = (path.relative_to(ROOT).as_posix(), qualname) + return out + + +def _resolve(target: str) -> object: + module, _, qualname = target.partition(":") + if module.endswith(".py"): + assert (ROOT / module).is_file(), target + return None + obj: object = importlib.import_module(module) + for part in qualname.split("."): + obj = getattr(obj, part) + return obj + + +def test_every_decorated_site_has_a_spec() -> None: + decorated = _decorated() + sites = {s.id for s in SPECS.values() if s.kind == "site"} + assert set(decorated) == sites, ( + f"decorated without a spec: {sorted(set(decorated) - sites)}; " + f"spec without a decorated function: {sorted(sites - set(decorated))}" + ) + + +def test_every_site_spec_targets_its_decorated_function() -> None: + decorated = _decorated() + for spec in SPECS.values(): + if spec.kind != "site": + continue + path, qualname = decorated[spec.id] + module, _, target_name = spec.target.partition(":") + assert path == "packages/flow/" + module.replace(".", "/") + ".py", spec.id + assert qualname == target_name, spec.id + assert getattr(_resolve(spec.target), "__verdict_site__", None) == spec.id + + +def test_owned_and_selftest_targets_exist() -> None: + for spec in SPECS.values(): + if spec.kind == "owned": + _resolve(spec.target) + assert spec.xfail, spec.id + elif spec.kind == "selftest": + assert spec.id.startswith("selftest."), spec.id + + +def test_vendored_files_carry_their_source() -> None: + selftest = Path(__file__).with_name("selftest") + for path in sorted(selftest.glob("_v_*.py")): + first = path.read_text(encoding="utf-8").splitlines()[0] + assert first.startswith("# vendored from "), path.name + assert "for the harness self-test only" in first, path.name + + +def test_vendored_lines_match_history_when_it_is_available() -> None: + """Each ``# vendored: sha:path a-b`` block equals those lines at that + commit (re-indented). CI's shallow checkout has no history: skipped there.""" + + import re + import subprocess + import textwrap + + import pytest + + marker = re.compile( + r"# vendored: (\w+):(\S+) (\d+)-(\d+)\n\s*# fmt: off\n(.*?)\n\s*# fmt: on", re.S + ) + checked = 0 + for path in sorted(Path(__file__).with_name("selftest").glob("_v_*.py")): + for sha, src, a, b, block in marker.findall(path.read_text(encoding="utf-8")): + got = subprocess.run( + ["git", "-C", str(ROOT), "show", f"{sha}:{src}"], + capture_output=True, + text=True, + ) + if got.returncode != 0: + continue + want = "\n".join(got.stdout.splitlines()[int(a) - 1 : int(b)]) + assert textwrap.dedent(block) == textwrap.dedent(want), f"{path.name} {sha}" + checked += 1 + if not checked: + pytest.skip("no git history for the vendored commits") diff --git a/packages/flow/tests/failopen/test_selftest.py b/packages/flow/tests/failopen/test_selftest.py new file mode 100644 index 0000000000..5ef157b9f7 --- /dev/null +++ b/packages/flow/tests/failopen/test_selftest.py @@ -0,0 +1,41 @@ +"""The harness catches every historical bug and passes every fix. + +Each bug is real code from this repository: vendored pre-fix copies under +``selftest/`` (commit and lines in their first line) or main itself. The fix +is the vendored post-fix copy, or main after this change. Kill criteria 1 and +2 of the design: at least 8 bugs caught, all from real code, and no post-fix +copy flagged. +""" + +from __future__ import annotations + +import pytest + +from tests.failopen.harness import load_all, run_site +from tests.failopen.selftest.specs import PAIRS + +REGISTRY = load_all() + + +@pytest.mark.parametrize("name", sorted(PAIRS)) +def test_pre_fix_is_flagged(name: str) -> None: + pre, _post, catches = PAIRS[name] + failures = run_site(REGISTRY[pre]) + caught_by = {f.mutator for f in failures} + assert caught_by & catches, ( + f"{name}: expected one of {sorted(catches)} to flag the pre-fix code, " + f"got {sorted(caught_by) or 'nothing'}" + ) + + +@pytest.mark.parametrize("name", sorted(n for n, p in PAIRS.items() if p[1])) +def test_post_fix_holds(name: str) -> None: + _pre, post, _catches = PAIRS[name] + assert post is not None + failures = run_site(REGISTRY[post]) + assert not failures, "\n".join(str(f) for f in failures) + + +def test_enough_real_bugs_are_caught() -> None: + caught = [n for n, (pre, _, _) in PAIRS.items() if run_site(REGISTRY[pre])] + assert len(caught) >= 8, caught diff --git a/packages/flow/tests/failopen/test_sites.py b/packages/flow/tests/failopen/test_sites.py new file mode 100644 index 0000000000..a7c1f3fe5a --- /dev/null +++ b/packages/flow/tests/failopen/test_sites.py @@ -0,0 +1,32 @@ +"""Every registered verdict site holds under every generic mutation. + +A site an open pull request owns is ``xfail(strict=True)`` with that pull +request in the reason: when its fix lands the test passes unexpectedly, and +the marker has to come out in the same change (FAIL_CLOSED.md, adoption). +""" + +from __future__ import annotations + +import pytest + +from tests.failopen.harness import load_all, run_site + +SPECS = {k: v for k, v in load_all().items() if v.kind in ("site", "owned")} + + +def _param(spec_id: str) -> object: + spec = SPECS[spec_id] + marks = [pytest.mark.xfail(strict=True, reason=spec.xfail)] if spec.xfail else [] + return pytest.param(spec_id, marks=marks, id=spec_id) + + +@pytest.mark.parametrize("spec_id", [_param(k) for k in sorted(SPECS)]) +def test_site_holds(spec_id: str) -> None: + failures = run_site(SPECS[spec_id]) + assert not failures, "\n".join(str(f) for f in failures) + + +def test_owned_sites_name_their_owner() -> None: + for spec in SPECS.values(): + if spec.kind == "owned": + assert spec.xfail and ("#" in spec.xfail), spec.id diff --git a/packages/flow/tests/failopen/test_verify_run_migration.py b/packages/flow/tests/failopen/test_verify_run_migration.py new file mode 100644 index 0000000000..6375466228 --- /dev/null +++ b/packages/flow/tests/failopen/test_verify_run_migration.py @@ -0,0 +1,70 @@ +"""The verify_run folds moved onto the kernel change nothing but the empty +case (kill criterion 6): differential against the copies vendored from main.""" + +from __future__ import annotations + +from types import SimpleNamespace + +from hypothesis import given, settings +from hypothesis import strategies as st + +from openadapt_flow import verify_run +from openadapt_flow.runtime.effects.effect import Verdict +from tests.failopen.selftest import _v_s9_verify_run_pre as before + +PROFILE = settings(derandomize=True, max_examples=300, deadline=None) +VERDICTS = st.sampled_from(list(Verdict)) +OBSERVED = st.sampled_from(["present", "absent", "unknown", "conflicting"]) + + +@PROFILE +@given(st.lists(VERDICTS, min_size=1, max_size=12)) +def test_aggregate_is_unchanged_on_any_effects(verdicts: list[Verdict]) -> None: + items = [SimpleNamespace(verdict=v) for v in verdicts] + assert verify_run._aggregate(items) == before._aggregate(items) + + +@PROFILE +@given(st.lists(OBSERVED, min_size=1, max_size=12)) +def test_observed_is_unchanged_on_any_effects(seen: list[str]) -> None: + items = [SimpleNamespace(observed_effect=s) for s in seen] + assert verify_run._observed(items) == before._observed(items) + + +class _Tier: + def __init__(self, sor: bool) -> None: + self.sor = sor + + def reads_system_of_record(self) -> bool: + return self.sor + + +@PROFILE +@given( + st.lists( + st.tuples(st.booleans(), st.booleans(), st.sampled_from([None, True, False])), + min_size=1, + max_size=8, + ) +) +def test_readback_class_is_unchanged_when_tiers_pair_with_effects( + rows: list[tuple[bool, bool, object]], +) -> None: + verdicts = [SimpleNamespace(unavailable=u, stale=s) for u, s, _ in rows] + tiers = [None if t is None else _Tier(bool(t)) for _, _, t in rows] + assert verify_run.readback_class(verdicts, tiers) == before.readback_class( + verdicts, tiers + ) + + +def test_only_the_empty_and_unpaired_cases_change() -> None: + assert (before._aggregate([]), verify_run._aggregate([])) == ( + "CONFIRMED", + "INDETERMINATE", + ) + assert (before._observed([]), verify_run._observed([])) == ("present", "unknown") + assert before.readback_class([], []) == "independent_readback" + assert verify_run.readback_class([], []) == "unchecked" + one = [SimpleNamespace(unavailable=False, stale=False)] * 2 + assert before.readback_class(one, [_Tier(True)]) == "independent_readback" + assert verify_run.readback_class(one, [_Tier(True)]) == "unchecked" diff --git a/packages/flow/tests/test_verdict_folds_check.py b/packages/flow/tests/test_verdict_folds_check.py new file mode 100644 index 0000000000..e5aa01fb35 --- /dev/null +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -0,0 +1,77 @@ +"""scripts/check_verdict_folds.py: each fold kind is counted, a registered +site is exempt, and only growth fails.""" + +from __future__ import annotations + +import textwrap +from pathlib import Path + +import pytest + +from scripts import check_verdict_folds as folds + +CONFIG = folds.load_config() + +SNIPPETS = { + "says_success": 'def f():\n return "VERIFIED"\n', + "cmp_literal": 'def f(x):\n return x == "ROLLED_BACK"\n', + "bool_fold": "def f(results):\n return all(r.ok for r in results)\n", + "swallow": "def f(g):\n try:\n return g()\n except Exception:\n return 0\n", + "slice_count": "def f(lines):\n n = sum(1 for x in lines[:256] if x)\n return n\n", + "else_success": 'def f(x):\n if x:\n y = "REFUTED"\n else:\n y = "CONFIRMED"\n return y\n', +} + + +def _count(tmp_path: Path, source: str) -> dict[str, int]: + path = tmp_path / "m.py" + path.write_text(textwrap.dedent(source)) + return dict(folds.count_file(path, CONFIG)) + + +@pytest.mark.parametrize("kind", sorted(SNIPPETS)) +def test_each_kind_is_counted(tmp_path: Path, kind: str) -> None: + assert _count(tmp_path, SNIPPETS[kind]).get(kind, 0) >= 1 + + +def test_closed_except_is_not_a_swallow(tmp_path: Path) -> None: + src = "def f(g):\n try:\n return g()\n except Exception as e:\n return Errored(type(e).__name__, '')\n" + assert "swallow" not in _count(tmp_path, src) + + +def test_a_registered_site_is_exempt(tmp_path: Path) -> None: + body = "".join(SNIPPETS.values()).replace("def f(", "def g(") + src = "@verdict_site('x', classes='C2')\n" + body.replace( + "\ndef g(", + "\n@verdict_site('x', classes='C2')\ndef g(", + ) + assert _count(tmp_path, src) == {} + + +def test_only_growth_fails() -> None: + base = {"a.py": {"swallow": 2}} + assert folds.compare({"a.py": {"swallow": 3}}, base) + assert folds.compare({"b.py": {"swallow": 1}}, base) + assert not folds.compare({"a.py": {"swallow": 1}}, base) + assert not folds.compare({}, base) + + +def test_the_baseline_only_lowers() -> None: + base = {"a.py": {"swallow": 2, "bool_fold": 1}} + assert folds.lowered({"a.py": {"swallow": 5}, "b.py": {"swallow": 1}}, base) == { + "a.py": {"swallow": 2} + } + + +def test_main_is_within_the_baseline() -> None: + import json + + baseline = json.loads(folds.BASELINE.read_text(encoding="utf-8")) + assert folds.compare(folds.scan(CONFIG), baseline) == [] + + +def test_the_config_names_no_application() -> None: + from scripts import check_engine_generality as gen + + text = folds.CONFIG.read_text(encoding="utf-8") + for term, (pattern, _is_name) in gen._term_patterns(gen.load_config()).items(): + assert not pattern.search(text), term From f6d8d0dfa08968f7b5ed15b351ac14b8bed95e2b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:03:30 -0500 Subject: [PATCH 02/14] fix(flow): close the gaps a review found in the verdict kernel and harness - settle matches on subject key and run binding; obligations dedupe on both - a HELD token is bound to its subject, so replace() can't move it - observe refuses to map an exception to Observed - owned sites list their exact known failures (strict xfail per case) - pre-fix controls are pinned copies, never live code; S3b shows the undo fix still passes an unlisted per-write code - the ratchet compares per-kind totals, so moving code into a new module is not a new fold, judges each exit of an except, refuses a site id on two functions, and runs in the smoke job on every change --- .github/workflows/ci.yml | 10 ++- .github/workflows/packages.yml | 6 -- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/CHANGELOG.md | 2 +- packages/flow/docs/FAIL_CLOSED.md | 35 ++++---- packages/flow/openadapt_flow/verdict.py | 52 ++++++++---- packages/flow/openadapt_flow/verify_run.py | 2 +- packages/flow/scripts/check_verdict_folds.py | 67 ++++++++++++---- .../flow/scripts/verdict_folds_baseline.json | 44 ++++++----- packages/flow/tests/failopen/harness.py | 31 ++++++-- packages/flow/tests/failopen/mutators.py | 10 +-- .../failopen/selftest/_v_s8_governed_pre.py | 79 +++++++++++++++++++ .../failopen/selftest/_v_wire_tap_pre.py | 73 +++++++++++++++++ .../flow/tests/failopen/selftest/specs.py | 28 ++++--- .../tests/failopen/sites/connector_status.py | 4 + .../tests/failopen/sites/governed_safety.py | 4 + .../tests/failopen/sites/verify_run_folds.py | 2 +- .../tests/failopen/sites/wire_tap_relay.py | 5 ++ packages/flow/tests/failopen/test_kernel.py | 31 +++++++- .../tests/failopen/test_kernel_mutants.py | 10 +-- .../tests/failopen/test_registry_complete.py | 17 +++- packages/flow/tests/failopen/test_sites.py | 32 ++++---- .../failopen/test_verify_run_migration.py | 4 +- .../flow/tests/test_verdict_folds_check.py | 34 +++++++- 25 files changed, 462 insertions(+), 124 deletions(-) create mode 100644 packages/flow/tests/failopen/selftest/_v_s8_governed_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_wire_tap_pre.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1ef25466a9..5c5e6f6715 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ name: CI # - The launcher's own lint and tests (main.yml). # - A smoke test of every package, whatever changed: each installs from its # lock, imports and starts (scripts/ci/smoke.py). The same job runs the -# file-size ratchet against the change's base. +# file-size ratchet against the change's base and the verdict-fold ratchet. # # `ci` passes when every job above passed or was not selected; it is skipped # (which counts as passing) when they all passed. Until branch @@ -61,6 +61,14 @@ jobs: # file this change grew (or whose budget row it edited), so a file # someone else left over budget never fails an unrelated change. run: python3 scripts/check_file_size_ratchet.py --base HEAD^1 + - name: No new hand-written verdict folds + # Runs on every change: it scans Flow, the launcher and scripts/ci. + # A check that can pass on an empty set, a short read or an unknown + # code is folded once in openadapt_flow/verdict.py; new verdict code + # goes in a @verdict_site with a spec under tests/failopen + # (packages/flow/docs/FAIL_CLOSED.md). Fails only when a kind's total + # rises above the baseline. Standard library only. + run: python3 packages/flow/scripts/check_verdict_folds.py - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: enable-cache: true diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 140b79b07e..7826dd6007 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -563,12 +563,6 @@ jobs: # App knowledge lives in profiles, contracts and fixtures (CONTRIBUTING: # "App knowledge lives in data"); the denylist is scripts/generality.toml. run: python scripts/check_engine_generality.py - - name: No new hand-written verdict folds - # A check that can pass on an empty set, a short read or an unknown - # code is folded once in openadapt_flow/verdict.py; a new fold goes in - # a @verdict_site with a spec under tests/failopen (docs/FAIL_CLOSED.md). - # Fails only when a file's count rises above the baseline. - run: python scripts/check_verdict_folds.py - name: Install uv (for the oldest-Python syntax check) uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Syntax at the oldest supported Python (3.10) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 4a458a10f7..bc5a32ff2b 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -177,7 +177,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | -| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 14 historical fail-open bugs rebuilt from this repository's own code (vendored pre-fix copies and three live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/llms-full.txt b/llms-full.txt index bb0c8db312..24262397b4 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -611,7 +611,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | -| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 14 historical fail-open bugs rebuilt from this repository's own code (vendored pre-fix copies and three live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index e503f5165f..d3660b1541 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -25,7 +25,7 @@ set, a truncated or short read, a probe that raised, a result bound to another run, two results that disagree, or a code nobody listed. Functions marked `@verdict_site` are run by a fail-open harness - (`tests/failopen`) with 13 generic mutations; it flags 14 historical bugs + (`tests/failopen`) with 13 generic mutations; it flags 15 fail-open bugs rebuilt from this repository's code and passes their fixes. `scripts/check_verdict_folds.py` fails CI when a file gains a hand-written fold. See `docs/FAIL_CLOSED.md`. diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 8cd29670e4..652a7b4d60 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -112,7 +112,8 @@ vectors (follow-up 5). from this repository's history. The first line of each file names the commit and the lines; the copied lines sit between `# fmt: off` and `# fmt: on`. `test_selftest.py` requires the harness to flag every pre-fix copy and to pass -every post-fix copy: +every post-fix copy. A spec with no pass seed, or one that no mutation +applies to, fails too: | Bug | Pre-fix | Post-fix | Caught by | |---|---|---|---| @@ -123,14 +124,20 @@ every post-fix copy: | S5 `min_scored=1`; an undelivered fault drops a run from the rates (#2419) | `275199914^` and `275199914` | open | M9 | | S6 a type-ahead prefix matches an assumed typed baseline (#2448) | `c329c57dc^` | `c329c57dc` | P0, M11 | | S7 a cancel after the child started is reported as failed (#2300) | `fd7133866` | #2300 head | M12 | -| S8 `''` and NULL in the governed check (#2258) | main | `00a55cc16` | P0, M10 | -| Wire tap relays `///host` raw (#2470) | main | #2470 head | M11 | +| S3b the S3 fix still keeps a deny-list: a per-write code nobody listed is `ROLLED_BACK` | `fda539c78` | open | M14 | +| S8 `''` and NULL in the governed check (#2258) | main at `576f87b41` | `00a55cc16` | P0, M10 | +| Wire tap relays `///host` raw (#2470) | main at `576f87b41` | #2470 head | M11 | | S9 `verify_run` folds pass an empty effect list | main before this change | main | M1, M3 | +The pre-fix controls are pinned copies, never live code, so landing a fix on +main can't turn a control green. + Three sites on main are still fail-open and are owned by open pull requests. -Their specs are `xfail(strict=True)` with the owner in the reason: when the fix -lands, the test passes unexpectedly and fails, so the marker has to come out -in the same change. +Their specs are `owned`: they name the owner and list exactly the failures the +site has today. This is a strict xfail per case. A new failure fails the test, +so a known bug can't hide another one. A known failure that goes away also +fails it, so the list, and then the `owned` marker, comes out in the change +that fixes the site. - `wire_tap.relay_redirect_location`: `///evil.example/x` is relayed raw (#2470). - `governed_safety.check`: a held target note changed between `''` and NULL @@ -141,18 +148,18 @@ in the same change. ## The ratchet -`scripts/check_verdict_folds.py` runs in the required `ci` check, next to the -engine-generality check. It counts, per file in `openadapt_flow/`, the +`scripts/check_verdict_folds.py` runs in the required `ci` check, in the smoke +job that runs on every change, next to the file-size ratchet. It counts, in `openadapt_flow/`, the launcher and `scripts/ci/`, six kinds of hand-written fold: a success literal produced in code (`VERIFIED`, `CONFIRMED`, `held`, ...), a compare against an outcome literal, `all()`/`any()` over verdicts or results, a broad `except` that returns without a raise or a not-checked value, a slice in a statement -that counts, and a final `else` that assigns success. It fails only when a -file's count rises above `verdict_folds_baseline.json`. It never fails on a -drop, so open pull requests that don't add folds are unaffected. To add -verdict code, put it in a `@verdict_site` with a spec; the ratchet doesn't -count inside one. When a file is renamed, move its baseline entry in the same -change. +that counts, and a final `else` that assigns success. It fails only when the +total for a kind rises above `verdict_folds_baseline.json`, and then lists the +files whose count rose. Totals decide, so moving code into a new module (as +the decomposition plan asks) is not a new fold. It never fails on a drop; run +it with `--update-baseline` to lower the baseline. To add verdict code, put it +in a `@verdict_site` with a spec; the ratchet doesn't count inside one. ## Review rule diff --git a/packages/flow/openadapt_flow/verdict.py b/packages/flow/openadapt_flow/verdict.py index 51ac4f63c6..276480d7a1 100644 --- a/packages/flow/openadapt_flow/verdict.py +++ b/packages/flow/openadapt_flow/verdict.py @@ -106,7 +106,8 @@ def observe( A returned :data:`Observation` passes through; any other value becomes :class:`Observed`. :class:`FailClosed` re-raises. An exception listed in ``benign`` maps to its declared observation (a 404 that means "no such - row" is ``Missing``, never a value). Any other ``Exception`` becomes + row" is ``Missing``; mapping one to ``Observed`` raises ``TypeError``). + Any other ``Exception`` becomes :class:`Errored`. It never returns a default value. """ @@ -117,6 +118,9 @@ def observe( except Exception as exc: # noqa: BLE001 - every failure becomes Errored for kind, mapped in (benign or {}).items(): if isinstance(exc, kind): + if not isinstance(mapped, (Missing, Errored)): + # A raised probe is never evidence that something holds. + raise TypeError("benign maps an exception to Missing or Errored") return mapped return Errored(type(exc).__name__, str(exc)[:200]) if isinstance(value, (Observed, Missing, Errored)): @@ -198,10 +202,15 @@ def require_bound(expected: Subject, got: Subject) -> None: # -- results ---------------------------------------------------------------------- #: Only this module's constructors hold it, so ``Result(..., Status.HELD, ...)`` -#: written anywhere else raises. +#: written anywhere else raises. The token is bound to the subject, so +#: ``dataclasses.replace(result, subject=other)`` raises too. _JUDGED = object() +def _seal(subject: "Subject") -> object: + return (_JUDGED, subject) + + @dataclass(frozen=True) class Result: """One check of one subject. Build it with the class methods.""" @@ -214,7 +223,14 @@ class Result: def __post_init__(self) -> None: if not isinstance(self.status, Status): raise TypeError(f"status must be a Status, not {self.status!r}") - if self.status is Status.HELD and self._token is not _JUDGED: + token = self._token + sealed = ( + isinstance(token, tuple) + and len(token) == 2 + and token[0] is _JUDGED + and token[1] == self.subject + ) + if self.status is Status.HELD and not sealed: raise TypeError( "HELD comes only from Result.held or Result.from_code; " "see docs/FAIL_CLOSED.md" @@ -226,7 +242,7 @@ def held(cls, subject: Subject, obs: Observation, reason: str = "") -> "Result": if not isinstance(obs, Observed) or obs.complete is not True: raise TypeError("HELD needs a complete Observed value") - return cls(subject, Status.HELD, reason or "held", _JUDGED) + return cls(subject, Status.HELD, reason or "held", _seal(subject)) @classmethod def refuted(cls, subject: Subject, obs: Observation, reason: str) -> "Result": @@ -278,7 +294,7 @@ def from_code( status = from_code(code, held=held, refuted=refuted) text = reason or f"code {code!r}" if status is Status.HELD: - return cls(subject, status, text, _JUDGED) + return cls(subject, status, text, _seal(subject)) return cls(subject, status, text) @@ -313,14 +329,16 @@ class Obligations: @classmethod def fix(cls, items: Iterable[Subject], *, source: str) -> "Obligations": - """Dedupe by :meth:`Subject.key_tuple`, keeping the first. Empty is - allowed; it never settles as a pass.""" + """Dedupe by subject key and binding, keeping the first: the same field + planned in two runs is two obligations. Empty is allowed; it never + settles as a pass.""" seen: set[tuple[object, ...]] = set() kept = [] for item in items: - if item.key_tuple() not in seen: - seen.add(item.key_tuple()) + ident = (*item.key_tuple(), *(getattr(item, f) for f in BINDING_FIELDS)) + if ident not in seen: + seen.add(ident) kept.append(item) return cls(tuple(kept), source) @@ -406,27 +424,31 @@ def settle( *, limit: Optional[int] = None, ) -> Settlement: - """Match results to obligations by subject key. See :class:`Settlement`.""" + """Match results to obligations by subject key and binding. See + :class:`Settlement`.""" by_key: dict[tuple[object, ...], list[Result]] = {} for result in results: by_key.setdefault(result.subject.key_tuple(), []).append(result) - wanted = {o.key_tuple() for o in obligations.items} buckets: dict[str, list[Subject]] = { k: [] for k in ("held", "refuted", "not_checked", "missing", "mismatched") } conflicting: list[Subject] = [] + used: set[int] = set() for item in obligations.items: - got = by_key.get(item.key_tuple(), []) - if not got: + same_key = by_key.get(item.key_tuple(), []) + got = [r for r in same_key if not binding_mismatches(item, r.subject)] + used.update(id(r) for r in got) + if not same_key: buckets["missing"].append(item) - elif any(binding_mismatches(item, r.subject) for r in got): + elif not got: buckets["mismatched"].append(item) elif len({r.status for r in got}) > 1: conflicting.append(item) else: buckets[got[0].status.value].append(item) - unexpected = tuple(r for key, rs in by_key.items() if key not in wanted for r in rs) + # A result no obligation took: another key, or another run's binding. + unexpected = tuple(r for rs in by_key.values() for r in rs if id(r) not in used) total = len(obligations.items) return Settlement( total=total, diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 110da6bb08..29c2897ae6 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -2964,7 +2964,7 @@ def _label(verdict: Verdict) -> EffectVerdictLabel: } -@verdict_site("verify_run.aggregate", classes="C2 C3") +@verdict_site("verify_run.aggregate", classes="C2") def _aggregate(verdicts: Sequence[EffectVerdict]) -> EffectVerdictLabel: """CONFIRMED only when every effect is; any INDETERMINATE outranks a REFUTED; no effects at all is INDETERMINATE (docs/FAIL_CLOSED.md).""" diff --git a/packages/flow/scripts/check_verdict_folds.py b/packages/flow/scripts/check_verdict_folds.py index 8b0a692777..7a39f7af34 100644 --- a/packages/flow/scripts/check_verdict_folds.py +++ b/packages/flow/scripts/check_verdict_folds.py @@ -6,8 +6,9 @@ compare against ``"VERIFIED"``. ``openadapt_flow/verdict.py`` folds once, and a function marked ``@verdict_site`` has a spec the fail-open harness runs (``tests/failopen``). This check counts the hand-written folds everywhere -else, per file and per kind, and fails only when a count rises above -``verdict_folds_baseline.json``. A count that falls never fails; lower the +else, per kind, and fails only when a kind's total rises above +``verdict_folds_baseline.json`` (it lists the files whose count rose). +Totals decide, so moving code into a new module is not a new fold. A count that falls never fails; lower the baseline with ``--update-baseline`` when you like (it never raises one). What it counts (``verdict_folds.toml`` holds the literal lists): @@ -106,6 +107,10 @@ def visit(node: ast.AST, prefix: str) -> None: name = f"{prefix}{child.name}" site = _site_decorator(child) if site is not None: + if site in out: + raise ValueError( + f"{path}: verdict site {site!r} on both {out[site]} and {name}" + ) out[site] = name visit(child, name + ".") @@ -145,6 +150,23 @@ def _names(node: ast.AST) -> Iterator[str]: _NOT_CHECKED_NAMES = frozenset( {"Missing", "Errored", "not_checked", "NOT_CHECKED", "FailClosed"} ) +_NOT_CHECKED_STRINGS = frozenset( + {"not_checked", "NOT_CHECKED", "INDETERMINATE", "unchecked", "unknown", "UNKNOWN"} +) + + +def _closed_exit(node: ast.AST) -> bool: + """True for a ``return`` that hands back a not-checked value.""" + + value = getattr(node, "value", None) + if not isinstance(node, ast.Return) or value is None: + return False + return any(n in _NOT_CHECKED_NAMES for n in _names(value)) or any( + isinstance(c, ast.Constant) and c.value in _NOT_CHECKED_STRINGS + for c in ast.walk(value) + ) + + _COUNTING = frozenset({"sum", "len", "Counter", "tally", "count"}) @@ -200,15 +222,14 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: isinstance(node.type, ast.Name) and node.type.id in ("Exception", "BaseException") ) + # Each way out of the handler is judged on its own: a raise on one + # branch doesn't excuse a ``return True`` on another. body = ast.Module(body=node.body, type_ignores=[]) - leaves = any( - isinstance(n, (ast.Return, ast.Continue, ast.Pass)) + if broad and any( + not _closed_exit(n) for n in ast.walk(body) - ) - closed = any(isinstance(n, ast.Raise) for n in ast.walk(body)) or any( - name in _NOT_CHECKED_NAMES for name in _names(body) - ) - if broad and leaves and not closed: + if isinstance(n, (ast.Return, ast.Continue, ast.Pass)) + ): counts["swallow"] += 1 elif isinstance(node, ast.If) and node.orelse: tail = node.orelse @@ -272,17 +293,33 @@ def scan( return out +def totals(counts: dict[str, dict[str, int]]) -> Counter[str]: + out: Counter[str] = Counter() + for kinds in counts.values(): + out.update(kinds) + return out + + def compare( found: dict[str, dict[str, int]], baseline: dict[str, dict[str, int]] ) -> list[str]: - """Every (file, kind) whose count rose above the baseline.""" + """Every kind whose total rose above the baseline's, with the files whose + count rose. Totals, not per-file counts, decide: moving a fold to a new + module (the decomposition plan splits large files) is not a new fold.""" grown = [] - for rel, kinds in sorted(found.items()): - for kind, n in sorted(kinds.items()): - allowed = baseline.get(rel, {}).get(kind, 0) - if n > allowed: - grown.append(f"{rel}: {kind} {n} (baseline {allowed})") + now, allowed = totals(found), totals(baseline) + for kind in KINDS: + if now[kind] > allowed[kind]: + files = [ + f"{rel} {kinds[kind]} (baseline {baseline.get(rel, {}).get(kind, 0)})" + for rel, kinds in sorted(found.items()) + if kinds.get(kind, 0) > baseline.get(rel, {}).get(kind, 0) + ] + grown.append( + f"{kind}: {now[kind]} (baseline {allowed[kind]}); rose in " + + ("; ".join(files) or "no single file") + ) return grown diff --git a/packages/flow/scripts/verdict_folds_baseline.json b/packages/flow/scripts/verdict_folds_baseline.json index 44e8358f4d..d952d92a17 100644 --- a/packages/flow/scripts/verdict_folds_baseline.json +++ b/packages/flow/scripts/verdict_folds_baseline.json @@ -38,7 +38,7 @@ }, "packages/flow/openadapt_flow/__main__.py": { "cmp_literal": 14, - "swallow": 7 + "swallow": 8 }, "packages/flow/openadapt_flow/_browser_readiness.py": { "swallow": 1 @@ -67,7 +67,7 @@ }, "packages/flow/openadapt_flow/agent/authoring.py": { "cmp_literal": 3, - "swallow": 2 + "swallow": 6 }, "packages/flow/openadapt_flow/agent/bridge.py": { "cmp_literal": 2 @@ -110,7 +110,7 @@ "swallow": 3 }, "packages/flow/openadapt_flow/agent/runs.py": { - "swallow": 1 + "swallow": 2 }, "packages/flow/openadapt_flow/agent/sandbox.py": { "says_success": 2, @@ -145,7 +145,7 @@ }, "packages/flow/openadapt_flow/agent_guard/session.py": { "cmp_literal": 1, - "swallow": 3 + "swallow": 4 }, "packages/flow/openadapt_flow/approval_mode/approver.py": { "bool_fold": 1 @@ -224,17 +224,17 @@ }, "packages/flow/openadapt_flow/backends/playwright_backend.py": { "cmp_literal": 1, - "swallow": 70 + "swallow": 71 }, "packages/flow/openadapt_flow/backends/rdp_backend.py": { - "swallow": 8 + "swallow": 11 }, "packages/flow/openadapt_flow/backends/redirect_guard.py": { "swallow": 1 }, "packages/flow/openadapt_flow/backends/remote_display.py": { "bool_fold": 1, - "swallow": 29 + "swallow": 31 }, "packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py": { "bool_fold": 1 @@ -333,7 +333,7 @@ }, "packages/flow/openadapt_flow/compile_agent/repair_bridge.py": { "cmp_literal": 4, - "swallow": 1 + "swallow": 2 }, "packages/flow/openadapt_flow/compile_agent/repair_selection.py": { "cmp_literal": 7 @@ -396,7 +396,7 @@ "swallow": 5 }, "packages/flow/openadapt_flow/console/app.py": { - "swallow": 1 + "swallow": 2 }, "packages/flow/openadapt_flow/console/attention.py": { "cmp_literal": 1 @@ -434,6 +434,9 @@ "packages/flow/openadapt_flow/countersign/tsa.py": { "swallow": 3 }, + "packages/flow/openadapt_flow/countersign/vault.py": { + "swallow": 1 + }, "packages/flow/openadapt_flow/decision/calibration.py": { "cmp_literal": 1 }, @@ -506,10 +509,11 @@ "cmp_literal": 1 }, "packages/flow/openadapt_flow/form_tx/playwright_surface.py": { - "swallow": 13 + "swallow": 14 }, "packages/flow/openadapt_flow/form_tx/session_lease.py": { - "cmp_literal": 1 + "cmp_literal": 1, + "swallow": 1 }, "packages/flow/openadapt_flow/form_tx/types.py": { "says_success": 1 @@ -549,7 +553,7 @@ "cmp_literal": 6 }, "packages/flow/openadapt_flow/interactive_recorder.py": { - "swallow": 17 + "swallow": 20 }, "packages/flow/openadapt_flow/interchange/conformance.py": { "cmp_literal": 3 @@ -628,7 +632,7 @@ "slice_count": 1 }, "packages/flow/openadapt_flow/privacy.py": { - "swallow": 2 + "swallow": 5 }, "packages/flow/openadapt_flow/provenance.py": { "says_success": 1, @@ -789,8 +793,7 @@ }, "packages/flow/openadapt_flow/rl_env/reward.py": { "says_success": 2, - "cmp_literal": 5, - "swallow": 2 + "cmp_literal": 5 }, "packages/flow/openadapt_flow/rl_env/trainers.py": { "swallow": 1 @@ -831,7 +834,7 @@ "says_success": 1, "cmp_literal": 7, "bool_fold": 1, - "swallow": 3 + "swallow": 4 }, "packages/flow/openadapt_flow/runner/verify.py": { "swallow": 2 @@ -883,10 +886,11 @@ }, "packages/flow/openadapt_flow/runtime/durable/authority.py": { "cmp_literal": 6, - "swallow": 1 + "swallow": 2 }, "packages/flow/openadapt_flow/runtime/durable/checkpoint.py": { "bool_fold": 1, + "swallow": 1, "slice_count": 2 }, "packages/flow/openadapt_flow/runtime/durable/continuation.py": { @@ -1083,8 +1087,7 @@ "packages/flow/openadapt_flow/taskgen/validate.py": { "says_success": 1, "cmp_literal": 2, - "bool_fold": 3, - "swallow": 2 + "bool_fold": 3 }, "packages/flow/openadapt_flow/taskgen/workbench.py": { "swallow": 2 @@ -1190,6 +1193,9 @@ "packages/flow/openadapt_flow/wire_check.py": { "swallow": 1 }, + "packages/flow/openadapt_flow/wrap/candidate.py": { + "swallow": 1 + }, "packages/flow/openadapt_flow/wrap/cli.py": { "says_success": 1, "swallow": 1 diff --git a/packages/flow/tests/failopen/harness.py b/packages/flow/tests/failopen/harness.py index 47c5f4ef86..0ef855712d 100644 --- a/packages/flow/tests/failopen/harness.py +++ b/packages/flow/tests/failopen/harness.py @@ -37,9 +37,10 @@ P2 = frozenset({"M1", "M2", "M3", "M4", "M5", "M7", "M10", "M14"}) P3 = frozenset({"M8", "M11"}) #: Mutators P1 applies to: each one only removes or corrupts evidence. A -#: value perturbation (M10) or a rebuilt set (M2) can land on the correct -#: value by chance, so it is held to P2/P3 only. -P1_IDS = frozenset({"M1", "M3", "M4", "M5", "M7", "M8"}) +#: value perturbation (M10), a rebuilt set (M2) or a dropped result (M1, which +#: can drop the one bad result) can repair a failing seed, so those are held +#: to P2/P3 only. +P1_IDS = frozenset({"M3", "M4", "M5", "M7", "M8"}) @dataclass(frozen=True) @@ -167,7 +168,11 @@ class SiteSpec: #: open pull request owns; decorated when the owner adopts) or #: ``selftest`` (vendored history). kind: str = "site" + #: For an ``owned`` site: why it is still fail-open, and who owns the fix. xfail: Optional[str] = None + #: For an ``owned`` site: exactly the failures it has today (``Failure.key``). + #: Any other failure, or one of these going away, fails the test. + known: frozenset[str] = frozenset() notes: dict[str, str] = field(default_factory=dict) @@ -178,18 +183,25 @@ class Failure: prop: str detail: str + @property + def key(self) -> str: + return f"{self.mutator} {self.prop}: {self.detail}" + def __str__(self) -> str: - return f"{self.site} {self.mutator} {self.prop}: {self.detail}" + return f"{self.site} {self.key}" REGISTRY: dict[str, SiteSpec] = {} -def register(spec: SiteSpec, xfail: Optional[str] = None) -> SiteSpec: +def register( + spec: SiteSpec, xfail: Optional[str] = None, known: Sequence[str] = () +) -> SiteSpec: if spec.id in REGISTRY: raise ValueError(f"spec {spec.id!r} registered twice") if xfail is not None: spec.xfail = xfail + spec.known = frozenset(known) REGISTRY[spec.id] = spec return spec @@ -208,7 +220,11 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: from tests.failopen import mutators failures: list[Failure] = [] - for seed in spec.seeds(): + seeds = spec.seeds() + if not any(seed.correct_pass for seed in seeds): + failures.append(Failure(spec.id, "seed", "P0", "no pass seed to mutate")) + ran = 0 + for seed in seeds: got = safe_pass(spec, seed.evidence) if got != seed.correct_pass: failures.append( @@ -218,6 +234,7 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: for m in mutators.mutations(spec, seed): if only is not None and m.id not in only: continue + ran += 1 if m.check is not None: problem = m.check() if problem: @@ -235,6 +252,8 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: ) elif m.expect == "same" and after != got: failures.append(Failure(spec.id, m.id, "P4", f"{m.label}: changed")) + if not ran and only is None: + failures.append(Failure(spec.id, "spec", "P0", "no mutation applies")) return failures diff --git a/packages/flow/tests/failopen/mutators.py b/packages/flow/tests/failopen/mutators.py index 53b822f035..bbad760d87 100644 --- a/packages/flow/tests/failopen/mutators.py +++ b/packages/flow/tests/failopen/mutators.py @@ -15,7 +15,7 @@ from pathlib import Path from typing import Any, Optional -from tests.failopen.harness import ABSENT, Seed, SiteSpec, safe_pass +from tests.failopen.harness import ABSENT, Seed, SiteSpec CORPUS = Path(__file__).with_name("corpus") @@ -89,7 +89,7 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: "not_pass", ) # type: ignore[union-attr] if spec.inflate is not None: - n = (spec.limit or 256) + 1 + n = (256 if spec.limit is None else spec.limit) + 1 yield Mutation( "M2", f"{n} results, the last one bad", spec.inflate(ev, n), "not_pass" ) @@ -232,12 +232,12 @@ def check() -> str: return "" if case.unknown: return ( - f"unknown code passed as {out!r}" - if safe_pass(spec, case.evidence) + f"{case.label}: unlisted code passed as {out!r}" + if spec.is_pass(out) else "" ) if case.may_have_changed and case.forbidden(out): - return f"may have changed, reported {out!r}" + return f"{case.label}: may have changed, reported {out!r}" return "" return check diff --git a/packages/flow/tests/failopen/selftest/_v_s8_governed_pre.py b/packages/flow/tests/failopen/selftest/_v_s8_governed_pre.py new file mode 100644 index 0000000000..afea783bfc --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_s8_governed_pre.py @@ -0,0 +1,79 @@ +# vendored from 576f87b41483:scripts/ci/check_windows_governed_safety.py, lines 27-91, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""S8 pre-fix: main's governed check reads '' as no write (#2258); pinned so a fix on main can't turn the control green. + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + + +# vendored: 576f87b41483:scripts/ci/check_windows_governed_safety.py 27-91 +# fmt: off +import json +import sys +from pathlib import Path +from typing import Any + +PHASES = ("approved", "held", "resumed") + + +def _approved(phase: str, record: dict[str, Any], evidence: dict[str, Any]) -> bool: + if record.get("approval_decision") == "approved": + return True + # A resumed item's approval is the person's signed answer to the held + # request, which the test records on the held phase. + if phase == "resumed": + answers = (evidence.get("held") or {}).get("answer") or [] + return any(a.get("decision") == "approve" for a in answers) + return False + + +def check(evidence: Any) -> list[str]: + """Return the safety violations in ``evidence``; empty means safe.""" + + if not isinstance(evidence, dict): + return ["the evidence is not a JSON object"] + target = evidence.get("target_id") + expected = evidence.get("expected_note") + phases = evidence.get("phases") + if target is None or not expected or not isinstance(phases, list): + return ["the evidence names no target, expected note or phases"] + problems: list[str] = [] + for phase in phases: + if phase not in PHASES: + problems.append(f"unknown phase {phase!r}") + continue + record = evidence.get(phase) + rows = record.get("rows") if isinstance(record, dict) else None + if not isinstance(rows, list) or not rows: + problems.append(f"{phase}: no record rows; cannot confirm what was written") + continue + assert isinstance(record, dict) + written = [r for r in rows if r.get("note")] + siblings = [r["id"] for r in written if r.get("id") != target] + if siblings: + problems.append(f"{phase}: non-target rows {siblings} have a note") + target_rows = [r for r in written if r.get("id") == target] + outcome = record.get("outcome") + if phase == "held": + if written: + problems.append("held: the held run wrote") + if outcome == "VERIFIED": + problems.append("held: reported VERIFIED while held") + continue + if target_rows: + note = target_rows[0].get("note") + if note != expected: + problems.append(f"{phase}: the target holds an unexpected note") + if outcome != "VERIFIED": + problems.append( + f"{phase}: the target was written but the outcome is {outcome!r}" + ) + if not _approved(phase, record, evidence): + problems.append(f"{phase}: the target was written without an approval") + elif outcome == "VERIFIED": + problems.append(f"{phase}: reported VERIFIED but nothing was written") + return problems +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_wire_tap_pre.py b/packages/flow/tests/failopen/selftest/_v_wire_tap_pre.py new file mode 100644 index 0000000000..2e5b0e7928 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_wire_tap_pre.py @@ -0,0 +1,73 @@ +# vendored from 576f87b41483:packages/flow/openadapt_flow/tx/wire_tap.py, lines 91-147, for the harness self-test only (re-indented) +# ruff: noqa: F401, F841, I001 +"""Wire tap pre-fix: main relays '///host' raw (#2470); pinned so a fix on main can't turn the control green. + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrapper ``def`` lines, +the ``return`` and the stubs above them are not.""" + +from __future__ import annotations + +from typing import Optional +from urllib.parse import urljoin, urlsplit + + +# vendored: 576f87b41483:packages/flow/openadapt_flow/tx/wire_tap.py 91-147 +# fmt: off +def _normalize_origin(url_or_origin: str) -> str: + parts = urlsplit(url_or_origin.strip()) + if not parts.scheme or not parts.netloc: + return "" + scheme = parts.scheme.lower() + host = (parts.hostname or "").lower() + port = parts.port + if ( + port is None + or (scheme == "http" and port == 80) + or (scheme == "https" and port == 443) + ): + return f"{scheme}://{host}" + return f"{scheme}://{host}:{port}" + + +def relay_redirect_location( + location: str, + *, + request_url: str, + allowed_origins: frozenset[str], + rewrite_from_origin: Optional[str] = None, + rewrite_to_origin: Optional[str] = None, +) -> Optional[str]: + """Return the ``Location`` to relay for a same-origin redirect, else ``None``. + + The tap never follows a redirect itself. It hands a redirect back to the + client only when the target, resolved against the request URL, stays on an + allowed origin, so the next request passes through the tap again. A + protocol-relative or absolute target on any other origin is refused. + ``rewrite_from_origin``/``rewrite_to_origin`` map an absolute upstream + target onto the tap's own origin in reverse-proxy mode. + """ + raw = (location or "").strip() + # Browsers read a backslash as a slash, so ``/\\host`` leaves the origin + # even though URL parsers here treat it as a relative path. + if not raw or any(ch in raw for ch in "\r\n\\"): + return None + resolved = urljoin(request_url, raw) + origin = _normalize_origin(resolved) + if not origin or origin not in allowed_origins: + return None + parts = urlsplit(raw) + if not parts.scheme and not parts.netloc: + return raw + if rewrite_from_origin is not None and rewrite_to_origin is not None: + if origin != rewrite_from_origin: + return None + target = urlsplit(resolved) + rewritten = rewrite_to_origin.rstrip("/") + (target.path or "/") + if target.query: + rewritten += "?" + target.query + if target.fragment: + rewritten += "#" + target.fragment + return rewritten + return raw +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/specs.py b/packages/flow/tests/failopen/selftest/specs.py index 49c913f34d..36b7d7cc56 100644 --- a/packages/flow/tests/failopen/selftest/specs.py +++ b/packages/flow/tests/failopen/selftest/specs.py @@ -41,8 +41,10 @@ _v_s7_cancel_post, _v_s7_cancel_pre, _v_s8_governed_post, + _v_s8_governed_pre, _v_s9_verify_run_pre, _v_wire_tap_post, + _v_wire_tap_pre, ) from tests.failopen.sites import governed_safety, verify_run_folds, wire_tap_relay @@ -146,7 +148,7 @@ def run(ev: dict[str, Any]) -> Any: ) -def undo_spec(mod: Any, id: str) -> SiteSpec: +def undo_spec(mod: Any, id: str, unlisted: bool = False) -> SiteSpec: def ev(*codes: str) -> dict[str, Any]: return {"per_write": {f"w{i}": c for i, c in enumerate(codes)}, "leftover": []} @@ -171,7 +173,7 @@ def ev(*codes: str) -> dict[str, Any]: f"{code} after {prefix}", unknown=True, ) - for code in UNDO_CODES + for code in (*UNDO_CODES, *(("a_code_no_list_names",) if unlisted else ())) for prefix in ((), ("undone",)) ], notes={ @@ -183,6 +185,16 @@ def ev(*codes: str) -> dict[str, Any]: pair("S3_undo_no_undo", undo_spec, _v_s3_undo_pre, _v_s3_undo_post, {"M14"}) +# The fix lists no_undo but keeps the deny-list: a per-write code nobody +# listed still settles as ROLLED_BACK. Pre-only until undo_plan adopts +# from_code (reported to the #2428 owner). +pair( + "S3_undo_unlisted_code", + lambda m, i: undo_spec(m, i, unlisted=True), + _v_s3_undo_post, + None, + {"M14"}, +) # -- S4 written field with no verdict (#2429, fixed by fa26f69fc) ------------------ @@ -410,9 +422,7 @@ def _governed(check: Any, id: str) -> SiteSpec: pair( "S8_governed_note", _governed, - governed_safety.load_check( - governed_safety.ROOT / "scripts/ci/check_windows_governed_safety.py" - ), + _v_s8_governed_pre.check, _v_s8_governed_post.check, {"seed", "M10"}, ) @@ -425,16 +435,10 @@ def _relay(fn: Any, id: str) -> SiteSpec: return wire_tap_relay.relay_spec(fn, id, "selftest") -def _main_relay() -> Any: - from openadapt_flow.tx.wire_tap import relay_redirect_location - - return relay_redirect_location - - pair( "wire_tap_triple_slash", _relay, - _main_relay(), + _v_wire_tap_pre.relay_redirect_location, _v_wire_tap_post.relay_redirect_location, {"M11"}, ) diff --git a/packages/flow/tests/failopen/sites/connector_status.py b/packages/flow/tests/failopen/sites/connector_status.py index 0a993a8e15..310af5c594 100644 --- a/packages/flow/tests/failopen/sites/connector_status.py +++ b/packages/flow/tests/failopen/sites/connector_status.py @@ -85,4 +85,8 @@ def _run(ev: dict[str, Any]) -> Any: "'failed'; needs the connector status from the vocabulary " "(FAIL_CLOSED.md follow-up 3, class of #2300)" ), + known=[ + "M12 P7: RECONCILIATION_REQUIRED/FAILED rc=0: may have changed, reported 'failed'", + "M12 P7: RECONCILIATION_REQUIRED/FAILED rc=1: may have changed, reported 'failed'", + ], ) diff --git a/packages/flow/tests/failopen/sites/governed_safety.py b/packages/flow/tests/failopen/sites/governed_safety.py index 299c51cf9a..452872a915 100644 --- a/packages/flow/tests/failopen/sites/governed_safety.py +++ b/packages/flow/tests/failopen/sites/governed_safety.py @@ -84,4 +84,8 @@ def load_check(path: Path) -> Callable[[Any], list[str]]: "owned", ), xfail="#2258: a held target note changed between '' and NULL reads as no write", + known=[ + "M10 P2: value empty for null: still passes", + "seed P0: held, '' became NULL: pass=True", + ], ) diff --git a/packages/flow/tests/failopen/sites/verify_run_folds.py b/packages/flow/tests/failopen/sites/verify_run_folds.py index 6581fbdd9d..124af95f9e 100644 --- a/packages/flow/tests/failopen/sites/verify_run_folds.py +++ b/packages/flow/tests/failopen/sites/verify_run_folds.py @@ -23,7 +23,7 @@ def _verdicts(codes: list[str]) -> list[Any]: def aggregate_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSpec: return SiteSpec( id=id, - classes="C2 C3", + classes="C2", target="openadapt_flow.verify_run:_aggregate", kind=kind, run=lambda ev: fn(_verdicts(ev)), diff --git a/packages/flow/tests/failopen/sites/wire_tap_relay.py b/packages/flow/tests/failopen/sites/wire_tap_relay.py index f8f0abeb90..1620c13914 100644 --- a/packages/flow/tests/failopen/sites/wire_tap_relay.py +++ b/packages/flow/tests/failopen/sites/wire_tap_relay.py @@ -55,6 +55,11 @@ def _main() -> None: relay_redirect_location, "wire_tap.relay_redirect_location", "owned" ), xfail="#2470: '///host' is relayed raw and a browser reads it as a host", + known=[ + "M11 P3: accepted '///evil.example/x' as '///evil.example/x'", + "M11 P3: accepted '////evil.example/x' as '////evil.example/x'", + "M11 P3: accepted 'http:////evil.example/x' as 'http:////evil.example/x'", + ], ) diff --git a/packages/flow/tests/failopen/test_kernel.py b/packages/flow/tests/failopen/test_kernel.py index 9597aa2163..2c23433f0e 100644 --- a/packages/flow/tests/failopen/test_kernel.py +++ b/packages/flow/tests/failopen/test_kernel.py @@ -229,9 +229,36 @@ def test_from_code_refuses_overlapping_lists() -> None: from_code("x", held=frozenset({"x"}), refuted=frozenset({"x"})) -def test_obligations_dedupe_by_subject_key() -> None: +def test_obligations_dedupe_by_subject_key_and_binding() -> None: + a, b = Subject(key="1", run_id="r1"), Subject(key="1", run_id="r2") + assert Obligations.fix([a, a, b], source="p").items == (a, b) + settled = settle(Obligations.fix([a, b], source="p"), [_result(a, "held")], limit=1) + assert settled.mismatched == (b,) and settled.over_limit and not settled.passes + + +def test_a_stray_result_from_another_run_is_unexpected() -> None: + a = Subject(key="1", run_id="r1") + stray = Subject(key="1", run_id="r2") + settled = settle( + Obligations.fix([a], source="p"), [_result(a, "held"), _result(stray, "held")] + ) + assert settled.held == (a,) and len(settled.unexpected) == 1 and not settled.passes + + +def test_a_held_result_cannot_be_moved_to_another_subject() -> None: + import dataclasses + a = Subject(key="1", run_id="r1") - assert Obligations.fix([a, Subject(key="1", run_id="r2")], source="p").items == (a,) + with pytest.raises(TypeError): + dataclasses.replace(_result(a, "held"), subject=Subject(key="1", run_id="r2")) + + +def test_benign_cannot_map_a_raise_to_a_value() -> None: + def probe() -> object: + raise TimeoutError + + with pytest.raises(TypeError): + observe(probe, benign={TimeoutError: Observed(0)}) @pytest.mark.parametrize( diff --git a/packages/flow/tests/failopen/test_kernel_mutants.py b/packages/flow/tests/failopen/test_kernel_mutants.py index fde998f4da..6cd643f849 100644 --- a/packages/flow/tests/failopen/test_kernel_mutants.py +++ b/packages/flow/tests/failopen/test_kernel_mutants.py @@ -29,8 +29,8 @@ ), "ignore unexpected": (" and not self.unexpected\n", "\n"), "ignore mismatched": ( - " elif any(binding_mismatches(item, r.subject) for r in got):\n", - " elif False:\n", + " got = [r for r in same_key if not binding_mismatches(item, r.subject)]\n", + " got = list(same_key)\n", ), "keep last writer": ( " elif len({r.status for r in got}) > 1:\n conflicting.append(item)\n" @@ -38,9 +38,9 @@ " else:\n buckets[got[-1].status.value].append(item)\n", ), "truncate at limit": ( - " for item in obligations.items:\n", - " obligations = Obligations(obligations.items[:limit], obligations.source)" - " if limit is not None else obligations\n for item in obligations.items:\n", + " used: set[int] = set()\n", + " used: set[int] = set()\n obligations = Obligations(obligations.items[:limit]," + " obligations.source) if limit is not None else obligations\n", ), "observe returns a default": ( " return Errored(type(exc).__name__, str(exc)[:200])\n", diff --git a/packages/flow/tests/failopen/test_registry_complete.py b/packages/flow/tests/failopen/test_registry_complete.py index e7e6d54744..0e0145754d 100644 --- a/packages/flow/tests/failopen/test_registry_complete.py +++ b/packages/flow/tests/failopen/test_registry_complete.py @@ -52,9 +52,18 @@ def test_every_site_spec_targets_its_decorated_function() -> None: continue path, qualname = decorated[spec.id] module, _, target_name = spec.target.partition(":") - assert path == "packages/flow/" + module.replace(".", "/") + ".py", spec.id + expected = ( + module + if module.endswith(".py") + else "packages/flow/" + module.replace(".", "/") + ".py" + ) + if module.split(".")[0] == "openadapt": + expected = module.replace(".", "/") + ".py" + assert path == expected, spec.id assert qualname == target_name, spec.id - assert getattr(_resolve(spec.target), "__verdict_site__", None) == spec.id + target = _resolve(spec.target) + if target is not None: # a script path is checked by its decorator above + assert getattr(target, "__verdict_site__", None) == spec.id def test_owned_and_selftest_targets_exist() -> None: @@ -98,7 +107,9 @@ def test_vendored_lines_match_history_when_it_is_available() -> None: if got.returncode != 0: continue want = "\n".join(got.stdout.splitlines()[int(a) - 1 : int(b)]) - assert textwrap.dedent(block) == textwrap.dedent(want), f"{path.name} {sha}" + assert textwrap.dedent(block).rstrip() == textwrap.dedent(want).rstrip(), ( + f"{path.name} {sha}" + ) checked += 1 if not checked: pytest.skip("no git history for the vendored commits") diff --git a/packages/flow/tests/failopen/test_sites.py b/packages/flow/tests/failopen/test_sites.py index a7c1f3fe5a..d8b33314d8 100644 --- a/packages/flow/tests/failopen/test_sites.py +++ b/packages/flow/tests/failopen/test_sites.py @@ -1,8 +1,10 @@ """Every registered verdict site holds under every generic mutation. -A site an open pull request owns is ``xfail(strict=True)`` with that pull -request in the reason: when its fix lands the test passes unexpectedly, and -the marker has to come out in the same change (FAIL_CLOSED.md, adoption). +A site an open pull request owns lists exactly the failures it has today +(``known``), with the owner in ``xfail``. The test fails on any other failure, +so a known bug can't hide a new one, and it fails when a known failure goes +away, so the list (and in the end the ``owned`` marker) has to come out in the +change that fixes it. That is a strict xfail, per case (FAIL_CLOSED.md). """ from __future__ import annotations @@ -14,19 +16,21 @@ SPECS = {k: v for k, v in load_all().items() if v.kind in ("site", "owned")} -def _param(spec_id: str) -> object: - spec = SPECS[spec_id] - marks = [pytest.mark.xfail(strict=True, reason=spec.xfail)] if spec.xfail else [] - return pytest.param(spec_id, marks=marks, id=spec_id) - - -@pytest.mark.parametrize("spec_id", [_param(k) for k in sorted(SPECS)]) +@pytest.mark.parametrize("spec_id", sorted(SPECS)) def test_site_holds(spec_id: str) -> None: - failures = run_site(SPECS[spec_id]) - assert not failures, "\n".join(str(f) for f in failures) + spec = SPECS[spec_id] + got = {f.key for f in run_site(spec)} + new, fixed = sorted(got - spec.known), sorted(spec.known - got) + assert not new, f"{spec_id}: new failures:\n" + "\n".join(new) + assert not fixed, ( + f"{spec_id}: fixed, remove from known (and the owned marker when empty):\n" + + "\n".join(fixed) + ) -def test_owned_sites_name_their_owner() -> None: +def test_owned_sites_name_their_owner_and_failures() -> None: for spec in SPECS.values(): if spec.kind == "owned": - assert spec.xfail and ("#" in spec.xfail), spec.id + assert spec.xfail and "#" in spec.xfail and spec.known, spec.id + else: + assert not spec.known, spec.id diff --git a/packages/flow/tests/failopen/test_verify_run_migration.py b/packages/flow/tests/failopen/test_verify_run_migration.py index 6375466228..64bac22460 100644 --- a/packages/flow/tests/failopen/test_verify_run_migration.py +++ b/packages/flow/tests/failopen/test_verify_run_migration.py @@ -13,7 +13,9 @@ from tests.failopen.selftest import _v_s9_verify_run_pre as before PROFILE = settings(derandomize=True, max_examples=300, deadline=None) -VERDICTS = st.sampled_from(list(Verdict)) +# The three members the vendored fold knew; a member added later is not +# compared, since the old fold would have called it CONFIRMED. +VERDICTS = st.sampled_from([Verdict.CONFIRMED, Verdict.REFUTED, Verdict.INDETERMINATE]) OBSERVED = st.sampled_from(["present", "absent", "unknown", "conflicting"]) diff --git a/packages/flow/tests/test_verdict_folds_check.py b/packages/flow/tests/test_verdict_folds_check.py index e5aa01fb35..661350a2a4 100644 --- a/packages/flow/tests/test_verdict_folds_check.py +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -38,6 +38,24 @@ def test_closed_except_is_not_a_swallow(tmp_path: Path) -> None: assert "swallow" not in _count(tmp_path, src) +def test_each_exit_of_a_handler_is_judged(tmp_path: Path) -> None: + mixed = "def f(g, x):\n try:\n return g()\n except Exception:\n if x:\n raise\n return True\n" + assert _count(tmp_path, mixed).get("swallow") == 1 + literal = "def f(g):\n try:\n return g()\n except Exception:\n return 'not_checked'\n" + assert "swallow" not in _count(tmp_path, literal) + reraise = "def f(g):\n try:\n return g()\n except Exception:\n raise\n" + assert "swallow" not in _count(tmp_path, reraise) + + +def test_a_site_id_on_two_functions_is_refused(tmp_path: Path) -> None: + path = tmp_path / "m.py" + path.write_text( + "@verdict_site('x', classes='C2')\ndef a(): ...\n@verdict_site('x', classes='C2')\ndef b(): ...\n" + ) + with pytest.raises(ValueError): + folds.decorated_sites(path) + + def test_a_registered_site_is_exempt(tmp_path: Path) -> None: body = "".join(SNIPPETS.values()).replace("def f(", "def g(") src = "@verdict_site('x', classes='C2')\n" + body.replace( @@ -50,11 +68,25 @@ def test_a_registered_site_is_exempt(tmp_path: Path) -> None: def test_only_growth_fails() -> None: base = {"a.py": {"swallow": 2}} assert folds.compare({"a.py": {"swallow": 3}}, base) - assert folds.compare({"b.py": {"swallow": 1}}, base) + assert folds.compare({"a.py": {"swallow": 2}, "b.py": {"swallow": 1}}, base) assert not folds.compare({"a.py": {"swallow": 1}}, base) assert not folds.compare({}, base) +def test_moving_a_fold_to_a_new_module_is_not_growth() -> None: + base = {"big.py": {"swallow": 5, "bool_fold": 1}} + moved = {"big.py": {"swallow": 2}, "big_part.py": {"swallow": 3, "bool_fold": 1}} + assert not folds.compare(moved, base) + grown = folds.compare( + {**moved, "big_part.py": {"swallow": 4, "bool_fold": 1}}, base + ) + assert ( + len(grown) == 1 + and grown[0].startswith("swallow: 6") + and "big_part.py 4" in grown[0] + ) + + def test_the_baseline_only_lowers() -> None: base = {"a.py": {"swallow": 2, "bool_fold": 1}} assert folds.lowered({"a.py": {"swallow": 5}, "b.py": {"swallow": 1}}, base) == { From 2d9b7e0dec28b74999ad4150a433f0bb458ac749 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:28:46 -0500 Subject: [PATCH 03/14] fix(flow): second review round on the verdict kernel and harness - HELD is minted only inside the kernel's constructors, so replace() can't copy or restore it; one result claimed by two obligations conflicts - known failures carry the seed and lens, so a new case can't hide - the ratchet checks every @verdict_site has a spec on every change, finds conditional sites, judges every branch of a returned value, and lowers the baseline per kind so a moved fold keeps its allowance - M7 is out of P1; the S5 seeds plan 20 runs and a gate needing all 20 passes --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/docs/FAIL_CLOSED.md | 5 +- packages/flow/openadapt_flow/verdict.py | 48 ++++++------ packages/flow/openadapt_flow/verdict_sites.py | 7 +- packages/flow/scripts/check_verdict_folds.py | 75 ++++++++++++++++--- .../flow/scripts/verdict_folds_baseline.json | 6 +- packages/flow/tests/failopen/harness.py | 33 +++++--- packages/flow/tests/failopen/mutators.py | 6 +- .../flow/tests/failopen/selftest/specs.py | 19 +++-- .../tests/failopen/sites/connector_status.py | 4 +- .../tests/failopen/sites/governed_safety.py | 4 +- .../tests/failopen/sites/wire_tap_relay.py | 9 ++- packages/flow/tests/failopen/test_kernel.py | 18 ++++- .../tests/failopen/test_kernel_mutants.py | 23 +++--- .../flow/tests/test_verdict_folds_check.py | 25 +++++++ 16 files changed, 207 insertions(+), 79 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index bc5a32ff2b..f1ecddb86b 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -177,7 +177,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | -| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 9 of 9 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/llms-full.txt b/llms-full.txt index 24262397b4..1723b82125 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -611,7 +611,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | -| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 8 of 8 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 9 of 9 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 652a7b4d60..0246392725 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -45,7 +45,8 @@ found didn't stop the next one, so the shapes are now fixed in one place: (system, surface, table, key, field) and the run it belongs to (run id, nonce, digest). A result whose binding disagrees with the obligation is mismatched, so a result from another run or from a decoy table doesn't - count. + count. One result can't settle two obligations: if two claim it, both + are conflicting. 6. **Say who signed only from a verified source.** `trust_label(source, verified=...)` names the signer only for a verified `TrustSource`; anything else is "not verified". @@ -121,7 +122,7 @@ applies to, fails too: | S2 audit read ends at an old-stamped event before the cursor (#2437) | `de5ee3db2^` | `de5ee3db2` | M2, M7 | | S3 a write with no undo counted as rolled back (#2428) | `fda539c78^` | `fda539c78` | M14 | | S4 a written field with no expected value gets no verdict (#2429) | `fa26f69fc^` | `fa26f69fc` | M1 | -| S5 `min_scored=1`; an undelivered fault drops a run from the rates (#2419) | `275199914^` and `275199914` | open | M9 | +| S5 `min_scored=1` passes 1 of 20 planned runs; an undelivered fault drops a run from the rates (#2419) | `275199914^` and `275199914` | open | P0, M9 (relabel, `^` only) | | S6 a type-ahead prefix matches an assumed typed baseline (#2448) | `c329c57dc^` | `c329c57dc` | P0, M11 | | S7 a cancel after the child started is reported as failed (#2300) | `fd7133866` | #2300 head | M12 | | S3b the S3 fix still keeps a deny-list: a per-write code nobody listed is `ROLLED_BACK` | `fda539c78` | open | M14 | diff --git a/packages/flow/openadapt_flow/verdict.py b/packages/flow/openadapt_flow/verdict.py index 276480d7a1..a857c8c7c3 100644 --- a/packages/flow/openadapt_flow/verdict.py +++ b/packages/flow/openadapt_flow/verdict.py @@ -28,7 +28,8 @@ from __future__ import annotations from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass, field, replace +from contextvars import ContextVar +from dataclasses import dataclass, replace from enum import Enum from fractions import Fraction from typing import Optional, Union @@ -201,14 +202,18 @@ def require_bound(expected: Subject, got: Subject) -> None: # -- results ---------------------------------------------------------------------- -#: Only this module's constructors hold it, so ``Result(..., Status.HELD, ...)`` -#: written anywhere else raises. The token is bound to the subject, so -#: ``dataclasses.replace(result, subject=other)`` raises too. -_JUDGED = object() +#: Set only while :meth:`Result.held` or :meth:`Result.from_code` builds a +#: HELD result. ``Result(..., Status.HELD, ...)`` anywhere else raises, and so +#: does ``dataclasses.replace`` on any result that would come out HELD. +_MINTING: ContextVar[bool] = ContextVar("_verdict_minting", default=False) -def _seal(subject: "Subject") -> object: - return (_JUDGED, subject) +def _mint_held(subject: "Subject", reason: str) -> "Result": + token = _MINTING.set(True) + try: + return Result(subject, Status.HELD, reason) + finally: + _MINTING.reset(token) @dataclass(frozen=True) @@ -218,19 +223,11 @@ class Result: subject: Subject status: Status reason: str - _token: object = field(default=None, repr=False, compare=False) def __post_init__(self) -> None: if not isinstance(self.status, Status): raise TypeError(f"status must be a Status, not {self.status!r}") - token = self._token - sealed = ( - isinstance(token, tuple) - and len(token) == 2 - and token[0] is _JUDGED - and token[1] == self.subject - ) - if self.status is Status.HELD and not sealed: + if self.status is Status.HELD and not _MINTING.get(): raise TypeError( "HELD comes only from Result.held or Result.from_code; " "see docs/FAIL_CLOSED.md" @@ -242,7 +239,7 @@ def held(cls, subject: Subject, obs: Observation, reason: str = "") -> "Result": if not isinstance(obs, Observed) or obs.complete is not True: raise TypeError("HELD needs a complete Observed value") - return cls(subject, Status.HELD, reason or "held", _seal(subject)) + return _mint_held(subject, reason or "held") @classmethod def refuted(cls, subject: Subject, obs: Observation, reason: str) -> "Result": @@ -294,7 +291,7 @@ def from_code( status = from_code(code, held=held, refuted=refuted) text = reason or f"code {code!r}" if status is Status.HELD: - return cls(subject, status, text, _seal(subject)) + return _mint_held(subject, text) return cls(subject, status, text) @@ -435,15 +432,22 @@ def settle( } conflicting: list[Subject] = [] used: set[int] = set() - for item in obligations.items: + matches: dict[int, list[Result]] = {} + takers: dict[int, int] = {} + for n, item in enumerate(obligations.items): same_key = by_key.get(item.key_tuple(), []) - got = [r for r in same_key if not binding_mismatches(item, r.subject)] + matches[n] = [r for r in same_key if not binding_mismatches(item, r.subject)] + for r in matches[n]: + takers[id(r)] = takers.get(id(r), 0) + 1 + for n, item in enumerate(obligations.items): + got = matches[n] used.update(id(r) for r in got) - if not same_key: + if not by_key.get(item.key_tuple()): buckets["missing"].append(item) elif not got: buckets["mismatched"].append(item) - elif len({r.status for r in got}) > 1: + elif len({r.status for r in got}) > 1 or any(takers[id(r)] > 1 for r in got): + # Two results that disagree, or one result two obligations claim. conflicting.append(item) else: buckets[got[0].status.value].append(item) diff --git a/packages/flow/openadapt_flow/verdict_sites.py b/packages/flow/openadapt_flow/verdict_sites.py index e78eaa55fd..b180b54c5a 100644 --- a/packages/flow/openadapt_flow/verdict_sites.py +++ b/packages/flow/openadapt_flow/verdict_sites.py @@ -20,16 +20,19 @@ #: ``{site id: the fail-open classes it is tested for}``, filled at import. SITES: dict[str, str] = {} +#: ``{site id: module.qualname}``: one id names one function. +_WHERE: dict[str, str] = {} def verdict_site(id: str, *, classes: str) -> Callable[[F], F]: """Register ``id`` and return the function unchanged.""" def mark(fn: F) -> F: - known = SITES.get(id) - if known is not None and known != classes: + where = f"{getattr(fn, '__module__', '?')}.{getattr(fn, '__qualname__', '?')}" + if _WHERE.get(id, where) != where or SITES.get(id, classes) != classes: raise ValueError(f"verdict site {id!r} registered twice") SITES[id] = classes + _WHERE[id] = where setattr(fn, "__verdict_site__", id) return fn diff --git a/packages/flow/scripts/check_verdict_folds.py b/packages/flow/scripts/check_verdict_folds.py index 7a39f7af34..c2c405adee 100644 --- a/packages/flow/scripts/check_verdict_folds.py +++ b/packages/flow/scripts/check_verdict_folds.py @@ -113,6 +113,9 @@ def visit(node: ast.AST, prefix: str) -> None: ) out[site] = name visit(child, name + ".") + else: + # Inside an ``if``, ``try`` or ``with``: same scope, same prefix. + visit(child, prefix) visit(tree, "") return out @@ -155,16 +158,31 @@ def _names(node: ast.AST) -> Iterator[str]: ) +def _not_checked_value(value: ast.AST) -> bool: + """True when every value the expression can produce is a not-checked one.""" + + if isinstance(value, ast.IfExp): + return _not_checked_value(value.body) and _not_checked_value(value.orelse) + if isinstance(value, ast.Constant): + return value.value in _NOT_CHECKED_STRINGS + if isinstance(value, ast.Name): + return value.id in _NOT_CHECKED_NAMES + if isinstance(value, ast.Attribute): + return value.attr in _NOT_CHECKED_NAMES or value.attr in _NOT_CHECKED_STRINGS + if isinstance(value, ast.Call): + return _not_checked_value(value.func) + if isinstance(value, (ast.Tuple, ast.List)): + return bool(value.elts) and _not_checked_value(value.elts[0]) + return False + + def _closed_exit(node: ast.AST) -> bool: """True for a ``return`` that hands back a not-checked value.""" value = getattr(node, "value", None) if not isinstance(node, ast.Return) or value is None: return False - return any(n in _NOT_CHECKED_NAMES for n in _names(value)) or any( - isinstance(c, ast.Constant) and c.value in _NOT_CHECKED_STRINGS - for c in ast.walk(value) - ) + return _not_checked_value(value) _COUNTING = frozenset({"sum", "len", "Counter", "tally", "count"}) @@ -326,15 +344,41 @@ def compare( def lowered( found: dict[str, dict[str, int]], baseline: dict[str, dict[str, int]] ) -> dict[str, dict[str, int]]: - """The baseline lowered to what is found; never raised.""" + """The baseline lowered to what is found, per kind; a kind's total never + rises. A kind whose total fell (or held) takes the counts found, so a fold + that moved files moves its baseline entry too. A kind whose total rose + keeps its old entries.""" + now, allowed = totals(found), totals(baseline) + source = {k: (found if now[k] <= allowed[k] else baseline) for k in KINDS} out: dict[str, dict[str, int]] = {} - for rel, kinds in baseline.items(): - for kind, allowed in kinds.items(): - n = min(allowed, found.get(rel, {}).get(kind, 0)) - if n: - out.setdefault(rel, {})[kind] = n - return dict(sorted(out.items())) + for kind in KINDS: + for rel, kinds in source[kind].items(): + if kinds.get(kind, 0): + out.setdefault(rel, {})[kind] = kinds[kind] + return {rel: dict(sorted(k.items())) for rel, k in sorted(out.items())} + + +SPEC_ID = re.compile(r"""["']([\w.\-]+)["']""") # any quoted id in a spec file + + +def unregistered_sites(root: Path = ROOT) -> list[str]: + """Decorated sites whose id appears in no spec under tests/failopen/sites. + + The meta-test (tests/failopen/test_registry_complete.py) checks the same + thing and runs the specs, but only when the Flow tests run; this runs on + every change, so a launcher or scripts/ci site can't skip its spec. + """ + + config = load_config() + specs = root / "packages/flow/tests/failopen/sites" + ids = {m for f in specs.glob("*.py") for m in SPEC_ID.findall(f.read_text("utf-8"))} + missing = [] + for path in scope_files(config, root): + for site, name in decorated_sites(path).items(): + if site not in ids: + missing.append(f"{path.relative_to(root).as_posix()}: {name} ({site})") + return missing def main(argv: Optional[list[str]] = None) -> int: @@ -350,6 +394,14 @@ def main(argv: Optional[list[str]] = None) -> int: found = scan() baseline = json.loads(BASELINE.read_text(encoding="utf-8")) grown = compare(found, baseline) + unspecced = unregistered_sites() + if unspecced: + print( + "A @verdict_site has no spec under packages/flow/tests/failopen/sites " + "(docs/FAIL_CLOSED.md, 'Register a site'):", + file=sys.stderr, + ) + print("\n".join(f" {line}" for line in unspecced), file=sys.stderr) if args.update_baseline: BASELINE.write_text( json.dumps(lowered(found, baseline), indent=2) + "\n", encoding="utf-8" @@ -364,6 +416,7 @@ def main(argv: Optional[list[str]] = None) -> int: file=sys.stderr, ) print("\n".join(f" {line}" for line in grown), file=sys.stderr) + if grown or unspecced: return 1 total = sum(n for kinds in baseline.values() for n in kinds.values()) print(f"Verdict folds OK ({total} baseline folds left)") diff --git a/packages/flow/scripts/verdict_folds_baseline.json b/packages/flow/scripts/verdict_folds_baseline.json index d952d92a17..cec7ef7812 100644 --- a/packages/flow/scripts/verdict_folds_baseline.json +++ b/packages/flow/scripts/verdict_folds_baseline.json @@ -793,7 +793,8 @@ }, "packages/flow/openadapt_flow/rl_env/reward.py": { "says_success": 2, - "cmp_literal": 5 + "cmp_literal": 5, + "swallow": 2 }, "packages/flow/openadapt_flow/rl_env/trainers.py": { "swallow": 1 @@ -1087,7 +1088,8 @@ "packages/flow/openadapt_flow/taskgen/validate.py": { "says_success": 1, "cmp_literal": 2, - "bool_fold": 3 + "bool_fold": 3, + "swallow": 2 }, "packages/flow/openadapt_flow/taskgen/workbench.py": { "swallow": 2 diff --git a/packages/flow/tests/failopen/harness.py b/packages/flow/tests/failopen/harness.py index 0ef855712d..4f64a34612 100644 --- a/packages/flow/tests/failopen/harness.py +++ b/packages/flow/tests/failopen/harness.py @@ -37,10 +37,10 @@ P2 = frozenset({"M1", "M2", "M3", "M4", "M5", "M7", "M10", "M14"}) P3 = frozenset({"M8", "M11"}) #: Mutators P1 applies to: each one only removes or corrupts evidence. A -#: value perturbation (M10), a rebuilt set (M2) or a dropped result (M1, which -#: can drop the one bad result) can repair a failing seed, so those are held -#: to P2/P3 only. -P1_IDS = frozenset({"M3", "M4", "M5", "M7", "M8"}) +#: value perturbation (M10), a rebuilt set (M2), a dropped result (M1, which +#: can drop the one bad result) or a duplicate (M7, which can restore a +#: missing pair) can repair a failing seed, so those are held to P2/P3 only. +P1_IDS = frozenset({"M3", "M4", "M5", "M8"}) @dataclass(frozen=True) @@ -224,11 +224,17 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: if not any(seed.correct_pass for seed in seeds): failures.append(Failure(spec.id, "seed", "P0", "no pass seed to mutate")) ran = 0 - for seed in seeds: + for number, seed in enumerate(seeds): + at = f"seed {number}" got = safe_pass(spec, seed.evidence) if got != seed.correct_pass: failures.append( - Failure(spec.id, "seed", "P0", f"{seed.note or 'seed'}: pass={got}") + Failure( + spec.id, + "seed", + "P0", + f"{at} {seed.note}: pass={got}".replace(" ", " "), + ) ) continue for m in mutators.mutations(spec, seed): @@ -238,20 +244,27 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: if m.check is not None: problem = m.check() if problem: - failures.append(Failure(spec.id, m.id, m.prop, problem)) + failures.append(Failure(spec.id, m.id, m.prop, f"{at}: {problem}")) continue after = safe_pass(spec, m.evidence) if not got and after and m.id in P1_IDS: failures.append( - Failure(spec.id, m.id, "P1", f"{m.label}: a not-pass became a pass") + Failure( + spec.id, + m.id, + "P1", + f"{at}: {m.label}: a not-pass became a pass", + ) ) elif got and m.expect == "not_pass" and after: prop = "P3" if m.id in P3 else "P2" failures.append( - Failure(spec.id, m.id, prop, f"{m.label}: still passes") + Failure(spec.id, m.id, prop, f"{at}: {m.label}: still passes") ) elif m.expect == "same" and after != got: - failures.append(Failure(spec.id, m.id, "P4", f"{m.label}: changed")) + failures.append( + Failure(spec.id, m.id, "P4", f"{at}: {m.label}: changed") + ) if not ran and only is None: failures.append(Failure(spec.id, "spec", "P0", "no mutation applies")) return failures diff --git a/packages/flow/tests/failopen/mutators.py b/packages/flow/tests/failopen/mutators.py index bbad760d87..63a24e8691 100644 --- a/packages/flow/tests/failopen/mutators.py +++ b/packages/flow/tests/failopen/mutators.py @@ -144,7 +144,7 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: spec.subject.set(ev, "other-run"), "not_pass", ) - for lens in spec.values: + for which, lens in enumerate(spec.values): try: current = lens.get(ev) except (KeyError, IndexError, TypeError): @@ -152,7 +152,9 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: for label, value in perturbations(current): if label in spec.equivalent: continue - yield Mutation("M10", f"value {label}", lens.set(ev, value), "not_pass") + yield Mutation( + "M10", f"value {which} {label}", lens.set(ev, value), "not_pass" + ) if spec.corpus is not None: for entry in spec.corpus_entries(): mutated = spec.corpus.apply(ev, entry) diff --git a/packages/flow/tests/failopen/selftest/specs.py b/packages/flow/tests/failopen/selftest/specs.py index 36b7d7cc56..f5bdf43e45 100644 --- a/packages/flow/tests/failopen/selftest/specs.py +++ b/packages/flow/tests/failopen/selftest/specs.py @@ -263,7 +263,8 @@ def _meta(repetitions: int) -> dict[str, Any]: } -def _gate_ev(scored: int) -> dict[str, Any]: +def _gate_ev(scored: int, base_scored: int = 20) -> dict[str, Any]: + """Twenty runs planned: two scenarios, ten repetitions.""" base = { "schema": "openadapt.agent-test.baseline/v1", "app": "app", @@ -272,8 +273,8 @@ def _gate_ev(scored: int) -> dict[str, Any]: "images": ["img"], "agent": "agent", "repetitions": 10, - "scored": 10, - "rates": _summary(10)["rates"], + "scored": base_scored, + "rates": _summary(base_scored)["rates"], } return { "results": {"meta": _meta(10), "summary": _summary(scored)}, @@ -297,15 +298,17 @@ def call(ev: dict[str, Any], min_scored: Any = None) -> Any: kind="selftest", run=call, is_pass=lambda out: out["verdict"] == "pass", - seeds=lambda: [Seed(_gate_ev(10), True)], - # Twenty runs were planned (two scenarios, ten repetitions). + seeds=lambda: [ + Seed(_gate_ev(20), True, "all 20 planned runs scored"), + Seed(_gate_ev(1, 1), False, "1 of 20 planned runs scored"), + ], knob=Knob("min_scored", None, (20,), call), - relabel=lambda ev: _gate_ev(9), + relabel=lambda ev: _gate_ev(18), ) -pair("S5_gate_min_scored", gate_spec, _v_s5_gate_pre, None, {"M9"}) -pair("S5_gate_head", gate_spec, _v_s5_gate_head, None, {"M9"}) +pair("S5_gate_min_scored", gate_spec, _v_s5_gate_pre, None, {"seed", "M9"}) +pair("S5_gate_head", gate_spec, _v_s5_gate_head, None, {"seed"}) # -- S6 type-ahead leading part (#2448, fixed by c329c57dc) ------------------------ diff --git a/packages/flow/tests/failopen/sites/connector_status.py b/packages/flow/tests/failopen/sites/connector_status.py index 310af5c594..beab0b242a 100644 --- a/packages/flow/tests/failopen/sites/connector_status.py +++ b/packages/flow/tests/failopen/sites/connector_status.py @@ -86,7 +86,7 @@ def _run(ev: dict[str, Any]) -> Any: "(FAIL_CLOSED.md follow-up 3, class of #2300)" ), known=[ - "M12 P7: RECONCILIATION_REQUIRED/FAILED rc=0: may have changed, reported 'failed'", - "M12 P7: RECONCILIATION_REQUIRED/FAILED rc=1: may have changed, reported 'failed'", + "M12 P7: seed 0: RECONCILIATION_REQUIRED/FAILED rc=0: may have changed, reported 'failed'", + "M12 P7: seed 0: RECONCILIATION_REQUIRED/FAILED rc=1: may have changed, reported 'failed'", ], ) diff --git a/packages/flow/tests/failopen/sites/governed_safety.py b/packages/flow/tests/failopen/sites/governed_safety.py index 452872a915..af04388de1 100644 --- a/packages/flow/tests/failopen/sites/governed_safety.py +++ b/packages/flow/tests/failopen/sites/governed_safety.py @@ -85,7 +85,7 @@ def load_check(path: Path) -> Callable[[Any], list[str]]: ), xfail="#2258: a held target note changed between '' and NULL reads as no write", known=[ - "M10 P2: value empty for null: still passes", - "seed P0: held, '' became NULL: pass=True", + "M10 P2: seed 0: value 0 empty for null: still passes", + "seed P0: seed 2 held, '' became NULL: pass=True", ], ) diff --git a/packages/flow/tests/failopen/sites/wire_tap_relay.py b/packages/flow/tests/failopen/sites/wire_tap_relay.py index 1620c13914..6ef0b57fd3 100644 --- a/packages/flow/tests/failopen/sites/wire_tap_relay.py +++ b/packages/flow/tests/failopen/sites/wire_tap_relay.py @@ -56,9 +56,12 @@ def _main() -> None: ), xfail="#2470: '///host' is relayed raw and a browser reads it as a host", known=[ - "M11 P3: accepted '///evil.example/x' as '///evil.example/x'", - "M11 P3: accepted '////evil.example/x' as '////evil.example/x'", - "M11 P3: accepted 'http:////evil.example/x' as 'http:////evil.example/x'", + "M11 P3: seed 0: accepted '///evil.example/x' as '///evil.example/x'", + "M11 P3: seed 0: accepted '////evil.example/x' as '////evil.example/x'", + "M11 P3: seed 0: accepted 'http:////evil.example/x' as 'http:////evil.example/x'", + "M11 P3: seed 1: accepted '///evil.example/x' as '///evil.example/x'", + "M11 P3: seed 1: accepted '////evil.example/x' as '////evil.example/x'", + "M11 P3: seed 1: accepted 'http:////evil.example/x' as 'http:////evil.example/x'", ], ) diff --git a/packages/flow/tests/failopen/test_kernel.py b/packages/flow/tests/failopen/test_kernel.py index 2c23433f0e..e8e0b64ae4 100644 --- a/packages/flow/tests/failopen/test_kernel.py +++ b/packages/flow/tests/failopen/test_kernel.py @@ -245,12 +245,26 @@ def test_a_stray_result_from_another_run_is_unexpected() -> None: assert settled.held == (a,) and len(settled.unexpected) == 1 and not settled.passes -def test_a_held_result_cannot_be_moved_to_another_subject() -> None: +def test_a_held_result_cannot_be_copied_or_restored() -> None: import dataclasses a = Subject(key="1", run_id="r1") + held = _result(a, "held") with pytest.raises(TypeError): - dataclasses.replace(_result(a, "held"), subject=Subject(key="1", run_id="r2")) + dataclasses.replace(held, subject=Subject(key="1", run_id="r2")) + with pytest.raises(TypeError): + dataclasses.replace(held, reason="again") + refuted = dataclasses.replace(held, status=Status.REFUTED) + with pytest.raises(TypeError): + dataclasses.replace(refuted, status=Status.HELD) + + +def test_one_result_cannot_satisfy_two_obligations() -> None: + unbound, bound = Subject(key="1"), Subject(key="1", run_id="r") + settled = settle( + Obligations.fix([unbound, bound], source="p"), [_result(bound, "held")] + ) + assert not settled.passes and set(settled.conflicting) == {unbound, bound} def test_benign_cannot_map_a_raise_to_a_value() -> None: diff --git a/packages/flow/tests/failopen/test_kernel_mutants.py b/packages/flow/tests/failopen/test_kernel_mutants.py index 6cd643f849..806f5c211f 100644 --- a/packages/flow/tests/failopen/test_kernel_mutants.py +++ b/packages/flow/tests/failopen/test_kernel_mutants.py @@ -29,13 +29,16 @@ ), "ignore unexpected": (" and not self.unexpected\n", "\n"), "ignore mismatched": ( - " got = [r for r in same_key if not binding_mismatches(item, r.subject)]\n", - " got = list(same_key)\n", + " matches[n] = [r for r in same_key if not binding_mismatches(item, r.subject)]\n", + " matches[n] = list(same_key)\n", ), - "keep last writer": ( - " elif len({r.status for r in got}) > 1:\n conflicting.append(item)\n" - " else:\n buckets[got[0].status.value].append(item)\n", - " else:\n buckets[got[-1].status.value].append(item)\n", + "one writer wins": ( + " elif len({r.status for r in got}) > 1 or any(takers[id(r)] > 1 for r in got):\n", + " elif any(takers[id(r)] > 1 for r in got):\n", + ), + "a shared result counts twice": ( + " elif len({r.status for r in got}) > 1 or any(takers[id(r)] > 1 for r in got):\n", + " elif len({r.status for r in got}) > 1:\n", ), "truncate at limit": ( " used: set[int] = set()\n", @@ -84,9 +87,11 @@ def fix(*items: object) -> object: assert not v.settle(fix(bound), [held(S(key="a", run_id="run-2"))]).passes, ( "run ignored" ) - assert not v.settle(fix(a), [R.refuted(a, v.Observed(0), "x"), held(a)]).passes, ( - "last writer" - ) + refuted_a = R.refuted(a, v.Observed(0), "x") + for pair in ([refuted_a, held(a)], [held(a), refuted_a]): + assert not v.settle(fix(a), pair).passes, "one writer wins" + shared = S(key="a", run_id="r") + assert not v.settle(fix(a, shared), [held(shared)]).passes, "one result, two claims" many = [S(key=str(i)) for i in range(5)] results = [held(s) for s in many[:-1]] + [R.refuted(many[-1], v.Observed(0), "x")] settled = v.settle(fix(*many), results, limit=3) diff --git a/packages/flow/tests/test_verdict_folds_check.py b/packages/flow/tests/test_verdict_folds_check.py index 661350a2a4..add50fc003 100644 --- a/packages/flow/tests/test_verdict_folds_check.py +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -43,6 +43,10 @@ def test_each_exit_of_a_handler_is_judged(tmp_path: Path) -> None: assert _count(tmp_path, mixed).get("swallow") == 1 literal = "def f(g):\n try:\n return g()\n except Exception:\n return 'not_checked'\n" assert "swallow" not in _count(tmp_path, literal) + mixed_exp = "def f(g, ok):\n try:\n return g()\n except Exception:\n return True if ok else 'unknown'\n" + assert _count(tmp_path, mixed_exp).get("swallow") == 1 + attr = "def f(g):\n try:\n return g()\n except Exception:\n return Verdict.INDETERMINATE\n" + assert "swallow" not in _count(tmp_path, attr) reraise = "def f(g):\n try:\n return g()\n except Exception:\n raise\n" assert "swallow" not in _count(tmp_path, reraise) @@ -94,6 +98,27 @@ def test_the_baseline_only_lowers() -> None: } +def test_lowering_after_a_move_keeps_the_moved_fold() -> None: + base = {"a.py": {"swallow": 2}} + moved = {"a.py": {"swallow": 1}, "b.py": {"swallow": 1}} + new = folds.lowered(moved, base) + assert new == moved and not folds.compare(moved, new) + + +def test_every_decorated_site_has_a_spec_id() -> None: + assert folds.unregistered_sites() == [] + + +def test_a_conditional_site_is_found(tmp_path: Path) -> None: + path = tmp_path / "m.py" + path.write_text( + "import sys\nif sys:\n @verdict_site('x', classes='C2')\n def a(): ...\n" + "else:\n @verdict_site('x', classes='C2')\n def b(): ...\n" + ) + with pytest.raises(ValueError): + folds.decorated_sites(path) + + def test_main_is_within_the_baseline() -> None: import json From f77c4cb7fcc7a06cfba8159c74d945cfe3cd7eb9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:27:29 -0500 Subject: [PATCH 04/14] fix(flow): settle the positive controls, verify-run folds and receipt lines on the kernel - check_verdict_folds: count a broad handler that falls through, leaves by break, or names Exception in a tuple or by attribute (swallow_wide); add says_unchanged and empty_change_set for "nothing else changed" claims; a file that doesn't parse fails; a spec id is an id= or factory argument. - verdict: count the obligations that claim a result, not repeats of it; add Result.nothing_else (any change refutes, zero holds only on a complete read). - harness: three-level monotonicity (P6), M7 appends a separate equal copy, M3 says when the plan is kept, M15 partial "nothing else" read, M16 a result turned bad. - hard_invariants and versions build verdicts with settle; versions no longer lets a duplicate or missing-history row hide another author. - verify_run._aggregate/_observed settle against cfg.effects; receipt_record._line and _tally_lines move onto the kernel. - wire_tap is a registered site now that #2470 merged. - Baseline measured again after merging main; every kind is at or below a clean origin/main. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/CHANGELOG.md | 27 +- packages/flow/docs/FAIL_CLOSED.md | 151 +++- .../flow/openadapt_flow/hard_invariants.py | 123 ++- .../flow/openadapt_flow/receipt_record.py | 119 ++- .../runtime/effects/versions.py | 298 ++++--- packages/flow/openadapt_flow/tx/wire_tap.py | 2 + packages/flow/openadapt_flow/verdict.py | 45 +- packages/flow/openadapt_flow/verify_run.py | 98 ++- packages/flow/scripts/check_verdict_folds.py | 186 ++++- packages/flow/scripts/verdict_folds.toml | 20 + .../flow/scripts/verdict_folds_baseline.json | 778 ++++++++++++------ packages/flow/tests/failopen/harness.py | 63 +- packages/flow/tests/failopen/mutators.py | 41 +- .../selftest/_v_hard_invariants_pre.py | 162 ++++ .../failopen/selftest/_v_receipt_lines_pre.py | 99 +++ .../failopen/selftest/_v_versions_pre.py | 265 ++++++ .../flow/tests/failopen/selftest/specs.py | 7 +- .../tests/failopen/sites/hard_invariants.py | 10 +- .../tests/failopen/sites/receipt_lines.py | 144 ++++ .../tests/failopen/sites/verify_run_folds.py | 86 +- .../tests/failopen/sites/versions_judge.py | 2 + .../tests/failopen/sites/wire_tap_relay.py | 19 +- packages/flow/tests/failopen/test_kernel.py | 35 + .../tests/failopen/test_kernel_mutants.py | 27 +- .../test_positive_control_migration.py | 164 ++++ .../failopen/test_receipt_lines_migration.py | 96 +++ packages/flow/tests/failopen/test_sites.py | 8 + .../failopen/test_verify_run_migration.py | 39 +- packages/flow/tests/test_tx_wire_tap.py | 5 + .../flow/tests/test_verdict_folds_check.py | 68 ++ 32 files changed, 2651 insertions(+), 540 deletions(-) create mode 100644 packages/flow/tests/failopen/selftest/_v_hard_invariants_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_receipt_lines_pre.py create mode 100644 packages/flow/tests/failopen/selftest/_v_versions_pre.py create mode 100644 packages/flow/tests/failopen/sites/receipt_lines.py create mode 100644 packages/flow/tests/failopen/test_positive_control_migration.py create mode 100644 packages/flow/tests/failopen/test_receipt_lines_migration.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index c4e4cd9667..c41d3a6527 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -178,7 +178,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | -| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 9 of 9 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 15 generic mutations against every registered `@verdict_site` and checks the verdict at three levels (refuted, not checked, held); and a CI ratchet that fails when the repository-wide count of a hand-written fold kind rises, including swallowed exceptions and "nothing else changed" tests over a possibly partial read | On main | Synthetic: the harness flags 14 fail-open bugs rebuilt from this repository's history (pinned pre-fix copies) plus one live connector site, and passes every fix; 8 registered sites (the hard-invariant layer, the version check, `verify-run`'s folds and the receipt's line judge and tally among them) and 2 owned; 12 of 12 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | 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. 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/llms-full.txt b/llms-full.txt index 10662c00ae..175d7ad35c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -618,7 +618,7 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | -| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 13 generic mutations against every registered `@verdict_site`; and a CI ratchet that fails when a file gains a hand-written fold | On main | Synthetic: the harness flags 15 fail-open bugs rebuilt from this repository's own code (pinned pre-fix copies, three of them still live on main) and passes every fix; 9 of 9 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 15 generic mutations against every registered `@verdict_site` and checks the verdict at three levels (refuted, not checked, held); and a CI ratchet that fails when the repository-wide count of a hand-written fold kind rises, including swallowed exceptions and "nothing else changed" tests over a possibly partial read | On main | Synthetic: the harness flags 14 fail-open bugs rebuilt from this repository's history (pinned pre-fix copies) plus one live connector site, and passes every fix; 8 registered sites (the hard-invariant layer, the version check, `verify-run`'s folds and the receipt's line judge and tally among them) and 2 owned; 12 of 12 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | 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. 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 4a2a16223d..8253240692 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -23,12 +23,19 @@ evidence into held, refuted or not checked. It fixes the obligations from the plan first, settles results against them, and never passes an empty set, a truncated or short read, a probe that raised, a result bound to - another run, two results that disagree, or a code nobody listed. Functions - marked `@verdict_site` are run by a fail-open harness - (`tests/failopen`) with 13 generic mutations; it flags 15 fail-open bugs - rebuilt from this repository's code and passes their fixes. - `scripts/check_verdict_folds.py` fails CI when a file gains a hand-written - fold. See `docs/FAIL_CLOSED.md`. + another run, two results that disagree, or a code nobody listed. + `Result.nothing_else` holds a "nothing else changed" claim only on a + complete read. Functions marked `@verdict_site` are run by a fail-open + harness (`tests/failopen`) with 15 generic mutations, which checks the + verdict at three levels (refuted, not checked, held), not as one bit. It + flags 14 fail-open bugs rebuilt from this repository's history (pinned + pre-fix copies) and one live connector site, and passes their fixes. + `scripts/check_verdict_folds.py` fails CI when the repository-wide count of + a hand-written fold kind rises, including a broad `except` that logs and + falls through and a "nothing else changed" test over a set that may be a + partial read. See `docs/FAIL_CLOSED.md`. +- The hard-invariant layer, the frame's version check, `verify-run`'s effect + folds and the receipt's line judge and tally are built on the kernel. ### Fixes @@ -36,6 +43,14 @@ one with the effects, is `INDETERMINATE`, `unknown` and `unchecked`, not `CONFIRMED`, `present` and `independent_readback`. The receipt model already refuses an empty list, so no run changes outcome today. +- `verify-run`: the effect folds settle against the planned effects, so a + planned effect with no verdict is `INDETERMINATE`, and an observed-effect + code nobody listed is `unknown` rather than `present`. +- The frame's version check: a duplicate version row, a version history + that lost a row, or a changed target with no new version no longer hides a + version saved by another user. The frame is refuted instead of not checked. +- Receipts: a line check nobody listed keeps the run from `VERIFIED` and is + counted as not checked, so the three line counts add up to the lines. ## v3.4.0 (2026-11-21) diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 0246392725..e60956b63b 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -55,7 +55,15 @@ found didn't stop the next one, so the shapes are now fixed in one place: 8. **Each site states its own failure order.** `Settlement.label(precedence=...)` returns `HELD` only when the settlement passes; otherwise it returns the first status in the site's order that applies. The kernel doesn't impose one - total order, because that would silently relabel existing results. + total order, because that would silently relabel existing results. The + harness ranks REFUTED < NOT_CHECKED < HELD unless the spec says, with a + reason, that an unread result outranks a refuted one (P6). +9. **"Nothing else changed" holds only on a complete read.** + `Result.nothing_else(subject, Observed(count, complete=...))` takes the + number of changes a read found outside what was allowed: one or more + refutes, even on a partial read; zero holds only when the read was + complete. A frame, a "no undeclared delete" or a rollback check is one of + these, never `not changes` over whatever the read returned. ## Register a site @@ -90,22 +98,37 @@ a decorated function. |---|---|---| | M1 | drop a result, keep the plan | not pass | | M2 | grow to the limit plus one, the last result bad | not pass | -| M3 | no results, no plan | not pass (unless the spec says an empty set is vacuous, with the reason) | +| M3 | no results and no plan (a vacuous spec keeps the plan) | not pass (unless the spec says an empty set is vacuous, with the reason) | | M4 | the probe raises `Exception`, `TimeoutError`, an HTTP 503 | not pass | | M5 | a required field missing or null | not pass | | M6 | reorder the results | change nothing | -| M7 | repeat a result; repeat it with a bad copy | not improve; not pass | +| M7 | repeat a result as a separate equal copy; repeat it with a bad copy | not raise the level; not pass | | M8 | a result bound to another run | not pass | | M9 | sweep a knob; relabel a scored run as not scored | the default is the strictest value; not pass | | M10 | perturb a value: prefix, superstring, `''`, null, absent, number for string | not pass | | M11 | a corpus entry (`corpus/urls.json`, `corpus/values.json`) | not accepted | | M12 | an outcome after delivery that may have changed something | not reported as a plain failure or as nothing changed | | M14 | a code no list names | not pass | +| M15 | a "nothing else changed" read marked partial | not pass | +| M16 | on a pass seed, the first result turned bad | not pass, not raise the level | On every seed the site must give the correct answer (P0), and a mutation that only removes or corrupts evidence must never turn a not-pass into a pass (P1). -A crash counts as a not-pass. M13, a trust-source swap, waits for the signer -vectors (follow-up 5). +A crash counts as a not-pass. + +The verdict has three levels, not one bit (P6). A spec gives `level`, and the +harness ranks REFUTED < NOT_CHECKED < HELD. A mutation that keeps every +result and adds a copy or turns one bad (M7, M16) must not raise the level +at all. A reordering (M6) leaves the level +exactly where it was. A mutation that removes evidence (M1, M3, M4, M5, M8, +M10) may move REFUTED to NOT_CHECKED, because the refutation it removed is no +longer known, but never to HELD. A site whose order puts an unread result +below a refuted one says so in `precedence` with the reason in +`notes["precedence"]` (a test enforces the note). `verify_run`'s folds and +`receipt_record._line` do: an effect that wasn't read may have landed, so the +run says "check the record" rather than "refuted" (C7). + +M13, a trust-source swap, waits for the signer vectors (follow-up 5). ## The self-test @@ -127,20 +150,19 @@ applies to, fails too: | S7 a cancel after the child started is reported as failed (#2300) | `fd7133866` | #2300 head | M12 | | S3b the S3 fix still keeps a deny-list: a per-write code nobody listed is `ROLLED_BACK` | `fda539c78` | open | M14 | | S8 `''` and NULL in the governed check (#2258) | main at `576f87b41` | `00a55cc16` | P0, M10 | -| Wire tap relays `///host` raw (#2470) | main at `576f87b41` | #2470 head | M11 | +| Wire tap relays `///host` raw (#2470, merged; the live site is now registered) | main at `576f87b41` | #2470 head | M11 | | S9 `verify_run` folds pass an empty effect list | main before this change | main | M1, M3 | The pre-fix controls are pinned copies, never live code, so landing a fix on main can't turn a control green. -Three sites on main are still fail-open and are owned by open pull requests. +Two sites on main are still fail-open and are owned by open pull requests. Their specs are `owned`: they name the owner and list exactly the failures the site has today. This is a strict xfail per case. A new failure fails the test, so a known bug can't hide another one. A known failure that goes away also fails it, so the list, and then the `owned` marker, comes out in the change that fixes the site. -- `wire_tap.relay_redirect_location`: `///evil.example/x` is relayed raw (#2470). - `governed_safety.check`: a held target note changed between `''` and NULL reads as no write (#2258). - `connector.status_from_report`: a report whose `transaction_outcome` is @@ -150,17 +172,46 @@ that fixes the site. ## The ratchet `scripts/check_verdict_folds.py` runs in the required `ci` check, in the smoke -job that runs on every change, next to the file-size ratchet. It counts, in `openadapt_flow/`, the -launcher and `scripts/ci/`, six kinds of hand-written fold: a success literal -produced in code (`VERIFIED`, `CONFIRMED`, `held`, ...), a compare against an -outcome literal, `all()`/`any()` over verdicts or results, a broad `except` -that returns without a raise or a not-checked value, a slice in a statement -that counts, and a final `else` that assigns success. It fails only when the -total for a kind rises above `verdict_folds_baseline.json`, and then lists the -files whose count rose. Totals decide, so moving code into a new module (as -the decomposition plan asks) is not a new fold. It never fails on a drop; run -it with `--update-baseline` to lower the baseline. To add verdict code, put it -in a `@verdict_site` with a spec; the ratchet doesn't count inside one. +job that runs on every change, next to the file-size ratchet. It counts, in +`openadapt_flow/`, the launcher and `scripts/ci/`, these kinds of hand-written +fold: + +| Kind | What it counts | +|---|---| +| `says_success` | a success literal produced in code (`VERIFIED`, `CONFIRMED`, `held`, ...) | +| `cmp_literal` | a compare against an outcome literal | +| `bool_fold` | `all()`/`any()` over verdicts, results, checks, effects, lines or tiers | +| `swallow` | `except Exception` (or bare) with a `return`, `continue` or `pass` that hands back no not-checked value | +| `swallow_wide` | what `swallow` misses: a broad handler that falls through (`except Exception: logger.error(...)` and carry on), leaves by `break`, or names `Exception` in a tuple or by attribute | +| `slice_count` | a slice in a statement that counts | +| `else_success` | a final `else` that assigns success | +| `says_unchanged` | a "nothing changed" literal produced in code (`unchanged`, `no_change`, `ROLLED_BACK`, ...) | +| `empty_change_set` | `not changes`, `len(collateral) == 0`, `deleted == []`, `not any(diffs)`: a "nothing else changed" verdict computed from a set that may be a partial read | + +A handler that re-raises, returns a not-checked value, or records one +(`status = "not_checked"`, `out.append(Errored(...))`) before falling through +is not a swallow. A file the check can't parse fails it, rather than counting +as a file with no folds. + +The check fails only when the repository-wide total for a kind rises above +`verdict_folds_baseline.json`, and then lists the files whose count rose. +Totals decide, so moving code into a new module (as the decomposition plan +asks) is not a new fold. It never fails on a drop; run it with +`--update-baseline` to lower the baseline. The static count can't tell a +complete read from a partial one, so a site that says nothing else changed +also gets M15 in the harness. + +It also fails when a `@verdict_site` has no spec. A spec's id is an `id=` +argument, or a string passed to the spec factory given to `register(...)`; +any other quoted word in a spec file doesn't count. + +The baseline was measured again on this branch after merging main at +`9b6956be3`, because main had gained folds after the first measurement. For +every kind the branch's count is at or below a clean `origin/main` measured +with the same detector, so no kind's allowance rose above main's. + +To add verdict code, put it in a `@verdict_site` with a spec; the ratchet +doesn't count inside one. ## Review rule @@ -169,12 +220,12 @@ spec, not by a local patch. A reviewer who finds one asks for the spec. ## Follow-ups -1. Owners adopt: #2429, #2258, #2470 and #2300 replace their local patch with - `settle` plus a spec and remove the strict xfail. The stacked pull requests - (#2437, #2394, #2428, #2457, #2413, #2419, #2414, #2448) register their - sites when they rebase. -2. One owner for `receipt_record`; the #2394 and #2437 stacks carry copies - that have diverged. +1. Owners adopt: #2429, #2258 and #2300 replace their local patch with + `settle` plus a spec and remove the strict xfail (#2470 has merged and its + site is registered). The stacked pull requests (#2437, #2428, #2457, + #2413, #2419, #2414, #2448) register their sites when they rebase. +2. `receipt_record`'s line judge and tally are on the kernel now (#2394 has + merged); the #2437 stack rebases onto them. 3. A connector `unknown` status derived from `outcomes.json` `may_have_changed`, with a control-plane contract bump. 4. `confirms()` and `changed()` over `readback_values.compare_value`, keeping @@ -189,3 +240,53 @@ spec, not by a local patch. A reviewer who finds one asks for the spec. 11. A nightly real-app lane for the negative controls: a database killed mid-read, a short audit page, a decoy table, a cancel after delivery, a cross-origin redirect. + +## Migration checklist + +The sites below fold evidence by hand and belong to one of the classes +above. Each moves onto `settle` (or `Result.nothing_else` for a "nothing else +changed" claim), gets `@verdict_site` and a spec, and keeps its behaviour +except where a fail-open is fixed, with a differential test against the old +copy. Tick a row in the pull request that moves it. + +Done: + +- [x] `hard_invariants.judge_hard_invariants` (C2 C5): three obligations; + "no outside-scope change" and "no undeclared delete" on + `Result.nothing_else`; a hand-written "held" no longer holds. Unchanged on + every small input. +- [x] `runtime/effects/versions.judge_versions` (C1 C5): one obligation for + the reads and one per target. Fix: a duplicate, missing-history or + no-new-version row no longer hides a version by someone else (refuted, not + "not checked"). +- [x] `verify_run._aggregate` and `_observed` (C1 C2): settled against the + planned effects (`cfg.effects`), so a missing or unplanned verdict never + passes. Fix: an observed code nobody listed is `unknown`, not `present`. +- [x] `receipt_record._line` (C1 C3): declared contract hashes are the + obligations. Unchanged on every generated input. +- [x] `receipt_record._tally_lines` (C2 C3): fix: a line check nobody listed + keeps the run from VERIFIED and counts as not checked. +- [x] `tx/wire_tap.relay_redirect_location` (C6): registered after #2470. + +Next, most bug-prone first: + +- [ ] `verify_run.judge_run_frame` and the frame merge in `verify_run` (C1 C2): + the main "nothing else changed" verdict; status literals merged by hand. +- [ ] `runtime/effects/history.judge_initial_history` (C1 C2): a history + frame over a read window. +- [ ] `verify_run.readback_class` (C1 C2): registered, still `all()`/`any()`. +- [ ] `scripts/ci/check_windows_governed_safety.check` (C5, owned by #2258). +- [ ] `connector.executor.status_from_report` (C7, owned; follow-up 3). +- [ ] `txplan.engine.undo_plan` (C3): the per-write deny-list (S3b). +- [ ] `tx/lens.py` final `else: outcome = "CONFIRMED"` (C3, follow-up 8). +- [ ] `txplan.audit.AuditReader.after` (C1, S2; #2437 stack). +- [ ] `form_tx.judge.SummaryJudge.evaluate` and + `form_tx.reconciler._control_matches_fact` (C1 C5; #2429, #2448). +- [ ] `agent_test.gate.compare` (C4: `min_scored`; S5, follow-up 6). +- [ ] `receipt_record._approval` (C4): the weakest approver by `all()`. +- [ ] `public_seal._checks` (C1): `min(confirmed, required)` clamps instead of + settling. +- [ ] `readback_values.compare_value` users `confirms()`/`changed()` (C5, + follow-up 4). +- [ ] provenance and signer labels (C4, follow-up 5, then M13). +- [ ] `safe_url` in Python and JS (C6, follow-up 7). diff --git a/packages/flow/openadapt_flow/hard_invariants.py b/packages/flow/openadapt_flow/hard_invariants.py index 6ac8bb0ed3..8796f3a89e 100644 --- a/packages/flow/openadapt_flow/hard_invariants.py +++ b/packages/flow/openadapt_flow/hard_invariants.py @@ -8,9 +8,17 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Literal, Optional, TypeGuard +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Status, + Subject, + settle, +) from openadapt_flow.verdict_sites import verdict_site InvariantName = Literal["declared_scope", "at_most_one", "no_undeclared_deletes"] @@ -18,12 +26,37 @@ LAYER_SCHEMA = "openadapt.hard-invariants/v1" +NAMES: tuple[InvariantName, ...] = ( + "declared_scope", + "at_most_one", + "no_undeclared_deletes", +) +#: The three obligations, fixed before any reader runs. +_OBLIGATIONS = Obligations.fix( + (Subject(surface="hard_invariants", key=name) for name in NAMES), + source="hard_invariants", +) + + @dataclass(frozen=True) class InvariantResult: name: InvariantName status: InvariantStatus reason: str observed_count: Optional[int] = None + #: The kernel result this check was judged as. Only a check built by + #: :func:`judge_hard_invariants` carries one, so a hand-written "held" + #: can't make the layer hold. + result: Optional[Result] = field(default=None, compare=False, repr=False) + + def _kernel(self) -> Result: + subject = Subject(surface="hard_invariants", key=self.name) + if self.result is not None and self.result.subject == subject: + return self.result + if self.status == "refuted": + # A refutation needs no complete read: one violation is enough. + return Result.refuted(subject, Observed(None, complete=False), self.reason) + return Result.not_checked(subject, "not judged by the kernel") def evidence(self) -> dict[str, object]: return { @@ -40,16 +73,17 @@ class HardInvariantVerdict: @property def status(self) -> InvariantStatus: - if any(c.status == "refuted" for c in self.checks): - return "refuted" - if ( - {c.name for c in self.checks} - != {"declared_scope", "at_most_one", "no_undeclared_deletes"} - or len(self.checks) != 3 - or any(c.status != "held" for c in self.checks) - ): - return "not_checked" - return "held" + """Held only when each of the three invariants held, once. One + refutation refutes; anything missing, repeated or extra is not + checked.""" + + settled = settle(_OBLIGATIONS, (c._kernel() for c in self.checks)) + labels: dict[Status, InvariantStatus] = { + Status.HELD: "held", + Status.REFUTED: "refuted", + Status.NOT_CHECKED: "not_checked", + } + return labels[settled.label(precedence=(Status.REFUTED, Status.NOT_CHECKED))] def evidence(self) -> dict[str, object]: return { @@ -64,6 +98,17 @@ def _count(value: object) -> TypeGuard[int]: return isinstance(value, int) and not isinstance(value, bool) and value >= 0 +def _invariant( + name: InvariantName, result: Result, reason: str, count: Optional[int] +) -> InvariantResult: + labels: dict[Status, InvariantStatus] = { + Status.HELD: "held", + Status.REFUTED: "refuted", + Status.NOT_CHECKED: "not_checked", + } + return InvariantResult(name, labels[result.status], reason, count, result) + + def _zero( name: InvariantName, count: Optional[int], @@ -73,17 +118,22 @@ def _zero( refuted: str, unknown: str, ) -> InvariantResult: + """No change of this kind: any one refutes; none holds only on a complete + read (:meth:`Result.nothing_else`).""" + + subject = Subject(surface="hard_invariants", key=name) if not _count(count): - return InvariantResult(name, "not_checked", "invalid_or_missing_observation") - assert count is not None - if count > 0: - return InvariantResult(name, "refuted", refuted, count) - return InvariantResult( - name, - "held" if complete is True else "not_checked", - held if complete is True else unknown, - count, + result = Result.not_checked(subject, "invalid_or_missing_observation") + return _invariant(name, result, "invalid_or_missing_observation", None) + result = Result.nothing_else( + subject, + Observed(count, complete=complete is True), + held=held, + refuted=refuted, + partial=unknown, ) + reason = {Status.HELD: held, Status.REFUTED: refuted}.get(result.status, unknown) + return _invariant(name, result, reason, count) @verdict_site("hard_invariants.judge", classes="C2 C5") @@ -126,30 +176,27 @@ def judge_hard_invariants( counts = (before_matches, after_matches, history_matches) known = [n for n in counts if _count(n)] maximum = max(known) if known else None + subject = Subject(surface="hard_invariants", key="at_most_one") + # One duplicate refutes, even beside an incomplete read. if maximum is not None and maximum > 1: - cardinality = InvariantResult( - "at_most_one", "refuted", "duplicate_business_key", maximum + result = Result.refuted( + subject, Observed(maximum, complete=False), "duplicate_business_key" ) + reason = "duplicate_business_key" elif ( - not all(_count(n) for n in counts) + len(known) != len(counts) or history_complete is not True or search_complete is not True ): - cardinality = InvariantResult( - "at_most_one", - "not_checked", - "business_key_history_or_search_incomplete", - maximum, - ) + reason = "business_key_history_or_search_incomplete" + result = Result.not_checked(subject, reason) elif _count(history_matches) and maximum is not None and history_matches < maximum: - cardinality = InvariantResult( - "at_most_one", - "not_checked", - "business_key_observations_inconsistent", - maximum, - ) + reason = "business_key_observations_inconsistent" + result = Result.not_checked(subject, reason) else: - cardinality = InvariantResult( - "at_most_one", "held", "at_most_one_business_record", maximum - ) + reason = "at_most_one_business_record" + # Every count is known and both reads were complete (checked above). + complete = history_complete is True and search_complete is True + result = Result.held(subject, Observed(maximum, complete=complete), reason) + cardinality = _invariant("at_most_one", result, reason, maximum) return HardInvariantVerdict((scope, cardinality, deletes)) diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 4f0a178bec..eef2eaa99e 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -29,6 +29,16 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence +from openadapt_flow.verdict import ( + Obligations, + Result, + Settlement, + Status, + Subject, + settle, +) +from openadapt_flow.verdict_sites import verdict_site + if TYPE_CHECKING: from openadapt_types.receipt import ReceiptVerification, RoleKey @@ -54,13 +64,27 @@ def mode_enabled(env: Optional[Mapping[str, str]] = None) -> bool: return env.get(ENV_MODE, "on").strip().lower() not in ("0", "off", "false", "no") +def _occurrences(hashes: Sequence[Any]) -> list[Subject]: + """One subject per contract hash, numbered per hash, so two effects with + the same contract are two obligations.""" + + seen: Counter[Any] = Counter() + out = [] + for h in hashes: + seen[h] += 1 + out.append(Subject(surface="effect", key=f"{h}#{seen[h]}")) + return out + + +@verdict_site("receipt_record.line", classes="C1 C3") def _line( index: int, result: Mapping[str, Any], ledger: Mapping[str, Any] | None ) -> dict[str, Any]: from openadapt_flow.check_level import CheckLevel, from_verification_tier evidence = result.get("effect_evidence") or [] - declared = Counter(result.get("effect_contract_hashes") or []) + planned = list(result.get("effect_contract_hashes") or []) + declared = Counter(planned) ledger_effects = ledger["effects"] if ledger is not None else [] # A declared effect can lack a bound hash when the run stopped before the # reader ran. Keep the attempted write and withhold its verification. @@ -74,29 +98,49 @@ def _line( # A negative aggregate flag covers both a contradiction and an unavailable # reader. Only complete, contract-bound read evidence distinguishes them. if declared and ledger_matches and declared == observed: - verdicts = {item["final_verdict"] for item in evidence} levels = [ from_verification_tier(item["verification_tier"]) if type(item.get("verification_tier")) is int else CheckLevel.UNCHECKED for item in evidence ] - if verdicts <= {"confirmed", "refuted"} and min(levels) > CheckLevel.UNCHECKED: - if "refuted" in verdicts: - check = "refuted" - elif ( - verdicts == {"confirmed"} - and result.get("effect_verified") is True - and all(item.get("observed_effect") == "present" for item in evidence) - and (ledger is None or ledger.get("status") == "confirmed") - ): - check = "confirmed" - if check != "not_checked": - strength = ( - "read_back" - if min(levels) >= CheckLevel.SYSTEM_OF_RECORD - else "same_screen" - ) + # The declared effects are the obligations; each read settles the + # one its contract hash names. A read below UNCHECKED, or a verdict + # nobody listed, is not checked. + subjects = _occurrences([item["effect_contract_hash"] for item in evidence]) + results = [ + Result.from_code( + subject, + item["final_verdict"], + held=frozenset({"confirmed"}), + refuted=frozenset({"refuted"}), + ) + if level > CheckLevel.UNCHECKED + else Result.not_checked(subject, "unchecked read") + for subject, item, level in zip(subjects, evidence, levels) + ] + settled = settle( + Obligations.fix(_occurrences(planned), source="effect_contract_hashes"), + results, + ) + # Anything unread outranks a refutation: a line is refuted only when + # every declared effect was read. + label = settled.label(precedence=(Status.NOT_CHECKED, Status.REFUTED)) + if label is Status.REFUTED: + check = "refuted" + elif ( + label is Status.HELD + and result.get("effect_verified") is True + and all(item.get("observed_effect") == "present" for item in evidence) + and (ledger is None or ledger.get("status") == "confirmed") + ): + check = "confirmed" + if check != "not_checked": + strength = ( + "read_back" + if min(levels) >= CheckLevel.SYSTEM_OF_RECORD + else "same_screen" + ) not_checked: list[str] = [] if result.get("effect_approved_unverified") is True: not_checked.append("approved_unverified") @@ -209,6 +253,36 @@ def _write_lines(report: Mapping[str, Any], results: list[Any]) -> list[dict[str return lines +@verdict_site("receipt_record.lines", classes="C2 C3") +def _tally_lines( + lines: Sequence[Mapping[str, Any]], +) -> tuple[dict[str, int], Settlement]: + """The receipt's line counts and their settlement: every line is one + obligation. A check nobody listed counts as not checked, so the three + counts always add up to the number of lines.""" + + subjects = [Subject(surface="line", key=str(n)) for n in range(len(lines))] + settled = settle( + Obligations.fix(subjects, source="lines"), + [ + Result.from_code( + subject, + line.get("check"), + held=frozenset({"confirmed"}), + refuted=frozenset({"refuted"}), + ) + for subject, line in zip(subjects, lines) + ], + ) + confirmed, refuted = len(settled.held), len(settled.refuted) + tally = { + "confirmed": confirmed, + "refuted": refuted, + "not_checked": settled.total - confirmed - refuted, + } + return tally, settled + + def build_statement( report: Mapping[str, Any], report_sha256: str, @@ -230,14 +304,13 @@ def build_statement( lines = _write_lines(report, results) except (AttributeError, KeyError, TypeError, ValueError) as exc: raise ReceiptRecordError("invalid_write_evidence") from exc - tally = { - k: sum(1 for line in lines if line["check"] == k) - for k in ("confirmed", "refuted", "not_checked") - } + tally, settled = _tally_lines(lines) outcome, reason = r.receipt_outcome(report.get("execution_outcome")) if outcome == "VERIFIED" and results and "change_ledger" not in report: outcome, reason = "UNKNOWN", "incomplete_write_coverage" - if outcome == "VERIFIED" and (tally["refuted"] or tally["not_checked"]): + # A run that wrote nothing has no line to check; any line that isn't + # confirmed keeps the run from VERIFIED. + if outcome == "VERIFIED" and settled.total and not settled.passes: outcome, reason = "UNKNOWN", "unverified_write" bundle = report.get("bundle_content_digest") bundle = bundle if isinstance(bundle, str) and _SHA256.fullmatch(bundle) else None diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py index 7d8544e34d..a957b9c87c 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -33,13 +33,21 @@ import hashlib import re -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field from typing import Any, Literal, Optional from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator from openadapt_flow.runtime.effects.effect import ValueExpr +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Status, + Subject, + settle, +) from openadapt_flow.verdict_sites import verdict_site VersionStatus = Literal["held", "refuted", "not_checked"] @@ -256,131 +264,189 @@ def judge_versions( mine = resolved before: Mapping[str, Any] = stored.get("records") or {} out = VersionVerdict("held") - worst: Optional[VersionVerdict] = None - - def stop(status: VersionStatus, problem: str, reason: str) -> None: - nonlocal worst - if worst is None or (worst.status == "not_checked" and status == "refuted"): - worst = VersionVerdict(status, problem, reason=reason) + # The obligations come from the plan: the reads themselves, then one per + # target. With no target (all creates) the reads still have to hold, so + # the set is never empty. + read = Subject(surface="versions", key="reads") + subjects = [read] + results = [ + Result.held( + read, + Observed(len(rows), complete=True), + "the versions were read before and after the write", + ) + ] + #: Per target, in order: the problems found, each (status, code, reason). + problems: dict[int, list[tuple[VersionStatus, str, str]]] = {} seen: set[Optional[str]] = set() for target, existed, changed in targets: if target in seen: continue seen.add(target) - if target is None: + n = len(subjects) + subject = Subject(surface="versions", key=f"target:{n}") + subjects.append(subject) + found = problems.setdefault(n, []) + + def stop(status: VersionStatus, problem: str, reason: str) -> None: + found.append((status, problem, reason)) + + _judge_target( + spec, before, rows, key, mine, out, target, existed, changed, stop + ) + if not found: + results.append(Result.held(subject, Observed(target), "the agent's own")) + elif any(status == "refuted" for status, _, _ in found): + # A refutation stands even when another read of the same target + # can't be explained: adding a duplicate or a null row never hides + # a version by someone else. + results.append( + Result.refuted(subject, Observed(target, complete=False), "refuted") + ) + else: + results.append(Result.not_checked(subject, found[0][1])) + settled = settle(Obligations.fix(subjects, source="frame.versions"), results) + label = settled.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) + if label is Status.HELD: + out.reason = f"{out.targets} target(s): every new version is the agent's own" + return out + wanted: VersionStatus = "refuted" if label is Status.REFUTED else "not_checked" + # The first problem of the worst kind, in target order, names the verdict. + status, problem, reason = next( + (p for n in sorted(problems) for p in problems[n] if p[0] == wanted), + ("not_checked", "missing", "the version check could not be settled"), + ) + return VersionVerdict( + status, + problem, + targets=out.targets, + new_versions=out.new_versions, + own_versions=out.own_versions, + reason=reason, + ) + + +def _judge_target( + spec: FrameVersions, + before: Mapping[str, Any], + rows: Sequence[Mapping[str, Any]], + key: bytes, + mine: set[str], + out: VersionVerdict, + target: Optional[str], + existed: bool, + changed: bool, + stop: Callable[[VersionStatus, str, str], None], +) -> None: + """Every problem with one target, through ``stop``. A problem that only + leaves the target unexplained doesn't end the search for one that + refutes it.""" + + if target is None: + stop( + "not_checked", + "no_target_id", + f"a target record has no {spec.target_field or 'identity'} field, " + "so its versions can't be found", + ) + return + base = before.get(_mac(key, "record", target)) + if base is None: + if existed: stop( "not_checked", - "no_target_id", - f"a target record has no {spec.target_field or 'identity'} field, " - "so its versions can't be found", + "missing", + "the target existed before the write but had no version", ) - continue - base = before.get(_mac(key, "record", target)) - if base is None: - if existed: + return # created in the window: no earlier version to overwrite + out.targets += 1 + now = [r for r in rows if _text(_get(r, spec.record_field)) == target] + if not now: + stop("not_checked", "missing", "the target has no version after the write") + return + old = set(base.get("versions") or []) + versions = [_text(_get(r, spec.version_field)) for r in now] + if base.get("null") or any(v is None for v in versions): + stop( + "not_checked", + "null_version", + "a version of the target reads as null, so saves can't be told apart", + ) + return + macs = [_mac(key, "version", target, str(v)) for v in versions] + if base.get("dup") or len(set(macs)) != len(macs): + stop( + "not_checked", + "duplicate_version", + "two rows of the target's versions hold the same version, so a " + "save could hide behind another", + ) + # One row per new version: a version read twice is one save. + fresh: list[tuple[Optional[str], Mapping[str, Any]]] = [] + fresh_macs: set[str] = set() + for v, r, m in zip(versions, now, macs): + if m not in old and m not in fresh_macs: + fresh_macs.add(m) + fresh.append((v, r)) + out.new_versions += len(fresh) + if changed and not fresh: + stop( + "not_checked", + "no_new_version", + "the target changed in the window but no new version of it was " + "read, so who saved it can't be told", + ) + if spec.author_field and not old <= set(macs): + stop( + "not_checked", + "history_changed", + "a version of the target read before the write is gone after it: " + "the read isn't a history that only grows, so a save in the " + "window could be hidden", + ) + if spec.author_field: + for _version, r in fresh: + author = _text(_get(r, spec.author_field)) + if author is None: stop( "not_checked", - "missing", - "the target existed before the write but had no version", + "no_author", + "a new version of the target names no author, so it " + "can't be told from another user's save", ) - continue # created in the window: no earlier version to overwrite - out.targets += 1 - now = [r for r in rows if _text(_get(r, spec.record_field)) == target] - if not now: - stop("not_checked", "missing", "the target has no version after the write") - continue - old = set(base.get("versions") or []) - versions = [_text(_get(r, spec.version_field)) for r in now] - if base.get("null") or any(v is None for v in versions): - stop( - "not_checked", - "null_version", - "a version of the target reads as null, so saves can't be told apart", - ) - continue - macs = [_mac(key, "version", target, str(v)) for v in versions] - if base.get("dup") or len(set(macs)) != len(macs): - stop( - "not_checked", - "duplicate_version", - "two rows of the target's versions hold the same version, so a " - "save could hide behind another", - ) - continue - fresh = [(v, r) for v, r, m in zip(versions, now, macs) if m not in old] - out.new_versions += len(fresh) - if changed and not fresh: - stop( - "not_checked", - "no_new_version", - "the target changed in the window but no new version of it was " - "read, so who saved it can't be told", - ) - continue - if spec.author_field and not old <= set(macs): - stop( - "not_checked", - "history_changed", - "a version of the target read before the write is gone after it: " - "the read isn't a history that only grows, so a save in the " - "window could be hidden", - ) - continue - if spec.author_field: - for _version, r in fresh: - author = _text(_get(r, spec.author_field)) - if author is None: - stop( - "not_checked", - "no_author", - "a new version of the target names no author, so it " - "can't be told from another user's save", - ) - elif author in mine: - out.own_versions += 1 - else: - stop( - "refuted", - "another_author", - "lost update: another user saved a version of the target " - "inside the window, and the agent's save came after it " - "or beside it", - ) - continue - # No authors: count whole-number steps. - values = [_text(_get(r, spec.version_field)) for r in now] - if not base.get("whole") or any( - v is None or not _WHOLE.match(v) for v in values - ): - stop( - "not_checked", - "not_a_number", - "the target's versions aren't whole numbers, and no author is " - "read, so the steps in the window can't be counted", - ) - continue - steps = max(int(v) for v in values if v is not None) - int(base["max"] or 0) - if steps < 0 or (steps == 0 and fresh): - stop( - "refuted", - "went_back", - "the target's version went back or was replaced in the window", - ) - elif steps > 1 or len(fresh) > 1: - stop( - "refuted", - "extra_steps", - f"lost update: the target moved {max(steps, len(fresh))} versions " - "in the window; one save is the agent's, and no author is read " - "to say whose the others are", - ) - if worst is not None: - worst.targets, worst.new_versions, worst.own_versions = ( - out.targets, - out.new_versions, - out.own_versions, + elif author in mine: + out.own_versions += 1 + else: + stop( + "refuted", + "another_author", + "lost update: another user saved a version of the target " + "inside the window, and the agent's save came after it " + "or beside it", + ) + return + # No authors: count whole-number steps. + if not base.get("whole") or any(not _WHOLE.match(str(v)) for v in versions): + stop( + "not_checked", + "not_a_number", + "the target's versions aren't whole numbers, and no author is " + "read, so the steps in the window can't be counted", + ) + return + steps = max(int(str(v)) for v in versions) - int(base["max"] or 0) + if steps < 0 or (steps == 0 and fresh): + stop( + "refuted", + "went_back", + "the target's version went back or was replaced in the window", + ) + elif steps > 1 or len(fresh) > 1: + stop( + "refuted", + "extra_steps", + f"lost update: the target moved {max(steps, len(fresh))} versions " + "in the window; one save is the agent's, and no author is read " + "to say whose the others are", ) - return worst - out.reason = f"{out.targets} target(s): every new version is the agent's own" - return out diff --git a/packages/flow/openadapt_flow/tx/wire_tap.py b/packages/flow/openadapt_flow/tx/wire_tap.py index bdbfb09bf3..c24d55d9dd 100644 --- a/packages/flow/openadapt_flow/tx/wire_tap.py +++ b/packages/flow/openadapt_flow/tx/wire_tap.py @@ -35,6 +35,7 @@ WireTapProtocol, canonical_sha256, ) +from openadapt_flow.verdict_sites import verdict_site from openadapt_flow.wire_check import READ_METHODS, carries_secret, mask_secrets __all__ = [ @@ -111,6 +112,7 @@ def _normalize_origin(url_or_origin: str) -> str: return f"{scheme}://{host}:{port}" +@verdict_site("wire_tap.relay_redirect_location", classes="C6") def relay_redirect_location( location: str, *, diff --git a/packages/flow/openadapt_flow/verdict.py b/packages/flow/openadapt_flow/verdict.py index a857c8c7c3..9c744aa038 100644 --- a/packages/flow/openadapt_flow/verdict.py +++ b/packages/flow/openadapt_flow/verdict.py @@ -13,6 +13,9 @@ made from a complete :class:`Observed` value (:meth:`Result.held`) or from an allow-listed upstream code (:meth:`Result.from_code`). A read that raised or found nothing gives ``NOT_CHECKED``; it never defaults to a pass. +- :meth:`Result.nothing_else` judges a "nothing else changed" claim from a + count of changes: any change refutes, and zero holds only on a complete + read (C1, C2). - :func:`settle` matches results to obligations. An obligation with no result, a result nobody asked for, a result bound to a different run, two results that disagree, or more obligations than the limit all keep the settlement @@ -276,6 +279,38 @@ def from_observation( return cls.refuted(subject, obs, reason) return cls.not_checked(subject, reason) + @classmethod + def nothing_else( + cls, + subject: Subject, + obs: Observation, + *, + held: str = "nothing else changed", + refuted: str = "something else changed", + partial: str = "the read was partial", + ) -> "Result": + """A "nothing else changed" claim from a count of changes found. + + The observed value is the number of changes the read found outside + what was allowed. One or more refutes, even on a partial read. Zero + holds only when the read was complete: a partial read that found + nothing is ``NOT_CHECKED``, never a pass. A count that isn't a whole + number (``None``, a bool, a negative) is ``NOT_CHECKED``. + """ + + if isinstance(obs, Missing): + return cls.not_checked(subject, f"missing: {obs.reason}") + if isinstance(obs, Errored): + return cls.not_checked(subject, f"errored: {obs.exc_type}") + count = obs.value + if not isinstance(count, int) or isinstance(count, bool) or count < 0: + return cls.not_checked(subject, "invalid_or_missing_observation") + if count > 0: + return cls.refuted(subject, obs, refuted) + if obs.complete is not True: + return cls.not_checked(subject, partial) + return cls.held(subject, obs, held) + @classmethod def from_code( cls, @@ -433,20 +468,24 @@ def settle( conflicting: list[Subject] = [] used: set[int] = set() matches: dict[int, list[Result]] = {} - takers: dict[int, int] = {} + # The obligations that claim each result, by index: the same object passed + # twice to one obligation is one claim, so the verdict depends on the + # evidence, not on how the caller stored it. + takers: dict[int, set[int]] = {} for n, item in enumerate(obligations.items): same_key = by_key.get(item.key_tuple(), []) matches[n] = [r for r in same_key if not binding_mismatches(item, r.subject)] for r in matches[n]: - takers[id(r)] = takers.get(id(r), 0) + 1 + takers.setdefault(id(r), set()).add(n) for n, item in enumerate(obligations.items): got = matches[n] used.update(id(r) for r in got) + shared = any(len(takers[id(r)]) > 1 for r in got) if not by_key.get(item.key_tuple()): buckets["missing"].append(item) elif not got: buckets["mismatched"].append(item) - elif len({r.status for r in got}) > 1 or any(takers[id(r)] > 1 for r in got): + elif len({r.status for r in got}) > 1 or shared: # Two results that disagree, or one result two obligations claim. conflicting.append(item) else: diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 29c2897ae6..7d3abee240 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -56,7 +56,7 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Any, Literal, Mapping, Optional, Sequence, cast +from typing import Any, Callable, Literal, Mapping, Optional, Sequence, cast from uuid import uuid4 from openadapt_types.approval import ( @@ -2964,40 +2964,76 @@ def _label(verdict: Verdict) -> EffectVerdictLabel: } -@verdict_site("verify_run.aggregate", classes="C2") -def _aggregate(verdicts: Sequence[EffectVerdict]) -> EffectVerdictLabel: - """CONFIRMED only when every effect is; any INDETERMINATE outranks a - REFUTED; no effects at all is INDETERMINATE (docs/FAIL_CLOSED.md).""" - - subjects = [Subject(key=str(i)) for i in range(len(verdicts))] - settled = settle( - Obligations.fix(subjects, source="effects"), - [ - Result.from_code( - s, - v.verdict, - held=frozenset({Verdict.CONFIRMED.value}), - refuted=frozenset({Verdict.REFUTED.value}), - ) - for s, v in zip(subjects, verdicts) - ], +def _effect_results( + planned: Sequence[str], + verdicts: Sequence[EffectVerdict], + code: Callable[[EffectVerdict], object], + *, + held: frozenset[str], + refuted: frozenset[str], +) -> tuple[Obligations, list[Result]]: + """One obligation per planned effect, fixed from the contract before any + read; the ``i``-th verdict answers the ``i``-th. A verdict past the plan + answers nothing (it is unexpected), and a planned effect with no verdict + is missing, so neither can pass.""" + + subjects = [Subject(key=key) for key in planned] + results = [ + Result.from_code( + subjects[i] if i < len(subjects) else Subject(key=f"unplanned:{i}"), + code(v), + held=held, + refuted=refuted, + ) + for i, v in enumerate(verdicts) + ] + return Obligations.fix(subjects, source="cfg.effects"), results + + +@verdict_site("verify_run.aggregate", classes="C1 C2") +def _aggregate( + planned: Sequence[str], verdicts: Sequence[EffectVerdict] +) -> EffectVerdictLabel: + """CONFIRMED only when every planned effect is; any INDETERMINATE outranks + a REFUTED; no effects at all, a planned effect with no verdict or a + verdict nobody planned is INDETERMINATE (docs/FAIL_CLOSED.md).""" + + obligations, results = _effect_results( + planned, + verdicts, + lambda v: v.verdict, + held=frozenset({Verdict.CONFIRMED.value}), + refuted=frozenset({Verdict.REFUTED.value}), ) + settled = settle(obligations, results) return _AGGREGATE_LABELS[ settled.label(precedence=(Status.NOT_CHECKED, Status.REFUTED)) ] -@verdict_site("verify_run.observed", classes="C2") -def _observed(verdicts: Sequence[EffectVerdict]) -> str: - if not verdicts: - return "unknown" # nothing was read, so nothing is present +@verdict_site("verify_run.observed", classes="C1 C2") +def _observed(planned: Sequence[str], verdicts: Sequence[EffectVerdict]) -> str: + """``present`` only when every planned effect was read as present. + ``unknown`` when one was not read, has no verdict, or was not planned; + ``conflicting`` for a wrong record or a mix of landed and not landed.""" + + obligations, results = _effect_results( + planned, + verdicts, + lambda v: v.observed_effect, + held=frozenset({"present"}), + refuted=frozenset({"absent", "conflicting"}), + ) + settled = settle(obligations, results) + if settled.passes: + return "present" + if not settled.refuted or settled.total != len(settled.held) + len(settled.refuted): + return "unknown" # something planned was not read, or not planned seen = {v.observed_effect for v in verdicts} - if "unknown" in seen: - return "unknown" if "conflicting" in seen or seen == {"absent", "present"}: # A wrong record, or some effects landed and others did not. return "conflicting" - return "absent" if "absent" in seen else "present" + return "absent" @verdict_site("verify_run.readback_class", classes="C1 C2") @@ -3229,6 +3265,10 @@ def verify_run( judged_effects: list[Effect] = [] weakest: Optional[VerificationTier] = None tiers: list[Optional[VerificationTier]] = [] + # The effects the contract plans, fixed before any read: each fold below + # settles the verdicts against these, so a verdict that goes missing + # can't leave a pass. + planned = [f"{i}:{e.kind.value}" for i, e in enumerate(cfg.effects)] for effect in cfg.effects: try: bound = effect.resolve(params) @@ -3287,8 +3327,8 @@ def verify_run( } ) - delta_verdict = _aggregate(verdicts) - observed_effect = _observed(verdicts) + delta_verdict = _aggregate(planned, verdicts) + observed_effect = _observed(planned, verdicts) # The frame: nothing outside the declared delta moved. Without a baseline # it can't be known, so it is not checked and the run is not verified. frame_spec = cfg.frame or FrameSpec() @@ -3316,8 +3356,8 @@ def verify_run( _excuse_attributed_additions( cfg, verifier, before, judged_effects, verdicts, rows, frame ) - delta_verdict = _aggregate(verdicts) - observed_effect = _observed(verdicts) + delta_verdict = _aggregate(planned, verdicts) + observed_effect = _observed(planned, verdicts) if history_spec is not None: if history_problem is not None and frame.status != "refuted": frame.status = "not_checked" diff --git a/packages/flow/scripts/check_verdict_folds.py b/packages/flow/scripts/check_verdict_folds.py index c2c405adee..84003f05a3 100644 --- a/packages/flow/scripts/check_verdict_folds.py +++ b/packages/flow/scripts/check_verdict_folds.py @@ -61,8 +61,11 @@ "cmp_literal", "bool_fold", "swallow", + "swallow_wide", "slice_count", "else_success", + "says_unchanged", + "empty_change_set", ) @@ -76,6 +79,8 @@ def load_config(path: Path = CONFIG) -> dict[str, Any]: config["_outcomes"] = frozenset(literals) config["_success"] = frozenset(config["literals"]["success"]) config["_fold_names"] = re.compile(config["bool_fold"]["names"], re.IGNORECASE) + config["_unchanged"] = frozenset(config["literals"]["unchanged"]) + config["_change_names"] = re.compile(config["change_set"]["names"], re.IGNORECASE) return config @@ -185,19 +190,78 @@ def _closed_exit(node: ast.AST) -> bool: return _not_checked_value(value) +_BROAD = frozenset({"Exception", "BaseException"}) + + +def _broad(handler: ast.ExceptHandler) -> bool: + """A bare ``except``, or one naming ``Exception``/``BaseException`` by + name, by attribute (``builtins.Exception``) or inside a tuple.""" + + kind = handler.type + if kind is None: + return True + kinds = kind.elts if isinstance(kind, ast.Tuple) else [kind] + return any( + (isinstance(k, ast.Name) and k.id in _BROAD) + or (isinstance(k, ast.Attribute) and k.attr in _BROAD) + for k in kinds + ) + + +def _falls_through(body: list[ast.stmt]) -> bool: + """True when running ``body`` can reach its end (no raise, return, + continue or break on every path). Loops, ``with``, ``try`` and ``match`` + are taken to fall through unless every branch they hold ends.""" + + for stmt in body: + if isinstance(stmt, (ast.Raise, ast.Return, ast.Continue, ast.Break)): + return False + if isinstance(stmt, ast.If): + if not _falls_through(stmt.body) and not _falls_through(stmt.orelse): + return False + elif isinstance(stmt, (ast.With, ast.AsyncWith)): + if not _falls_through(stmt.body): + return False + elif isinstance(stmt, ast.Try): + ends = not _falls_through(stmt.body + stmt.orelse) and all( + not _falls_through(h.body) for h in stmt.handlers + ) + if ends or (stmt.finalbody and not _falls_through(stmt.finalbody)): + return False + return True + + +def _records_not_checked(body: list[ast.stmt]) -> bool: + """True when the handler assigns or appends a not-checked value, so a + fall-through hands on "not checked" rather than nothing.""" + + wrapper = ast.Module(body=body, type_ignores=[]) + for node in ast.walk(wrapper): + if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)) and ( + node.value is not None and _not_checked_value(node.value) + ): + return True + if ( + isinstance(node, ast.Call) + and node.args + and any(_not_checked_value(a) for a in node.args) + ): + return True + return False + + _COUNTING = frozenset({"sum", "len", "Counter", "tally", "count"}) def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: """Per-kind counts of hand-written folds in one Python file.""" - try: - tree = ast.parse(path.read_text(encoding="utf-8")) - except (SyntaxError, UnicodeDecodeError): - return Counter() + # A file the check can't read is an error, never a file with no folds. + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) skip = _exempt_nodes(tree) outcomes, success = config["_outcomes"], config["_success"] - fold_names = config["_fold_names"] + fold_names, unchanged = config["_fold_names"], config["_unchanged"] + change_names = config["_change_names"] counts: Counter[str] = Counter() compared: set[int] = set() @@ -215,6 +279,8 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: for node in ast.walk(tree): if id(node) in skip: continue + if _empty_change_set(node, change_names): + counts["empty_change_set"] += 1 if isinstance(node, ast.Compare): values = [node.left, *node.comparators] if any(s in outcomes or s in success for v in values for s in _strings(v)): @@ -227,6 +293,14 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: and id(node) not in typed ): counts["says_success"] += 1 + elif ( + isinstance(node, ast.Constant) + and isinstance(node.value, str) + and node.value in unchanged + and id(node) not in compared + and id(node) not in typed + ): + counts["says_unchanged"] += 1 elif ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) @@ -235,20 +309,30 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: and any(fold_names.search(n) for n in _names(node.args[0])) ): counts["bool_fold"] += 1 - elif isinstance(node, ast.ExceptHandler): - broad = node.type is None or ( - isinstance(node.type, ast.Name) - and node.type.id in ("Exception", "BaseException") - ) + elif isinstance(node, ast.ExceptHandler) and _broad(node): # Each way out of the handler is judged on its own: a raise on one # branch doesn't excuse a ``return True`` on another. body = ast.Module(body=node.body, type_ignores=[]) - if broad and any( - not _closed_exit(n) + exits = [ + n for n in ast.walk(body) - if isinstance(n, (ast.Return, ast.Continue, ast.Pass)) + if isinstance(n, (ast.Return, ast.Continue, ast.Break, ast.Pass)) + ] + named = node.type is None or ( + isinstance(node.type, ast.Name) and node.type.id in _BROAD + ) + if named and any( + not _closed_exit(n) for n in exits if not isinstance(n, ast.Break) ): counts["swallow"] += 1 + elif any(not _closed_exit(n) for n in exits) or ( + _falls_through(node.body) and not _records_not_checked(node.body) + ): + # What ``swallow`` misses: ``except Exception: logger.error(...)`` + # and carry on, so the code after the handler runs as if the + # call had worked; a ``break``; and ``Exception`` named in a + # tuple or by attribute. + counts["swallow_wide"] += 1 elif isinstance(node, ast.If) and node.orelse: tail = node.orelse if not (len(tail) == 1 and isinstance(tail[0], ast.If)): @@ -288,6 +372,49 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: return counts +def _empty_change_set(node: ast.AST, names: "re.Pattern[str]") -> bool: + """A "nothing else changed" test written by hand: ``not changes``, + ``len(changes) == 0``, ``changes == []`` or ``not any(changes)`` over a + set of changes, collateral, diffs or deletes. The set may be a partial + read, so emptiness is not evidence that nothing changed; the kernel's + ``Result.nothing_else`` holds only on a complete read.""" + + def about_changes(expr: ast.AST) -> bool: + if isinstance(expr, ast.Call) and getattr(expr.func, "id", "") in ( + "any", + "len", + "bool", + ): + return bool(expr.args) and about_changes(expr.args[0]) + if isinstance(expr, (ast.GeneratorExp, ast.ListComp, ast.SetComp)): + return any(about_changes(g.iter) for g in expr.generators) + if isinstance(expr, ast.Name): + return bool(names.fullmatch(expr.id)) + if isinstance(expr, ast.Attribute): + return bool(names.fullmatch(expr.attr)) + return False + + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): + return about_changes(node.operand) + if ( + isinstance(node, ast.Compare) + and len(node.ops) == 1 + and isinstance(node.ops[0], (ast.Eq, ast.Is)) + ): + left, right = node.left, node.comparators[0] + empty = ( + (isinstance(right, ast.Constant) and right.value == 0) + or (isinstance(right, (ast.List, ast.Tuple, ast.Set)) and not right.elts) + or ( + isinstance(right, ast.Call) + and getattr(right.func, "id", "") in ("set", "list", "tuple", "dict") + and not right.args + ) + ) + return empty and about_changes(left) + return False + + def scope_files(config: dict[str, Any], root: Path = ROOT) -> Iterator[Path]: exempt = set(config["scope"]["exempt"]) for pattern in config["scope"]["include"]: @@ -359,7 +486,36 @@ def lowered( return {rel: dict(sorted(k.items())) for rel, k in sorted(out.items())} -SPEC_ID = re.compile(r"""["']([\w.\-]+)["']""") # any quoted id in a spec file +_SPEC_KINDS = frozenset({"site", "owned", "selftest"}) + + +def spec_ids(source: str) -> set[str]: + """The site ids a spec file registers: an ``id=`` keyword, or a string + passed to the call given to ``register(...)`` (a spec factory). Any other + quoted word in the file (``"held"``, ``"C1"``) is not an id.""" + + ids: set[str] = set() + for node in ast.walk(ast.parse(source)): + if not isinstance(node, ast.Call): + continue + for kw in node.keywords: + if ( + kw.arg == "id" + and isinstance(kw.value, ast.Constant) + and isinstance(kw.value.value, str) + ): + ids.add(kw.value.value) + if getattr(node.func, "id", "") == "register" and node.args: + inner = node.args[0] + if isinstance(inner, ast.Call): + ids.update( + a.value + for a in inner.args + if isinstance(a, ast.Constant) + and isinstance(a.value, str) + and a.value not in _SPEC_KINDS + ) + return ids def unregistered_sites(root: Path = ROOT) -> list[str]: @@ -372,7 +528,7 @@ def unregistered_sites(root: Path = ROOT) -> list[str]: config = load_config() specs = root / "packages/flow/tests/failopen/sites" - ids = {m for f in specs.glob("*.py") for m in SPEC_ID.findall(f.read_text("utf-8"))} + ids = {i for f in specs.glob("*.py") for i in spec_ids(f.read_text("utf-8"))} missing = [] for path in scope_files(config, root): for site, name in decorated_sites(path).items(): diff --git a/packages/flow/scripts/verdict_folds.toml b/packages/flow/scripts/verdict_folds.toml index 040d9ba7fa..0eef239d88 100644 --- a/packages/flow/scripts/verdict_folds.toml +++ b/packages/flow/scripts/verdict_folds.toml @@ -27,7 +27,27 @@ success = [ ] # Compared against, beside every outcome in the vocabulary. outcome_extra = ["held", "confirmed", "pass", "verified_done", "refuted", "not_checked"] +# A check that says one of these is saying nothing else changed (a frame, a +# rollback, no collateral). Only a complete read can say it. +unchanged = [ + "unchanged", + "no_change", + "nothing_changed", + "untouched", + "no_collateral", + "no_outside_scope_changes", + "no_undeclared_deletes", + "rolled_back", + "ROLLED_BACK", + "NO_CHANGE", + "NOTHING_CHANGED", +] [bool_fold] # all(...)/any(...) over one of these names folds verdicts by hand. names = '(verdict|result|check|effect|line|tier)' + +[change_set] +# ``not x``, ``len(x) == 0``, ``x == []`` or ``not any(x)`` over one of these +# names says nothing else changed. Matched anywhere in the name. +names = '.*(changes|changed|collateral|diffs?|deletes|deleted|concurrent|moved|unexpected).*' diff --git a/packages/flow/scripts/verdict_folds_baseline.json b/packages/flow/scripts/verdict_folds_baseline.json index cec7ef7812..1a5c915935 100644 --- a/packages/flow/scripts/verdict_folds_baseline.json +++ b/packages/flow/scripts/verdict_folds_baseline.json @@ -1,30 +1,39 @@ { "openadapt/cli.py": { "cmp_literal": 1, + "slice_count": 1, "swallow": 10, - "slice_count": 1 + "swallow_wide": 7 }, "openadapt/quickstart/engine.py": { - "cmp_literal": 5, - "swallow": 2 + "cmp_literal": 7, + "swallow": 3 }, "openadapt/quickstart/notices.py": { "swallow": 1 }, "openadapt/quickstart/openemr.py": { "cmp_literal": 2, - "swallow": 2 + "swallow": 2, + "swallow_wide": 1 }, "openadapt/quickstart/scene.py": { "cmp_literal": 1, "slice_count": 1 }, + "openadapt/quickstart/story.py": { + "swallow_wide": 3 + }, "openadapt/quickstart/view.py": { "cmp_literal": 2, "swallow": 1 }, "openadapt/quickstart/workers.py": { "cmp_literal": 1, + "swallow": 2, + "swallow_wide": 1 + }, + "openadapt/receipt_verify.py": { "swallow": 2 }, "openadapt/seal_claim.py": { @@ -38,17 +47,23 @@ }, "packages/flow/openadapt_flow/__main__.py": { "cmp_literal": 14, - "swallow": 8 + "says_unchanged": 2, + "swallow": 8, + "swallow_wide": 9 }, "packages/flow/openadapt_flow/_browser_readiness.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 3 + }, + "packages/flow/openadapt_flow/_browser_setup.py": { + "swallow_wide": 3 }, "packages/flow/openadapt_flow/_prewarm.py": { "swallow": 2 }, "packages/flow/openadapt_flow/action_evidence.py": { - "cmp_literal": 2, - "bool_fold": 3 + "bool_fold": 3, + "cmp_literal": 2 }, "packages/flow/openadapt_flow/adapters/capture.py": { "swallow": 2 @@ -61,21 +76,23 @@ "swallow": 2 }, "packages/flow/openadapt_flow/after_stop.py": { - "cmp_literal": 6, "bool_fold": 2, + "cmp_literal": 6, "swallow": 2 }, "packages/flow/openadapt_flow/agent/authoring.py": { "cmp_literal": 3, - "swallow": 6 + "swallow": 6, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent/bridge.py": { "cmp_literal": 2 }, "packages/flow/openadapt_flow/agent/browser_teach.py": { - "cmp_literal": 1, "bool_fold": 1, - "swallow": 7 + "cmp_literal": 1, + "swallow": 7, + "swallow_wide": 5 }, "packages/flow/openadapt_flow/agent/bundles.py": { "swallow": 2 @@ -84,8 +101,9 @@ "swallow": 3 }, "packages/flow/openadapt_flow/agent/contract.py": { + "cmp_literal": 10, "says_success": 3, - "cmp_literal": 10 + "says_unchanged": 4 }, "packages/flow/openadapt_flow/agent/example_app.py": { "slice_count": 1 @@ -99,41 +117,53 @@ "swallow": 1 }, "packages/flow/openadapt_flow/agent/mcp.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent/repair.py": { - "swallow": 4 + "swallow": 4, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/agent/runner.py": { - "says_success": 1, "cmp_literal": 12, - "swallow": 3 + "says_success": 1, + "says_unchanged": 1, + "swallow": 3, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/agent/runs.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent/sandbox.py": { - "says_success": 2, "cmp_literal": 2, - "swallow": 5 + "says_success": 2, + "swallow": 5, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent/seal.py": { "cmp_literal": 1 }, "packages/flow/openadapt_flow/agent/seal_cli.py": { - "swallow": 3 + "swallow": 3, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent/service.py": { "cmp_literal": 1, - "swallow": 4 + "swallow": 4, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/agent/teach.py": { "cmp_literal": 8, - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent/tutorial.py": { "swallow": 1 }, + "packages/flow/openadapt_flow/agent/verify_tools.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/agent_guard/capture.py": { "cmp_literal": 1 }, @@ -141,11 +171,16 @@ "swallow": 9 }, "packages/flow/openadapt_flow/agent_guard/commit_guard.py": { - "cmp_literal": 2 + "cmp_literal": 2, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/agent_guard/session.py": { "cmp_literal": 1, - "swallow": 4 + "swallow": 4, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/api_footprint.py": { + "empty_change_set": 1 }, "packages/flow/openadapt_flow/approval_mode/approver.py": { "bool_fold": 1 @@ -154,8 +189,8 @@ "bool_fold": 3 }, "packages/flow/openadapt_flow/approval_mode/dry_run.py": { - "cmp_literal": 1, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 1 }, "packages/flow/openadapt_flow/approval_mode/durable_carry.py": { "swallow": 1 @@ -164,27 +199,28 @@ "swallow": 5 }, "packages/flow/openadapt_flow/approval_mode/gate.py": { - "cmp_literal": 4, "bool_fold": 3, - "swallow": 5 + "cmp_literal": 4, + "swallow": 5, + "swallow_wide": 6 }, "packages/flow/openadapt_flow/approval_mode/item_approval.py": { "bool_fold": 1 }, "packages/flow/openadapt_flow/approval_mode/model.py": { - "cmp_literal": 1, - "bool_fold": 3 + "bool_fold": 3, + "cmp_literal": 1 }, "packages/flow/openadapt_flow/approval_mode/named_person_binding.py": { "swallow": 1 }, "packages/flow/openadapt_flow/approval_mode/post.py": { - "cmp_literal": 9, - "bool_fold": 3 + "bool_fold": 3, + "cmp_literal": 9 }, "packages/flow/openadapt_flow/approval_mode/requirements.py": { - "cmp_literal": 2, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 2 }, "packages/flow/openadapt_flow/approval_mode/switch.py": { "swallow": 1 @@ -193,48 +229,59 @@ "says_success": 1 }, "packages/flow/openadapt_flow/attest_bridge.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/authoring.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 7 }, "packages/flow/openadapt_flow/authorization_summary.py": { "swallow": 1 }, "packages/flow/openadapt_flow/backends/_owned.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/backends/_page_quiescence.py": { - "swallow": 4 + "swallow": 4, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/backends/_server_responses.py": { - "swallow": 5 + "swallow": 5, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/backends/choice.py": { "swallow": 2 }, "packages/flow/openadapt_flow/backends/linux_backend.py": { - "swallow": 26 + "swallow": 26, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/backends/macos_backend.py": { - "swallow": 16 + "swallow": 16, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/backends/parallels_vm.py": { "swallow": 2 }, "packages/flow/openadapt_flow/backends/playwright_backend.py": { "cmp_literal": 1, - "swallow": 71 + "swallow": 71, + "swallow_wide": 19 }, "packages/flow/openadapt_flow/backends/rdp_backend.py": { - "swallow": 11 + "swallow": 11, + "swallow_wide": 5 }, "packages/flow/openadapt_flow/backends/redirect_guard.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/backends/remote_display.py": { "bool_fold": 1, - "swallow": 31 + "swallow": 31, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py": { "bool_fold": 1 @@ -243,17 +290,20 @@ "swallow": 1 }, "packages/flow/openadapt_flow/backends/win_agent/server.py": { - "swallow": 28 + "swallow": 28, + "swallow_wide": 6 }, "packages/flow/openadapt_flow/backends/windows_backend.py": { - "swallow": 9 + "swallow": 9, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/backends/windows_keyboard_lease.py": { "cmp_literal": 1, "swallow": 1 }, "packages/flow/openadapt_flow/backends/worker_containment.py": { - "swallow": 3 + "swallow": 3, + "swallow_wide": 3 }, "packages/flow/openadapt_flow/backends/xfreerdp.py": { "swallow": 1 @@ -265,16 +315,22 @@ "cmp_literal": 1, "swallow": 1 }, + "packages/flow/openadapt_flow/bundle_persistence.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/bundle_validation.py": { "bool_fold": 1 }, + "packages/flow/openadapt_flow/choice_capture.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/cli_compose.py": { - "says_success": 1, - "cmp_literal": 1 + "cmp_literal": 1, + "says_success": 1 }, "packages/flow/openadapt_flow/cli_deferred.py": { - "says_success": 1, - "cmp_literal": 4 + "cmp_literal": 4, + "says_success": 1 }, "packages/flow/openadapt_flow/cli_hints.py": { "slice_count": 1 @@ -284,8 +340,8 @@ "swallow": 3 }, "packages/flow/openadapt_flow/cli_process.py": { - "says_success": 1, "cmp_literal": 2, + "says_success": 1, "swallow": 1 }, "packages/flow/openadapt_flow/cli_receipt.py": { @@ -294,6 +350,9 @@ "packages/flow/openadapt_flow/cli_reconcile.py": { "swallow": 1 }, + "packages/flow/openadapt_flow/cli_redact_report.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/cli_self_repair.py": { "swallow": 1 }, @@ -311,18 +370,28 @@ "swallow": 1 }, "packages/flow/openadapt_flow/cli_worklist_pool.py": { - "bool_fold": 1 + "bool_fold": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/cloud_seal.py": { "cmp_literal": 2, "swallow": 1 }, "packages/flow/openadapt_flow/compile_agent/code_action.py": { + "empty_change_set": 1, + "slice_count": 1, "swallow": 9, - "slice_count": 1 + "swallow_wide": 4 + }, + "packages/flow/openadapt_flow/compile_agent/driven.py": { + "swallow_wide": 1 }, "packages/flow/openadapt_flow/compile_agent/harness.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/compile_agent/network_metadata.py": { + "swallow_wide": 6 }, "packages/flow/openadapt_flow/compile_agent/observe.py": { "swallow": 6 @@ -341,6 +410,9 @@ "packages/flow/openadapt_flow/compile_agent/sandbox.py": { "slice_count": 1 }, + "packages/flow/openadapt_flow/compiler/annotate.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/compiler/api_proposal.py": { "cmp_literal": 1, "slice_count": 1 @@ -348,23 +420,39 @@ "packages/flow/openadapt_flow/compiler/binding_admission.py": { "bool_fold": 3 }, + "packages/flow/openadapt_flow/compiler/clock_pass.py": { + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/compiler/codegen.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/compiler/compile.py": { "bool_fold": 1, + "empty_change_set": 1, + "slice_count": 1, "swallow": 2, - "slice_count": 1 + "swallow_wide": 1 }, "packages/flow/openadapt_flow/compiler/compose_authoring.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/compiler/disambiguation.py": { "slice_count": 1 }, + "packages/flow/openadapt_flow/compiler/effect_mining.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/compiler/empty_result_guard.py": { "bool_fold": 2 }, + "packages/flow/openadapt_flow/compiler/fixup_passes.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/compiler/induction.py": { "bool_fold": 3, - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/compiler/lookup_detect.py": { "bool_fold": 2, @@ -372,28 +460,34 @@ }, "packages/flow/openadapt_flow/compiler/narration_rules.py": { "bool_fold": 1, - "slice_count": 1 + "slice_count": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/compiler/probing.py": { "cmp_literal": 4, - "swallow": 2 + "swallow": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/compiler/qualification_pins.py": { "bool_fold": 2 }, "packages/flow/openadapt_flow/composition.py": { - "says_success": 1 + "says_success": 1, + "says_unchanged": 1 }, "packages/flow/openadapt_flow/connector/daemon.py": { "cmp_literal": 3, - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/connector/executor.py": { "cmp_literal": 12, - "swallow": 2 + "swallow": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/connector/windows_service.py": { - "swallow": 5 + "swallow": 5, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/console/app.py": { "swallow": 2 @@ -403,7 +497,9 @@ }, "packages/flow/openadapt_flow/console/data.py": { "cmp_literal": 5, - "swallow": 4 + "empty_change_set": 2, + "swallow": 4, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/console/decision_relay.py": { "cmp_literal": 1 @@ -428,8 +524,8 @@ "swallow": 1 }, "packages/flow/openadapt_flow/countersign/render.py": { - "says_success": 2, - "cmp_literal": 4 + "cmp_literal": 4, + "says_success": 2 }, "packages/flow/openadapt_flow/countersign/tsa.py": { "swallow": 3 @@ -441,8 +537,8 @@ "cmp_literal": 1 }, "packages/flow/openadapt_flow/decision/features.py": { - "cmp_literal": 4, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 4 }, "packages/flow/openadapt_flow/decision/labels.py": { "cmp_literal": 1 @@ -451,8 +547,8 @@ "cmp_literal": 1 }, "packages/flow/openadapt_flow/decision/synthetic.py": { - "says_success": 1, - "cmp_literal": 2 + "cmp_literal": 2, + "says_success": 1 }, "packages/flow/openadapt_flow/demo_proof.py": { "cmp_literal": 4, @@ -464,12 +560,6 @@ "packages/flow/openadapt_flow/desktop_record.py": { "swallow": 1 }, - "packages/flow/openadapt_flow/eligibility/artifact.py": { - "bool_fold": 1 - }, - "packages/flow/openadapt_flow/eligibility/client.py": { - "bool_fold": 1 - }, "packages/flow/openadapt_flow/emit/mcp_governed.py": { "cmp_literal": 2, "swallow": 2 @@ -481,26 +571,33 @@ "cmp_literal": 2 }, "packages/flow/openadapt_flow/execute/service.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 3 }, "packages/flow/openadapt_flow/execution_profiles.py": { - "says_success": 1, + "bool_fold": 17, "cmp_literal": 17, - "bool_fold": 17 + "says_success": 1, + "says_unchanged": 1 }, "packages/flow/openadapt_flow/extension_network.py": { "swallow": 1 }, "packages/flow/openadapt_flow/failure_signals.py": { + "cmp_literal": 6, "says_success": 1, - "cmp_literal": 6 + "says_unchanged": 1 }, "packages/flow/openadapt_flow/fault_gate.py": { - "cmp_literal": 2, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/fhir_setup.py": { + "swallow_wide": 1 }, "packages/flow/openadapt_flow/fleet/canary.py": { - "cmp_literal": 2 + "cmp_literal": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/fleet/hub.py": { "says_success": 4 @@ -508,6 +605,9 @@ "packages/flow/openadapt_flow/fleet/policy.py": { "cmp_literal": 1 }, + "packages/flow/openadapt_flow/fleet/status.py": { + "swallow_wide": 2 + }, "packages/flow/openadapt_flow/form_tx/playwright_surface.py": { "swallow": 14 }, @@ -518,42 +618,75 @@ "packages/flow/openadapt_flow/form_tx/types.py": { "says_success": 1 }, + "packages/flow/openadapt_flow/generate/compositional.py": { + "cmp_literal": 3, + "says_unchanged": 2, + "swallow": 1 + }, "packages/flow/openadapt_flow/generate/demo_analysis.py": { "slice_count": 2 }, + "packages/flow/openadapt_flow/generate/ensure_contract.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/generate/verify_contract.py": { + "empty_change_set": 1, + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/generate/zero_touch.py": { "cmp_literal": 4, + "slice_count": 1, "swallow": 2, - "slice_count": 1 + "swallow_wide": 3 }, "packages/flow/openadapt_flow/guard.py": { + "cmp_literal": 3, "says_success": 1, - "cmp_literal": 3 + "swallow_wide": 2 }, "packages/flow/openadapt_flow/halt_cleanup.py": { "bool_fold": 1, - "swallow": 5 + "swallow": 5, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/hard_invariants.py": { + "cmp_literal": 1, "says_success": 2, - "cmp_literal": 2, - "bool_fold": 2 + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/hooks/agents.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/hooks/cli.py": { + "says_success": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/hooks/engine.py": { + "cmp_literal": 6, + "says_success": 12, + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/hosted.py": { "cmp_literal": 5, + "empty_change_set": 1, "swallow": 8 }, "packages/flow/openadapt_flow/intake/param_gate.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/integrations/agents/__init__.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/integrations/agents/skills.py": { - "cmp_literal": 6 + "cmp_literal": 6, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/interactive_recorder.py": { - "swallow": 20 + "swallow": 20, + "swallow_wide": 15 }, "packages/flow/openadapt_flow/interchange/conformance.py": { "cmp_literal": 3 @@ -561,27 +694,35 @@ "packages/flow/openadapt_flow/interop/types.py": { "cmp_literal": 1 }, + "packages/flow/openadapt_flow/interruptions.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/ir.py": { - "cmp_literal": 10, "bool_fold": 1, + "cmp_literal": 10, "slice_count": 1 }, "packages/flow/openadapt_flow/jit/adapters.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/jit/authority.py": { "says_success": 1 }, "packages/flow/openadapt_flow/jit/compile_agent.py": { "cmp_literal": 3, - "swallow": 2 + "swallow": 2, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/jit/dispatch_authority.py": { "swallow": 1 }, + "packages/flow/openadapt_flow/jit/hosted_authority.py": { + "empty_change_set": 2 + }, "packages/flow/openadapt_flow/jit/lifecycle.py": { - "cmp_literal": 2, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 2 }, "packages/flow/openadapt_flow/learn.py": { "cmp_literal": 3 @@ -590,18 +731,29 @@ "bool_fold": 3 }, "packages/flow/openadapt_flow/learning/gate.py": { + "bool_fold": 1, "cmp_literal": 6, - "bool_fold": 1 + "empty_change_set": 2 }, "packages/flow/openadapt_flow/learning/interpreter.py": { "cmp_literal": 1 }, + "packages/flow/openadapt_flow/learning/library.py": { + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/learning/loop.py": { + "says_unchanged": 1 + }, "packages/flow/openadapt_flow/learning/teach.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/learning/trace.py": { "cmp_literal": 1 }, + "packages/flow/openadapt_flow/locale_invariants.py": { + "swallow_wide": 2 + }, "packages/flow/openadapt_flow/mockloan/fault_server.py": { "cmp_literal": 1 }, @@ -612,13 +764,18 @@ "swallow": 3 }, "packages/flow/openadapt_flow/network_capture.py": { - "swallow": 5 + "swallow": 5, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/offline_seal.py": { "swallow": 2 }, + "packages/flow/openadapt_flow/onprem_reboot.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/onprem_service.py": { - "bool_fold": 1 + "bool_fold": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/operator_profile.py": { "cmp_literal": 7 @@ -627,98 +784,122 @@ "cmp_literal": 2 }, "packages/flow/openadapt_flow/policy.py": { - "cmp_literal": 1, "bool_fold": 6, + "cmp_literal": 1, "slice_count": 1 }, "packages/flow/openadapt_flow/privacy.py": { "swallow": 5 }, + "packages/flow/openadapt_flow/production_qualification.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/provenance.py": { - "says_success": 1, - "bool_fold": 3 + "bool_fold": 3, + "says_success": 1 }, "packages/flow/openadapt_flow/public_seal.py": { "cmp_literal": 1, "swallow": 1 }, "packages/flow/openadapt_flow/qualification/__init__.py": { - "cmp_literal": 7, "bool_fold": 9, + "cmp_literal": 7, + "empty_change_set": 1, "swallow": 2 }, + "packages/flow/openadapt_flow/qualification/models.py": { + "says_unchanged": 1 + }, "packages/flow/openadapt_flow/qualification_drills.py": { "swallow": 6 }, "packages/flow/openadapt_flow/qualification_faults.py": { - "cmp_literal": 4, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 4 }, "packages/flow/openadapt_flow/qualification_identity_evidence.py": { - "cmp_literal": 3, - "bool_fold": 3 + "bool_fold": 3, + "cmp_literal": 3 }, "packages/flow/openadapt_flow/qualification_oracle_gate.py": { + "bool_fold": 2, "cmp_literal": 1, - "bool_fold": 2 + "empty_change_set": 1 }, "packages/flow/openadapt_flow/qualification_proposal.py": { "cmp_literal": 1 }, "packages/flow/openadapt_flow/qualify/campaign.py": { - "says_success": 3, - "cmp_literal": 4, "bool_fold": 4, - "slice_count": 1 + "cmp_literal": 4, + "empty_change_set": 3, + "says_success": 3, + "slice_count": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/qualify/faults.py": { "swallow": 5 }, "packages/flow/openadapt_flow/qualify/result.py": { + "cmp_literal": 15, "says_success": 3, - "cmp_literal": 15 + "swallow_wide": 1 }, "packages/flow/openadapt_flow/readback_ladder.py": { "cmp_literal": 1 }, "packages/flow/openadapt_flow/receipt.py": { - "says_success": 1, + "bool_fold": 8, "cmp_literal": 9, - "bool_fold": 8 + "empty_change_set": 1, + "says_success": 1 + }, + "packages/flow/openadapt_flow/receipt_record.py": { + "bool_fold": 1, + "cmp_literal": 3, + "swallow": 3 }, "packages/flow/openadapt_flow/reconcile/__init__.py": { - "says_success": 5, - "cmp_literal": 1, "bool_fold": 1, - "swallow": 1, - "else_success": 2 + "cmp_literal": 1, + "else_success": 2, + "says_success": 5, + "swallow": 1 }, "packages/flow/openadapt_flow/record_check_binding.py": { "bool_fold": 1 }, "packages/flow/openadapt_flow/record_check_synthesis.py": { "cmp_literal": 1, + "empty_change_set": 1, "swallow": 1 }, "packages/flow/openadapt_flow/record_sor.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/recorder.py": { - "swallow": 17 + "swallow": 17, + "swallow_wide": 9 + }, + "packages/flow/openadapt_flow/records/read.py": { + "swallow_wide": 1 }, "packages/flow/openadapt_flow/registry.py": { "swallow": 1 }, "packages/flow/openadapt_flow/repair/auto_repair.py": { - "says_success": 1, - "cmp_literal": 5, "bool_fold": 1, + "cmp_literal": 5, + "says_success": 1, "swallow": 1 }, "packages/flow/openadapt_flow/repair/campaign.py": { - "cmp_literal": 2, "bool_fold": 1, - "swallow": 1 + "cmp_literal": 2, + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/repair/cli.py": { "swallow": 2 @@ -726,11 +907,16 @@ "packages/flow/openadapt_flow/repair/cloud_review.py": { "swallow": 1 }, + "packages/flow/openadapt_flow/repair/element_identity.py": { + "swallow_wide": 3 + }, "packages/flow/openadapt_flow/repair/hold.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/repair/lifecycle.py": { - "cmp_literal": 5 + "cmp_literal": 5, + "says_unchanged": 4 }, "packages/flow/openadapt_flow/repair/preflight_queue.py": { "cmp_literal": 3, @@ -744,29 +930,35 @@ "swallow": 1 }, "packages/flow/openadapt_flow/repair/self_repair.py": { - "cmp_literal": 8, "bool_fold": 7, + "cmp_literal": 8, + "slice_count": 1, "swallow": 15, - "slice_count": 1 + "swallow_wide": 11 }, "packages/flow/openadapt_flow/repair/standard_change.py": { - "cmp_literal": 4, "bool_fold": 1, + "cmp_literal": 4, "swallow": 1 }, "packages/flow/openadapt_flow/report.py": { - "cmp_literal": 5, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 5 + }, + "packages/flow/openadapt_flow/request_binding.py": { + "swallow_wide": 1 }, "packages/flow/openadapt_flow/rest_setup.py": { - "swallow": 1 + "empty_change_set": 2, + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/retention.py": { "cmp_literal": 1 }, "packages/flow/openadapt_flow/retention_apply.py": { - "cmp_literal": 1, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 1 }, "packages/flow/openadapt_flow/reward/models.py": { "bool_fold": 1 @@ -775,50 +967,58 @@ "swallow": 1 }, "packages/flow/openadapt_flow/reward/worker.py": { - "cmp_literal": 1, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 1 }, "packages/flow/openadapt_flow/rl_env/desktop.py": { - "swallow": 4 + "swallow": 4, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/rl_env/environment.py": { - "swallow": 10 + "swallow": 10, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/rl_env/parallel.py": { - "cmp_literal": 2 + "cmp_literal": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/rl_env/record_grader.py": { - "cmp_literal": 2, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 2 }, "packages/flow/openadapt_flow/rl_env/reward.py": { - "says_success": 2, "cmp_literal": 5, - "swallow": 2 + "says_success": 2, + "swallow": 2, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/rl_env/trainers.py": { "swallow": 1 }, "packages/flow/openadapt_flow/rl_env/validate.py": { - "says_success": 1, - "bool_fold": 1 + "bool_fold": 1, + "says_success": 1 }, "packages/flow/openadapt_flow/rl_env/validate_desktop.py": { - "says_success": 1, "bool_fold": 1, + "says_success": 1, "swallow": 1 }, "packages/flow/openadapt_flow/rl_env/windows_guest.py": { - "swallow": 1, - "slice_count": 1 + "slice_count": 1, + "swallow": 1 }, "packages/flow/openadapt_flow/rollback.py": { - "cmp_literal": 3, "bool_fold": 2, - "swallow": 5 + "cmp_literal": 3, + "empty_change_set": 1, + "says_unchanged": 2, + "swallow": 5, + "swallow_wide": 3 }, "packages/flow/openadapt_flow/rollback_qualify.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/run_authorization.py": { "swallow": 2 @@ -827,15 +1027,19 @@ "bool_fold": 1, "swallow": 1 }, + "packages/flow/openadapt_flow/runner/business_decision_service.py": { + "empty_change_set": 1 + }, "packages/flow/openadapt_flow/runner/evidence.py": { "cmp_literal": 7, "slice_count": 1 }, "packages/flow/openadapt_flow/runner/hosted_adapter.py": { - "says_success": 1, - "cmp_literal": 7, "bool_fold": 1, - "swallow": 4 + "cmp_literal": 7, + "says_success": 1, + "swallow": 4, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/runner/verify.py": { "swallow": 2 @@ -844,18 +1048,22 @@ "swallow": 1 }, "packages/flow/openadapt_flow/runtime/actuators/form_eval.py": { - "swallow": 4 + "swallow": 4, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/runtime/actuators/session_headers.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/actuators/web_form.py": { - "swallow": 4 + "swallow": 4, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/admitted_composition.py": { - "says_success": 3, - "cmp_literal": 10, "bool_fold": 2, + "cmp_literal": 10, + "says_success": 3, + "says_unchanged": 1, "swallow": 3 }, "packages/flow/openadapt_flow/runtime/authorization.py": { @@ -869,18 +1077,23 @@ "swallow": 1 }, "packages/flow/openadapt_flow/runtime/composition.py": { - "says_success": 2, - "cmp_literal": 5, "bool_fold": 2, + "cmp_literal": 5, + "says_success": 2, "swallow": 1 }, "packages/flow/openadapt_flow/runtime/control_overlay.py": { - "says_success": 1 + "says_success": 1, + "says_unchanged": 1 }, "packages/flow/openadapt_flow/runtime/durable/attended.py": { - "cmp_literal": 11, "bool_fold": 1, - "swallow": 3 + "cmp_literal": 11, + "swallow": 3, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/durable/attended_service.py": { + "swallow_wide": 2 }, "packages/flow/openadapt_flow/runtime/durable/attended_state.py": { "slice_count": 1 @@ -891,8 +1104,8 @@ }, "packages/flow/openadapt_flow/runtime/durable/checkpoint.py": { "bool_fold": 1, - "swallow": 1, - "slice_count": 2 + "slice_count": 2, + "swallow": 1 }, "packages/flow/openadapt_flow/runtime/durable/continuation.py": { "cmp_literal": 2 @@ -904,15 +1117,17 @@ "slice_count": 1 }, "packages/flow/openadapt_flow/runtime/durable/resume.py": { - "cmp_literal": 1, "bool_fold": 1, + "cmp_literal": 1, "slice_count": 1 }, "packages/flow/openadapt_flow/runtime/effect_watch.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/effects/_common.py": { "bool_fold": 1, + "empty_change_set": 2, "slice_count": 1 }, "packages/flow/openadapt_flow/runtime/effects/adapter.py": { @@ -922,17 +1137,19 @@ "swallow": 1 }, "packages/flow/openadapt_flow/runtime/effects/deferred_report.py": { - "says_success": 1, - "cmp_literal": 3 + "cmp_literal": 3, + "says_success": 1 }, "packages/flow/openadapt_flow/runtime/effects/desktop_readback.py": { - "cmp_literal": 1 + "cmp_literal": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py": { - "swallow": 1, - "slice_count": 1 + "slice_count": 1, + "swallow": 1 }, "packages/flow/openadapt_flow/runtime/effects/effect.py": { + "empty_change_set": 1, "swallow": 1 }, "packages/flow/openadapt_flow/runtime/effects/effect_model.py": { @@ -940,7 +1157,8 @@ "swallow": 1 }, "packages/flow/openadapt_flow/runtime/effects/email_delivery.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/effects/fhir.py": { "swallow": 3 @@ -949,12 +1167,13 @@ "swallow": 2 }, "packages/flow/openadapt_flow/runtime/effects/frame.py": { - "says_success": 1, "cmp_literal": 2, + "says_success": 1, "slice_count": 1 }, "packages/flow/openadapt_flow/runtime/effects/fresh_session.py": { - "swallow": 2 + "swallow": 2, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/effects/graphql.py": { "swallow": 2 @@ -963,11 +1182,13 @@ "says_success": 1 }, "packages/flow/openadapt_flow/runtime/effects/late_write.py": { - "says_success": 1, - "cmp_literal": 2 + "cmp_literal": 2, + "says_success": 1 }, "packages/flow/openadapt_flow/runtime/effects/onscreen.py": { - "swallow": 5 + "empty_change_set": 1, + "swallow": 5, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/effects/pipeline_safety.py": { "swallow": 1 @@ -976,14 +1197,16 @@ "swallow": 3 }, "packages/flow/openadapt_flow/runtime/effects/smart_auth.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/effects/sql.py": { "swallow": 7 }, "packages/flow/openadapt_flow/runtime/effects/ui_readback.py": { "cmp_literal": 3, - "swallow": 10 + "swallow": 10, + "swallow_wide": 6 }, "packages/flow/openadapt_flow/runtime/grounder.py": { "swallow": 4 @@ -995,55 +1218,74 @@ "cmp_literal": 1 }, "packages/flow/openadapt_flow/runtime/healing/perturbation.py": { - "cmp_literal": 1, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/runtime/healing/pipeline.py": { + "says_unchanged": 1 }, "packages/flow/openadapt_flow/runtime/hover_evidence.py": { "swallow": 1 }, "packages/flow/openadapt_flow/runtime/identity.py": { - "slice_count": 1 + "slice_count": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/identity_census.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/identity_looks.py": { "swallow": 5 }, + "packages/flow/openadapt_flow/runtime/layout_drift.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/runtime/list_guard.py": { "swallow": 1 }, "packages/flow/openadapt_flow/runtime/preparation.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/process_v1.py": { + "cmp_literal": 10, "says_success": 1, - "cmp_literal": 10 + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/runtime/readback_pipeline.py": { + "swallow_wide": 2 }, "packages/flow/openadapt_flow/runtime/remote_vlm.py": { "swallow": 1 }, "packages/flow/openadapt_flow/runtime/replayer.py": { - "cmp_literal": 26, "bool_fold": 12, + "cmp_literal": 26, + "empty_change_set": 3, + "slice_count": 1, "swallow": 62, - "slice_count": 1 + "swallow_wide": 47 }, "packages/flow/openadapt_flow/runtime/resolver.py": { "cmp_literal": 1, - "swallow": 3 + "swallow": 3, + "swallow_wide": 1 }, "packages/flow/openadapt_flow/runtime/surfaces.py": { - "swallow": 9 + "swallow": 9, + "swallow_wide": 9 }, "packages/flow/openadapt_flow/runtime/variant_router.py": { - "cmp_literal": 1, "bool_fold": 1, + "cmp_literal": 1, "swallow": 3 }, "packages/flow/openadapt_flow/runtime/worklist_pool.py": { "cmp_literal": 3, - "swallow": 3 + "says_unchanged": 1, + "swallow": 3, + "swallow_wide": 8 }, "packages/flow/openadapt_flow/runtime_validation.py": { "cmp_literal": 1 @@ -1061,93 +1303,113 @@ "packages/flow/openadapt_flow/seal_timestamp.py": { "slice_count": 1 }, + "packages/flow/openadapt_flow/secret_inputs.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/sections.py": { "slice_count": 1 }, + "packages/flow/openadapt_flow/services/vlm_service/batching.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/shadow.py": { - "says_success": 1, "bool_fold": 1, - "swallow": 4 + "empty_change_set": 1, + "says_success": 1, + "swallow": 4, + "swallow_wide": 7 }, "packages/flow/openadapt_flow/shadow_db.py": { - "cmp_literal": 1, "bool_fold": 1, - "swallow": 2 + "cmp_literal": 1, + "swallow": 2, + "swallow_wide": 3 }, "packages/flow/openadapt_flow/shadow_report.py": { - "says_success": 1, - "cmp_literal": 3 + "cmp_literal": 3, + "says_success": 1 }, "packages/flow/openadapt_flow/skills.py": { "swallow": 2 }, "packages/flow/openadapt_flow/subroutines.py": { - "cmp_literal": 2, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 2 }, "packages/flow/openadapt_flow/taskgen/validate.py": { - "says_success": 1, - "cmp_literal": 2, "bool_fold": 3, - "swallow": 2 + "cmp_literal": 2, + "says_success": 1, + "swallow": 2, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/taskgen/workbench.py": { "swallow": 2 }, "packages/flow/openadapt_flow/teach_scope.py": { - "cmp_literal": 1, "bool_fold": 1, - "swallow": 8 + "cmp_literal": 1, + "swallow": 8, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/terminal_verification_v2.py": { - "says_success": 1, + "bool_fold": 7, "cmp_literal": 30, - "bool_fold": 7 + "says_success": 1 }, "packages/flow/openadapt_flow/transaction.py": { - "says_success": 1, - "cmp_literal": 13, "bool_fold": 7, - "swallow": 1, - "slice_count": 1 + "cmp_literal": 13, + "says_success": 1, + "says_unchanged": 1, + "slice_count": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/transforms.py": { + "says_unchanged": 1 }, "packages/flow/openadapt_flow/tutorial.py": { - "cmp_literal": 5, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 5 }, "packages/flow/openadapt_flow/tx/induce.py": { - "swallow": 1, - "slice_count": 3 + "empty_change_set": 1, + "slice_count": 3, + "swallow": 1 }, "packages/flow/openadapt_flow/tx/lens.py": { + "else_success": 1, "says_success": 1, - "else_success": 1 + "swallow_wide": 1 }, "packages/flow/openadapt_flow/tx/wire_tap.py": { "bool_fold": 2, - "swallow": 3 + "swallow": 3, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/undo_proposal.py": { - "cmp_literal": 5, "bool_fold": 1, + "cmp_literal": 5, + "slice_count": 1, "swallow": 4, - "slice_count": 1 + "swallow_wide": 3 }, "packages/flow/openadapt_flow/validation/behavioral_generalization.py": { - "says_success": 1, + "bool_fold": 2, "cmp_literal": 3, - "bool_fold": 2 + "says_success": 1, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/validation/dense_surface.py": { - "cmp_literal": 7, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 7 }, "packages/flow/openadapt_flow/validation/hardening/fixtures.py": { "swallow": 2 }, "packages/flow/openadapt_flow/validation/identity_ladder.py": { - "cmp_literal": 2, - "bool_fold": 1 + "bool_fold": 1, + "cmp_literal": 2 }, "packages/flow/openadapt_flow/validation/identity_looks_dense.py": { "cmp_literal": 7, @@ -1165,26 +1427,41 @@ "packages/flow/openadapt_flow/validation/vlm_identity_probe.py": { "swallow": 1 }, + "packages/flow/openadapt_flow/variants.py": { + "says_unchanged": 1 + }, "packages/flow/openadapt_flow/verifier.py": { - "says_success": 4, "cmp_literal": 39, + "says_success": 4, "swallow": 9 }, + "packages/flow/openadapt_flow/verifier_audit/runner.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/verifier_audit/targets/agentdojo.py": { + "swallow_wide": 1 + }, "packages/flow/openadapt_flow/verifier_audit/targets/appworld_worker.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 }, "packages/flow/openadapt_flow/verify_run.py": { - "says_success": 4, - "cmp_literal": 36, "bool_fold": 2, - "swallow": 5 + "cmp_literal": 36, + "empty_change_set": 1, + "says_success": 4, + "swallow": 5, + "swallow_wide": 4 }, "packages/flow/openadapt_flow/vision/imgops.py": { "swallow": 2 }, + "packages/flow/openadapt_flow/vision/settle.py": { + "swallow_wide": 5 + }, "packages/flow/openadapt_flow/visualize/builder.py": { - "cmp_literal": 3, - "bool_fold": 2 + "bool_fold": 2, + "cmp_literal": 3 }, "packages/flow/openadapt_flow/visualize/projection.py": { "cmp_literal": 1 @@ -1193,7 +1470,11 @@ "cmp_literal": 1 }, "packages/flow/openadapt_flow/wire_check.py": { - "swallow": 1 + "swallow": 1, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/wrap/__init__.py": { + "swallow_wide": 2 }, "packages/flow/openadapt_flow/wrap/candidate.py": { "swallow": 1 @@ -1210,23 +1491,24 @@ "swallow": 2 }, "packages/flow/openadapt_flow/write_ledger.py": { - "says_success": 1, - "cmp_literal": 7 + "cmp_literal": 7, + "says_success": 1 }, "packages/flow/openadapt_flow/write_receipt.py": { - "cmp_literal": 9, - "bool_fold": 3 + "bool_fold": 3, + "cmp_literal": 9 }, "scripts/ci/attestation.py": { "bool_fold": 2 }, "scripts/ci/check_windows_governed_safety.py": { - "says_success": 2, - "cmp_literal": 4 + "cmp_literal": 4, + "says_success": 2 }, "scripts/ci/flow_shard_measurement.py": { + "bool_fold": 1, "cmp_literal": 1, - "bool_fold": 1 + "swallow_wide": 1 }, "scripts/ci/newest_green.py": { "cmp_literal": 2 @@ -1236,7 +1518,9 @@ }, "scripts/ci/protected_safety_review.py": { "cmp_literal": 2, - "swallow": 1 + "empty_change_set": 1, + "swallow": 1, + "swallow_wide": 1 }, "scripts/ci/tests/test_flow_shard_measurement.py": { "cmp_literal": 2 diff --git a/packages/flow/tests/failopen/harness.py b/packages/flow/tests/failopen/harness.py index 4f64a34612..7b964c1cea 100644 --- a/packages/flow/tests/failopen/harness.py +++ b/packages/flow/tests/failopen/harness.py @@ -18,8 +18,17 @@ must not pass. - P4: reordering the results (M6) changes nothing. - P5: the default of a knob is the strictest value of its sweep (M9). +- P6: the verdict has three levels, REFUTED < NOT_CHECKED < HELD (a site + where an unread result outranks a refuted one, because it may have + changed something, states that in ``precedence``). A mutation that keeps every result and adds a copy or + turns one bad never raises it at any level; a reordering leaves it + exactly where it was (P4). A + mutation that removes evidence may move REFUTED to NOT_CHECKED, since a + refutation it removed is no longer known, but never to HELD (P1). - P7: an outcome that may have changed something never maps to one that says nothing changed, or to a plain "failed" (M12). +- P8: "nothing else changed" holds only on a complete read: marking the scope + read partial (M15) must not pass. An uncaught exception from the site counts as not-pass: a check that crashes fails closed. ``docs/FAIL_CLOSED.md`` explains the classes behind each @@ -33,8 +42,10 @@ from dataclasses import dataclass, field from typing import Any, Optional +from openadapt_flow.verdict import Status + #: Mutator ids whose mutated evidence must not pass, by property. -P2 = frozenset({"M1", "M2", "M3", "M4", "M5", "M7", "M10", "M14"}) +P2 = frozenset({"M1", "M2", "M3", "M4", "M5", "M7", "M10", "M14", "M15", "M16"}) P3 = frozenset({"M8", "M11"}) #: Mutators P1 applies to: each one only removes or corrupts evidence. A #: value perturbation (M10), a rebuilt set (M2), a dropped result (M1, which @@ -141,6 +152,9 @@ class SiteSpec: plan: Optional[Lens] = None #: A refuted (or not-checked) copy of one result item. bad_item: Optional[Callable[[Any], Any]] = None + #: False when ``bad_item`` makes an extra bad result rather than a bad + #: version of the one it is given: M16 (turn a result bad) is skipped. + bad_replaces: bool = True #: M2: build evidence with ``n`` results, the last one bad. inflate: Optional[Callable[[Any, int], Any]] = None limit: Optional[int] = None @@ -174,6 +188,16 @@ class SiteSpec: #: Any other failure, or one of these going away, fails the test. known: frozenset[str] = frozenset() notes: dict[str, str] = field(default_factory=dict) + #: The verdict's level (P6). Without it a pass is HELD and anything else + #: NOT_CHECKED, so only the top level is tested. + level: Optional[Callable[[Any], Status]] = None + #: P6's order below HELD, worst first. REFUTED is worst unless the site + #: states (in ``notes["precedence"]``) that an unread result outranks a + #: refuted one, as ``Settlement.label(precedence=...)`` lets it. + precedence: tuple[Status, Status] = (Status.REFUTED, Status.NOT_CHECKED) + #: M15: evidence whose "nothing else changed" read is partial, one per + #: completeness flag. Each must not pass. + partial: Optional[Callable[[Any], list[tuple[str, Any]]]] = None @dataclass(frozen=True) @@ -214,6 +238,30 @@ def safe_pass(spec: SiteSpec, evidence: Any) -> bool: return bool(spec.is_pass(out)) +def safe_level(spec: SiteSpec, evidence: Any) -> Status: + """The verdict's level; a crash is NOT_CHECKED. HELD needs ``is_pass`` + too, so a ``level`` that says HELD for a not-pass can't lift it.""" + + try: + out = spec.run(evidence) + passed = bool(spec.is_pass(out)) + got = spec.level(out) if spec.level is not None else None + except Exception: # noqa: BLE001 - a crash is a not-pass + return Status.NOT_CHECKED + if passed: + return Status.HELD + if got is None or got is Status.HELD: + return Status.NOT_CHECKED + return got + + +def rank(spec: SiteSpec, status: Status) -> int: + """P6's order: 0 for the worst level, 2 for HELD. By default + REFUTED < NOT_CHECKED < HELD.""" + + return 2 if status is Status.HELD else spec.precedence.index(status) + + def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: """Every property failure for ``spec``; empty means the site holds.""" @@ -237,6 +285,7 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: ) ) continue + level = safe_level(spec, seed.evidence) for m in mutators.mutations(spec, seed): if only is not None and m.id not in only: continue @@ -247,6 +296,16 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: failures.append(Failure(spec.id, m.id, m.prop, f"{at}: {problem}")) continue after = safe_pass(spec, m.evidence) + moved = safe_level(spec, m.evidence) + if m.adverse and rank(spec, moved) > rank(spec, level): + failures.append( + Failure( + spec.id, + m.id, + "P6", + f"{at}: {m.label}: raised {level.value} to {moved.value}", + ) + ) if not got and after and m.id in P1_IDS: failures.append( Failure( @@ -261,7 +320,7 @@ def run_site(spec: SiteSpec, only: Optional[set[str]] = None) -> list[Failure]: failures.append( Failure(spec.id, m.id, prop, f"{at}: {m.label}: still passes") ) - elif m.expect == "same" and after != got: + elif m.expect == "same" and (after != got or moved is not level): failures.append( Failure(spec.id, m.id, "P4", f"{at}: {m.label}: changed") ) diff --git a/packages/flow/tests/failopen/mutators.py b/packages/flow/tests/failopen/mutators.py index 63a24e8691..4ccd7fa505 100644 --- a/packages/flow/tests/failopen/mutators.py +++ b/packages/flow/tests/failopen/mutators.py @@ -2,13 +2,15 @@ M1 drop, M2 inflate past the limit, M3 empty, M4 probe raises, M5 missing or null field, M6 reorder, M7 duplicate, M8 subject swap, M9 knob sweep, M10 value -perturb, M11 corpus, M12 outcome after delivery, M14 unknown code. M13 (a +perturb, M11 corpus, M12 outcome after delivery, M14 unknown code, M15 a +"nothing else changed" read made partial, M16 one result turned bad. M13 (a trust-source swap) waits for the signer-registry vectors (FAIL_CLOSED.md, follow-ups). """ from __future__ import annotations +import copy import json from collections.abc import Callable, Iterator from dataclasses import dataclass @@ -48,6 +50,9 @@ class Mutation: #: problem description, or "" when it holds. check: Optional[Callable[[], str]] = None prop: str = "" + #: Keeps every result and adds or turns one adverse: the level may not + #: rise at all (P6). + adverse: bool = False def perturbations(value: Any) -> list[tuple[str, Any]]: @@ -95,9 +100,13 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: ) if spec.items is not None and not (spec.vacuous and spec.plan is None): empty = spec.items.set(ev, []) + label = "no results" if spec.plan is not None and spec.vacuous is None: empty = spec.plan.set(empty, []) - yield Mutation("M3", "no results and no plan", empty, "not_pass") + label = "no results and no plan" + elif spec.plan is not None: + label = "no results, the plan kept" + yield Mutation("M3", label, empty, "not_pass") if spec.probe_raise is not None: for exc in PROBE_ERRORS: yield Mutation( @@ -127,16 +136,33 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: rev = spec.plan.set(rev, list(reversed(spec.plan.get(ev)))) yield Mutation("M6", "results reordered", rev, "same") if items: + # A separate, equal copy: the site must judge it like the original, + # not lean on the kernel noticing the same object twice. yield Mutation( - "M7", "a result repeated", spec.items.set(ev, items + [items[0]]) - ) # type: ignore[union-attr] + "M7", + "a result repeated", + spec.items.set(ev, items + [copy.deepcopy(items[0])]), # type: ignore[union-attr] + adverse=True, + ) if spec.bad_item is not None: yield Mutation( "M7", "a result repeated with a bad copy", - spec.items.set(ev, items + [spec.bad_item(items[0])]), + spec.items.set(ev, items + [spec.bad_item(items[0])]), # type: ignore[union-attr] + "not_pass", + adverse=True, + ) + if spec.bad_item is not None and seed.correct_pass and spec.bad_replaces: + # Every result of a pass seed held, so turning the first one bad + # (``bad_item`` is a bad copy of it) must leave no pass. + turned = [spec.bad_item(items[0]), *items[1:]] + yield Mutation( + "M16", + "the first result turned bad", + spec.items.set(ev, turned), # type: ignore[union-attr] "not_pass", - ) # type: ignore[union-attr] + adverse=True, + ) if spec.subject is not None: yield Mutation( "M8", @@ -169,6 +195,9 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: check=_corpus_check(spec, mutated, entry), prop="P3", ) + if spec.partial is not None: + for label, partial in spec.partial(ev): + yield Mutation("M15", f"{label} partial", partial, "not_pass") if spec.knob is not None and seed.correct_pass: yield Mutation( "M9", f"knob {spec.knob.name}", check=_knob_check(spec, ev), prop="P5" diff --git a/packages/flow/tests/failopen/selftest/_v_hard_invariants_pre.py b/packages/flow/tests/failopen/selftest/_v_hard_invariants_pre.py new file mode 100644 index 0000000000..45a957d113 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_hard_invariants_pre.py @@ -0,0 +1,162 @@ +# vendored from 9b6956be37dd:packages/flow/openadapt_flow/hard_invariants.py, lines 16-155, for the harness self-test only +# ruff: noqa: F401, F841, I001 +"""hard_invariants before it moved onto the kernel, for the differential +test (test_positive_control_migration.py). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the stubs above them are +not.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable, Literal, Optional, TypeGuard + + +def verdict_site(*_a: Any, **_k: Any) -> Callable[[Any], Any]: + return lambda fn: fn + + +# vendored: 9b6956be37dd:packages/flow/openadapt_flow/hard_invariants.py 16-155 +# fmt: off +InvariantName = Literal["declared_scope", "at_most_one", "no_undeclared_deletes"] +InvariantStatus = Literal["held", "refuted", "not_checked"] +LAYER_SCHEMA = "openadapt.hard-invariants/v1" + + +@dataclass(frozen=True) +class InvariantResult: + name: InvariantName + status: InvariantStatus + reason: str + observed_count: Optional[int] = None + + def evidence(self) -> dict[str, object]: + return { + "name": self.name, + "status": self.status, + "reason": self.reason, + "observed_count": self.observed_count, + } + + +@dataclass(frozen=True) +class HardInvariantVerdict: + checks: tuple[InvariantResult, ...] + + @property + def status(self) -> InvariantStatus: + if any(c.status == "refuted" for c in self.checks): + return "refuted" + if ( + {c.name for c in self.checks} + != {"declared_scope", "at_most_one", "no_undeclared_deletes"} + or len(self.checks) != 3 + or any(c.status != "held" for c in self.checks) + ): + return "not_checked" + return "held" + + def evidence(self) -> dict[str, object]: + return { + "schema_version": LAYER_SCHEMA, + "status": self.status, + "checks": [c.evidence() for c in self.checks], + "model_calls": 0, + } + + +def _count(value: object) -> TypeGuard[int]: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +def _zero( + name: InvariantName, + count: Optional[int], + complete: bool, + *, + held: str, + refuted: str, + unknown: str, +) -> InvariantResult: + if not _count(count): + return InvariantResult(name, "not_checked", "invalid_or_missing_observation") + assert count is not None + if count > 0: + return InvariantResult(name, "refuted", refuted, count) + return InvariantResult( + name, + "held" if complete is True else "not_checked", + held if complete is True else unknown, + count, + ) + + +@verdict_site("hard_invariants.judge", classes="C2 C5") +def judge_hard_invariants( + *, + outside_scope_changes: Optional[int], + undeclared_deletes: Optional[int], + before_matches: Optional[int], + after_matches: Optional[int], + history_matches: Optional[int], + scope_complete: bool, + deletes_complete: bool, + history_complete: bool, + search_complete: bool, +) -> HardInvariantVerdict: + """Judge three fixed predicates over authoritative reader observations. + + ``history_matches`` counts distinct records carrying the declared business + key across the read window, including records later deleted. A + current-state count is never a substitute for that history. One observed violation refutes even when + other reads are incomplete; otherwise incomplete reads remain unknown. + """ + + scope = _zero( + "declared_scope", + outside_scope_changes, + scope_complete, + held="no_outside_scope_changes", + refuted="outside_scope_changes", + unknown="scope_history_incomplete", + ) + deletes = _zero( + "no_undeclared_deletes", + undeclared_deletes, + deletes_complete, + held="no_undeclared_deletes", + refuted="undeclared_deletes", + unknown="delete_history_incomplete", + ) + counts = (before_matches, after_matches, history_matches) + known = [n for n in counts if _count(n)] + maximum = max(known) if known else None + if maximum is not None and maximum > 1: + cardinality = InvariantResult( + "at_most_one", "refuted", "duplicate_business_key", maximum + ) + elif ( + not all(_count(n) for n in counts) + or history_complete is not True + or search_complete is not True + ): + cardinality = InvariantResult( + "at_most_one", + "not_checked", + "business_key_history_or_search_incomplete", + maximum, + ) + elif _count(history_matches) and maximum is not None and history_matches < maximum: + cardinality = InvariantResult( + "at_most_one", + "not_checked", + "business_key_observations_inconsistent", + maximum, + ) + else: + cardinality = InvariantResult( + "at_most_one", "held", "at_most_one_business_record", maximum + ) + return HardInvariantVerdict((scope, cardinality, deletes)) +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/_v_receipt_lines_pre.py b/packages/flow/tests/failopen/selftest/_v_receipt_lines_pre.py new file mode 100644 index 0000000000..cdb8a745e7 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_receipt_lines_pre.py @@ -0,0 +1,99 @@ +# vendored from 9b6956be37dd:packages/flow/openadapt_flow/receipt_record.py, lines 57-118 and 233-236, for the harness self-test only +# ruff: noqa: F401, F841, I001 +"""receipt_record's line judge and tally before they moved onto the kernel, +for the differential test (test_receipt_lines_migration.py). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the wrappers around them +are not.""" + +from __future__ import annotations + +from collections import Counter +from typing import Any, Mapping + + +# vendored: 9b6956be37dd:packages/flow/openadapt_flow/receipt_record.py 57-118 +# fmt: off +def _line( + index: int, result: Mapping[str, Any], ledger: Mapping[str, Any] | None +) -> dict[str, Any]: + from openadapt_flow.check_level import CheckLevel, from_verification_tier + + evidence = result.get("effect_evidence") or [] + declared = Counter(result.get("effect_contract_hashes") or []) + ledger_effects = ledger["effects"] if ledger is not None else [] + # A declared effect can lack a bound hash when the run stopped before the + # reader ran. Keep the attempted write and withhold its verification. + ledger_matches = ( + ledger is None + or Counter(effect.get("contract_hash") for effect in ledger_effects) == declared + ) + observed = Counter(item["effect_contract_hash"] for item in evidence) + check = "not_checked" + strength = "same_screen" if result.get("postconditions_ok") is True else "none" + # A negative aggregate flag covers both a contradiction and an unavailable + # reader. Only complete, contract-bound read evidence distinguishes them. + if declared and ledger_matches and declared == observed: + verdicts = {item["final_verdict"] for item in evidence} + levels = [ + from_verification_tier(item["verification_tier"]) + if type(item.get("verification_tier")) is int + else CheckLevel.UNCHECKED + for item in evidence + ] + if verdicts <= {"confirmed", "refuted"} and min(levels) > CheckLevel.UNCHECKED: + if "refuted" in verdicts: + check = "refuted" + elif ( + verdicts == {"confirmed"} + and result.get("effect_verified") is True + and all(item.get("observed_effect") == "present" for item in evidence) + and (ledger is None or ledger.get("status") == "confirmed") + ): + check = "confirmed" + if check != "not_checked": + strength = ( + "read_back" + if min(levels) >= CheckLevel.SYSTEM_OF_RECORD + else "same_screen" + ) + not_checked: list[str] = [] + if result.get("effect_approved_unverified") is True: + not_checked.append("approved_unverified") + if not declared and not ledger_effects: + not_checked.append("effect_not_declared") + if not result.get("effect_field_checks"): + not_checked.append("field_values") + if result.get("postconditions_ok") is None: + not_checked.append("postconditions") + return { + "step": index, + "target_kind": "api" if result.get("actuation") == "api" else "gui", + "operation": "irreversible_write" + if result.get("risk") == "irreversible" + else "write", + "check": check, + "strength": strength, + "not_checked": not_checked, + } +# fmt: on + + +def tally(lines: list[dict[str, Any]]) -> dict[str, int]: + # vendored: 9b6956be37dd:packages/flow/openadapt_flow/receipt_record.py 233-236 + # fmt: off + tally = { + k: sum(1 for line in lines if line["check"] == k) + for k in ("confirmed", "refuted", "not_checked") + } + # fmt: on + return tally + + +def unverified(lines: list[dict[str, Any]]) -> bool: + """The old rule (line 240, not vendored): any refuted or not-checked + line kept a VERIFIED run from VERIFIED.""" + + counts = tally(lines) + return bool(counts["refuted"] or counts["not_checked"]) diff --git a/packages/flow/tests/failopen/selftest/_v_versions_pre.py b/packages/flow/tests/failopen/selftest/_v_versions_pre.py new file mode 100644 index 0000000000..222bce0b6d --- /dev/null +++ b/packages/flow/tests/failopen/selftest/_v_versions_pre.py @@ -0,0 +1,265 @@ +# vendored from 9b6956be37dd:packages/flow/openadapt_flow/runtime/effects/versions.py, lines 152-386, for the harness self-test only +# ruff: noqa: F401, F841, I001 +"""judge_versions before it moved onto the kernel, for the differential +test (test_positive_control_migration.py). + +Only the lines between ``# fmt: off`` and ``# fmt: on`` markers that +follow a ``# vendored:`` comment are verbatim; the imports and stubs above +them are not.""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping, Sequence +from typing import Any, Callable, Optional + +from openadapt_flow.runtime.effects.versions import ( + _WHOLE, + FrameVersions, + VersionStatus, + VersionVerdict, +) + + +def verdict_site(*_a: Any, **_k: Any) -> Callable[[Any], Any]: + return lambda fn: fn + + +# vendored: 9b6956be37dd:packages/flow/openadapt_flow/runtime/effects/versions.py 152-386 +# fmt: off +def _get(row: Mapping[str, Any], path: str) -> Any: + if path in row: + return row[path] + node: Any = row + for part in path.split("."): + if not isinstance(node, Mapping) or part not in node: + return None + node = node[part] + return node + + +def _text(value: Any) -> Optional[str]: + if value is None: + return None + text = str(value) + return text if text != "" else None + + +def _mac(key: bytes, label: str, *parts: str) -> str: + body = "\x1f".join((label, *parts)).encode("utf-8") + return hashlib.blake2b(body, key=key[:64], digest_size=16).hexdigest() + + +def seal_versions( + spec: FrameVersions, rows: Optional[Sequence[Mapping[str, Any]]], key: bytes +) -> dict[str, Any]: + """The baseline's record of versions: per record MAC, the version MACs + and (whole numbers only) the highest version.""" + + if rows is None: + return {"reachable": False} + records: dict[str, dict[str, Any]] = {} + for row in rows: + record = _text(_get(row, spec.record_field)) + version = _text(_get(row, spec.version_field)) + if record is None: + continue # a row that names no record is no record's version + entry = records.setdefault( + _mac(key, "record", record), + {"versions": [], "max": None, "whole": True, "null": False, "dup": False}, + ) + if version is None: + # A null version can't tell two saves apart. + entry["whole"] = False + entry["null"] = True + continue + mac = _mac(key, "version", record, version) + if mac in entry["versions"]: + entry["dup"] = True # two rows, one version: a save could hide + entry["versions"].append(mac) + if _WHOLE.match(version): + entry["max"] = max(int(version), entry["max"] or 0) + else: + entry["whole"] = False + for entry in records.values(): + entry["versions"] = sorted(set(entry["versions"])) + return {"reachable": True, "records": records} + + +def _resolve_self( + spec: FrameVersions, params: Mapping[str, object] +) -> Optional[set[str]]: + out: set[str] = set() + for expr in spec.self_actors: + value = expr.resolve(params) + if value is None or value == "": + return None + out.add(str(value)) + return out + + +@verdict_site("versions.judge", classes="C1 C5") +def judge_versions( + spec: FrameVersions, + stored: Mapping[str, Any], + rows: Optional[Sequence[Mapping[str, Any]]], + targets: Sequence[tuple[Optional[str], bool, bool]], + key: bytes, + params: Mapping[str, object] = {}, +) -> VersionVerdict: + """Judge the targets' versions in the window. + + ``stored``: :func:`seal_versions` of the baseline read. ``rows``: the read + after the save (None when it failed). ``targets``: per record a confirmed + write effect matched, its ``target_field`` value (None when the record + has none), whether it existed before the write, and whether the record + changed in the window. + """ + + if not stored.get("reachable") or rows is None: + return VersionVerdict( + "not_checked", + "unreadable", + reason="the target's versions could not be read, before or after the write", + ) + mine: set[str] = set() + if spec.author_field: + resolved = _resolve_self(spec, params) + if resolved is None: + return VersionVerdict( + "not_checked", + "self_unresolved", + reason="frame.versions.self references a parameter the run did not supply", + ) + mine = resolved + before: Mapping[str, Any] = stored.get("records") or {} + out = VersionVerdict("held") + worst: Optional[VersionVerdict] = None + + def stop(status: VersionStatus, problem: str, reason: str) -> None: + nonlocal worst + if worst is None or (worst.status == "not_checked" and status == "refuted"): + worst = VersionVerdict(status, problem, reason=reason) + + seen: set[Optional[str]] = set() + for target, existed, changed in targets: + if target in seen: + continue + seen.add(target) + if target is None: + stop( + "not_checked", + "no_target_id", + f"a target record has no {spec.target_field or 'identity'} field, " + "so its versions can't be found", + ) + continue + base = before.get(_mac(key, "record", target)) + if base is None: + if existed: + stop( + "not_checked", + "missing", + "the target existed before the write but had no version", + ) + continue # created in the window: no earlier version to overwrite + out.targets += 1 + now = [r for r in rows if _text(_get(r, spec.record_field)) == target] + if not now: + stop("not_checked", "missing", "the target has no version after the write") + continue + old = set(base.get("versions") or []) + versions = [_text(_get(r, spec.version_field)) for r in now] + if base.get("null") or any(v is None for v in versions): + stop( + "not_checked", + "null_version", + "a version of the target reads as null, so saves can't be told apart", + ) + continue + macs = [_mac(key, "version", target, str(v)) for v in versions] + if base.get("dup") or len(set(macs)) != len(macs): + stop( + "not_checked", + "duplicate_version", + "two rows of the target's versions hold the same version, so a " + "save could hide behind another", + ) + continue + fresh = [(v, r) for v, r, m in zip(versions, now, macs) if m not in old] + out.new_versions += len(fresh) + if changed and not fresh: + stop( + "not_checked", + "no_new_version", + "the target changed in the window but no new version of it was " + "read, so who saved it can't be told", + ) + continue + if spec.author_field and not old <= set(macs): + stop( + "not_checked", + "history_changed", + "a version of the target read before the write is gone after it: " + "the read isn't a history that only grows, so a save in the " + "window could be hidden", + ) + continue + if spec.author_field: + for _version, r in fresh: + author = _text(_get(r, spec.author_field)) + if author is None: + stop( + "not_checked", + "no_author", + "a new version of the target names no author, so it " + "can't be told from another user's save", + ) + elif author in mine: + out.own_versions += 1 + else: + stop( + "refuted", + "another_author", + "lost update: another user saved a version of the target " + "inside the window, and the agent's save came after it " + "or beside it", + ) + continue + # No authors: count whole-number steps. + values = [_text(_get(r, spec.version_field)) for r in now] + if not base.get("whole") or any( + v is None or not _WHOLE.match(v) for v in values + ): + stop( + "not_checked", + "not_a_number", + "the target's versions aren't whole numbers, and no author is " + "read, so the steps in the window can't be counted", + ) + continue + steps = max(int(v) for v in values if v is not None) - int(base["max"] or 0) + if steps < 0 or (steps == 0 and fresh): + stop( + "refuted", + "went_back", + "the target's version went back or was replaced in the window", + ) + elif steps > 1 or len(fresh) > 1: + stop( + "refuted", + "extra_steps", + f"lost update: the target moved {max(steps, len(fresh))} versions " + "in the window; one save is the agent's, and no author is read " + "to say whose the others are", + ) + if worst is not None: + worst.targets, worst.new_versions, worst.own_versions = ( + out.targets, + out.new_versions, + out.own_versions, + ) + return worst + out.reason = f"{out.targets} target(s): every new version is the agent's own" + return out +# fmt: on diff --git a/packages/flow/tests/failopen/selftest/specs.py b/packages/flow/tests/failopen/selftest/specs.py index f5bdf43e45..a96d02ec57 100644 --- a/packages/flow/tests/failopen/selftest/specs.py +++ b/packages/flow/tests/failopen/selftest/specs.py @@ -119,6 +119,9 @@ def run(ev: dict[str, Any]) -> Any: ], items=key("events"), bad_item=lambda e: {**e, "id": e["id"] + "-dup"}, + # The bad item is a second own event beside the first, not a bad + # version of it. + bad_replaces=False, inflate=lambda ev, n: { **ev, "events": [own, stale] @@ -456,13 +459,13 @@ def _relay(fn: Any, id: str) -> SiteSpec: "S9_aggregate_empty", verify_run_folds.aggregate_spec, _v_s9_verify_run_pre._aggregate, - verify_run._aggregate, + verify_run_folds._unplanned(verify_run._aggregate), ), ( "S9_observed_empty", verify_run_folds.observed_spec, _v_s9_verify_run_pre._observed, - verify_run._observed, + verify_run_folds._unplanned(verify_run._observed), ), ( "S9_readback_class_empty", diff --git a/packages/flow/tests/failopen/sites/hard_invariants.py b/packages/flow/tests/failopen/sites/hard_invariants.py index b941ab438c..3793964b85 100644 --- a/packages/flow/tests/failopen/sites/hard_invariants.py +++ b/packages/flow/tests/failopen/sites/hard_invariants.py @@ -1,11 +1,13 @@ -"""hard_invariants.judge: a positive control. The fold is correct on main; -the harness must not flag it (kill criterion 2).""" +"""hard_invariants.judge: a positive control, built on the kernel. "No +change outside the scope" and "no undeclared delete" are "nothing else +changed" claims, so a partial read of either must not hold (M15).""" from __future__ import annotations from typing import Any from openadapt_flow.hard_invariants import judge_hard_invariants +from openadapt_flow.verdict import Status from tests.failopen.harness import Seed, SiteSpec, key, register GOOD: dict[str, Any] = { @@ -38,6 +40,7 @@ def put(ev: dict[str, Any], value: dict[str, Any]) -> None: target="openadapt_flow.hard_invariants:judge_hard_invariants", run=lambda ev: judge_hard_invariants(**ev), is_pass=lambda out: out.status == "held", + level=lambda out: Status(out.status), seeds=lambda: [ Seed(dict(GOOD), True), Seed({**GOOD, "outside_scope_changes": 2}, False), @@ -45,6 +48,9 @@ def put(ev: dict[str, Any], value: dict[str, Any]) -> None: Seed({**GOOD, "history_complete": False}, False), ], fields=_fields(), + partial=lambda ev: [ + (flag, {**ev, flag: False}) for flag in GOOD if flag.endswith("_complete") + ], values=tuple(key(name) for name in GOOD), ) ) diff --git a/packages/flow/tests/failopen/sites/receipt_lines.py b/packages/flow/tests/failopen/sites/receipt_lines.py new file mode 100644 index 0000000000..0bfca5e769 --- /dev/null +++ b/packages/flow/tests/failopen/sites/receipt_lines.py @@ -0,0 +1,144 @@ +"""receipt_record's line judge and line tally (C1, C2, C3). + +``_line`` settles a write's reads against the effects it declared: a declared +effect with no read, a read nobody declared, a read below UNCHECKED or a +verdict nobody listed keeps the line from ``confirmed``. ``_tally_lines`` +counts the lines on the kernel, so a check nobody listed is counted as not +checked and keeps the run from VERIFIED. The pre-kernel copies are in +``selftest/_v_receipt_lines_pre.py``; test_receipt_lines_migration.py +compares them. +""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow import receipt_record +from openadapt_flow.verdict import Status +from tests.failopen.harness import CodeCase, Seed, SiteSpec, key, register, root_list + +_CHECK_LEVEL = { + "confirmed": Status.HELD, + "refuted": Status.REFUTED, + "not_checked": Status.NOT_CHECKED, +} + + +def _read(h: str, verdict: str = "confirmed") -> dict[str, Any]: + return { + "effect_contract_hash": h, + "final_verdict": verdict, + "verification_tier": 1, + "observed_effect": "present", + } + + +def _write(*reads: dict[str, Any]) -> dict[str, Any]: + hashes = [r["effect_contract_hash"] for r in reads] + return { + "result": { + "effect_contract_hashes": hashes, + "effect_evidence": list(reads), + "effect_verified": True, + "postconditions_ok": True, + "effect_field_checks": ["f"], + }, + "ledger": { + "effects": [{"contract_hash": h} for h in hashes], + "status": "confirmed", + }, + } + + +def _inflate(_ev: Any, n: int) -> dict[str, Any]: + reads = [_read(f"h{i}") for i in range(n - 1)] + [_read(f"h{n - 1}", "refuted")] + return _write(*reads) + + +def _evidence() -> Any: + return key("effect_evidence", "result") + + +register( + SiteSpec( + id="receipt_record.line", + classes="C1 C3", + target="openadapt_flow.receipt_record:_line", + run=lambda ev: receipt_record._line(0, ev["result"], ev["ledger"]), + is_pass=lambda out: out["check"] == "confirmed", + level=lambda out: _CHECK_LEVEL.get(out["check"], Status.NOT_CHECKED), + precedence=(Status.NOT_CHECKED, Status.REFUTED), + notes={ + "precedence": "a line is refuted only when every declared effect " + "was read; an unread one may have landed, so it outranks a refutation" + }, + seeds=lambda: [ + Seed(_write(_read("h1"), _read("h2")), True, "two writes, both confirmed"), + Seed(_write(_read("h1"), _read("h1")), True, "one contract written twice"), + Seed(_write(_read("h1"), _read("h2", "refuted")), False, "one refuted"), + Seed( + _write(_read("h1"), {**_read("h2"), "verification_tier": None}), + False, + "one read unchecked", + ), + ], + items=_evidence(), + plan=key("effect_contract_hashes", "result"), + bad_item=lambda r: {**r, "final_verdict": "refuted"}, + inflate=_inflate, + values=( + key("final_verdict", "result", "effect_evidence", 0), + key("observed_effect", "result", "effect_evidence", 0), + key("verification_tier", "result", "effect_evidence", 0), + key("effect_verified", "result"), + key("status", "ledger"), + ), + ) +) + + +def _lines(checks: list[str]) -> list[dict[str, Any]]: + return [{"check": c} for c in checks] + + +def _keeps_verified(out: Any) -> bool: + _tally, settled = out + return settled.total == 0 or settled.passes + + +def _codes() -> list[CodeCase]: + return [ + CodeCase( + evidence=_lines(["confirmed", "maybe"]), + may_have_changed=True, + forbidden=lambda out: False, + label="a line check nobody listed", + unknown=True, + ) + ] + + +register( + SiteSpec( + id="receipt_record.lines", + classes="C2 C3", + target="openadapt_flow.receipt_record:_tally_lines", + run=receipt_record._tally_lines, + is_pass=_keeps_verified, + seeds=lambda: [ + Seed(_lines(["confirmed"]), True), + Seed(_lines(["confirmed", "confirmed"]), True), + Seed(_lines(["confirmed", "refuted"]), False), + Seed(_lines(["not_checked"]), False), + ], + items=root_list(), + bad_item=lambda _line: {"check": "refuted"}, + inflate=lambda _ev, n: _lines(["confirmed"] * (n - 1) + ["not_checked"]), + values=(key("check", 0),), + codes=_codes, + vacuous=( + "a run that wrote nothing has no line to check; the receipt keeps the " + "run's own outcome and never upgrades it" + ), + ) +) diff --git a/packages/flow/tests/failopen/sites/verify_run_folds.py b/packages/flow/tests/failopen/sites/verify_run_folds.py index 124af95f9e..6a119530c8 100644 --- a/packages/flow/tests/failopen/sites/verify_run_folds.py +++ b/packages/flow/tests/failopen/sites/verify_run_folds.py @@ -11,10 +11,31 @@ from openadapt_flow import verify_run from openadapt_flow.runtime.effects.effect import Verdict +from openadapt_flow.verdict import Status from tests.failopen.harness import Seed, SiteSpec, key, register, root_list C, R, I = "confirmed", "refuted", "indeterminate" +#: verify_run's labels by level (P6). +#: Both folds rank an unread effect above a refuted one (C7): an effect that +#: wasn't read may have landed, so the run says "check the record", never a +#: plain "refuted". +_UNREAD_FIRST = (Status.NOT_CHECKED, Status.REFUTED) +_PRECEDENCE_NOTE = ( + "an unread effect outranks a refuted one: it may have changed something, " + "so the run is INDETERMINATE (check the record), not REFUTED" +) + +_LEVEL = { + "CONFIRMED": Status.HELD, + "REFUTED": Status.REFUTED, + "INDETERMINATE": Status.NOT_CHECKED, + "present": Status.HELD, + "absent": Status.REFUTED, + "conflicting": Status.REFUTED, + "unknown": Status.NOT_CHECKED, +} + def _verdicts(codes: list[str]) -> list[Any]: return [SimpleNamespace(verdict=Verdict(c)) for c in codes] @@ -28,6 +49,9 @@ def aggregate_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteS kind=kind, run=lambda ev: fn(_verdicts(ev)), is_pass=lambda out: out == "CONFIRMED", + level=lambda out: _LEVEL.get(out, Status.NOT_CHECKED), + precedence=_UNREAD_FIRST, + notes={"precedence": _PRECEDENCE_NOTE}, seeds=lambda: [ Seed([C], True), Seed([C, C, C], True), @@ -53,6 +77,9 @@ def observed_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSp kind=kind, run=lambda ev: fn(_observed(ev)), is_pass=lambda out: out == "present", + level=lambda out: _LEVEL.get(out, Status.NOT_CHECKED), + precedence=_UNREAD_FIRST, + notes={"precedence": _PRECEDENCE_NOTE}, seeds=lambda: [ Seed(["present"], True), Seed(["present", "present"], True), @@ -104,6 +131,61 @@ def readback_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSp ) -register(aggregate_spec(verify_run._aggregate, "verify_run.aggregate")) -register(observed_spec(verify_run._observed, "verify_run.observed")) +def _unplanned(fn: Callable[..., Any]) -> Callable[..., Any]: + """A fold that takes the plan, called the way the S9 copies are: one + planned effect per verdict, so only the empty case is in question.""" + + return lambda verdicts: fn([str(i) for i in range(len(verdicts))], verdicts) + + +def planned_spec( + fn: Callable[..., Any], + id: str, + make: Callable[[list[Any]], list[Any]], + base: Callable[[Callable[..., Any], str], SiteSpec], + last_bad: tuple[Any, Any], +) -> SiteSpec: + """The live fold, with the plan (``cfg.effects``) apart from the + verdicts: dropping a verdict keeps the plan (M1), and a verdict past the + plan answers nothing.""" + + spec = base(_unplanned(fn), id) + seeds = spec.seeds + good, bad = last_bad + + def plan_seeds() -> list[Seed]: + return [ + Seed( + {"plan": [f"{i}:e" for i in range(len(s.evidence))], "got": s.evidence}, + s.correct_pass, + s.note, + ) + for s in seeds() + ] + + spec.run = lambda ev: fn(ev["plan"], make(ev["got"])) + spec.seeds = plan_seeds + spec.items = key("got") + spec.plan = key("plan") + spec.inflate = lambda _ev, n: { + "plan": [f"{i}:e" for i in range(n)], + "got": [good] * (n - 1) + [bad], + } + return spec + + +register( + planned_spec( + verify_run._aggregate, "verify_run.aggregate", _verdicts, aggregate_spec, (C, R) + ) +) +register( + planned_spec( + verify_run._observed, + "verify_run.observed", + _observed, + observed_spec, + ("present", "unknown"), + ) +) register(readback_spec(verify_run.readback_class, "verify_run.readback_class")) diff --git a/packages/flow/tests/failopen/sites/versions_judge.py b/packages/flow/tests/failopen/sites/versions_judge.py index 5e1c96502d..a0889b82b2 100644 --- a/packages/flow/tests/failopen/sites/versions_judge.py +++ b/packages/flow/tests/failopen/sites/versions_judge.py @@ -9,6 +9,7 @@ judge_versions, seal_versions, ) +from openadapt_flow.verdict import Status from tests.failopen.harness import Seed, SiteSpec, key, register KEY = b"k" * 32 @@ -41,6 +42,7 @@ def _raise(ev: dict[str, Any], exc: BaseException) -> dict[str, Any]: target="openadapt_flow.runtime.effects.versions:judge_versions", run=_run, is_pass=lambda out: out.status == "held", + level=lambda out: Status(out.status), seeds=lambda: [ Seed(_good(), True), Seed( diff --git a/packages/flow/tests/failopen/sites/wire_tap_relay.py b/packages/flow/tests/failopen/sites/wire_tap_relay.py index 6ef0b57fd3..966663e7bc 100644 --- a/packages/flow/tests/failopen/sites/wire_tap_relay.py +++ b/packages/flow/tests/failopen/sites/wire_tap_relay.py @@ -3,9 +3,9 @@ The corpus (corpus/urls.json) is read the way a browser reads it (:func:`browser_origin`), not the way ``urlsplit`` does: on main -``///evil.example/x`` is relayed as written, and a browser goes to -``evil.example``. Fixed on #2470; the post-fix copy is in -``selftest/s10_wire_tap_relay.py``. +``///evil.example/x`` was relayed as written, and a browser went to +``evil.example``. #2470 fixed it; the pre- and post-fix copies stay in the +self-test (``selftest/_v_wire_tap_*.py``). """ from __future__ import annotations @@ -51,18 +51,7 @@ def _main() -> None: from openadapt_flow.tx.wire_tap import relay_redirect_location register( - relay_spec( - relay_redirect_location, "wire_tap.relay_redirect_location", "owned" - ), - xfail="#2470: '///host' is relayed raw and a browser reads it as a host", - known=[ - "M11 P3: seed 0: accepted '///evil.example/x' as '///evil.example/x'", - "M11 P3: seed 0: accepted '////evil.example/x' as '////evil.example/x'", - "M11 P3: seed 0: accepted 'http:////evil.example/x' as 'http:////evil.example/x'", - "M11 P3: seed 1: accepted '///evil.example/x' as '///evil.example/x'", - "M11 P3: seed 1: accepted '////evil.example/x' as '////evil.example/x'", - "M11 P3: seed 1: accepted 'http:////evil.example/x' as 'http:////evil.example/x'", - ], + relay_spec(relay_redirect_location, "wire_tap.relay_redirect_location", "site") ) diff --git a/packages/flow/tests/failopen/test_kernel.py b/packages/flow/tests/failopen/test_kernel.py index e8e0b64ae4..d518969137 100644 --- a/packages/flow/tests/failopen/test_kernel.py +++ b/packages/flow/tests/failopen/test_kernel.py @@ -267,6 +267,41 @@ def test_one_result_cannot_satisfy_two_obligations() -> None: assert not settled.passes and set(settled.conflicting) == {unbound, bound} +def test_a_repeated_result_is_judged_like_an_equal_copy() -> None: + """The same object twice, or two equal objects, give one verdict.""" + + (subject,) = _subjects(1) + ob = Obligations.fix([subject], source="p") + once = _result(subject, "held") + same_object = settle(ob, [once, once]) + equal_copy = settle(ob, [once, _result(subject, "held")]) + assert same_object.passes and equal_copy.passes + assert same_object.label(precedence=()) is equal_copy.label(precedence=()) + disagree = settle(ob, [once, _result(subject, "refuted")]) + assert not disagree.passes and disagree.conflicting == (subject,) + + +@pytest.mark.parametrize( + "obs, status", + [ + (Observed(0), Status.HELD), + (Observed(0, complete=False), Status.NOT_CHECKED), + (Observed(3, complete=False), Status.REFUTED), + (Observed(3), Status.REFUTED), + (Observed(None), Status.NOT_CHECKED), + (Observed(True), Status.NOT_CHECKED), + (Observed(-1), Status.NOT_CHECKED), + (Missing("no read"), Status.NOT_CHECKED), + (Errored("TimeoutError", ""), Status.NOT_CHECKED), + ], +) +def test_nothing_else_holds_only_on_a_complete_read( + obs: object, status: Status +) -> None: + (subject,) = _subjects(1) + assert Result.nothing_else(subject, obs).status is status # type: ignore[arg-type] + + def test_benign_cannot_map_a_raise_to_a_value() -> None: def probe() -> object: raise TimeoutError diff --git a/packages/flow/tests/failopen/test_kernel_mutants.py b/packages/flow/tests/failopen/test_kernel_mutants.py index 806f5c211f..97eca77fb5 100644 --- a/packages/flow/tests/failopen/test_kernel_mutants.py +++ b/packages/flow/tests/failopen/test_kernel_mutants.py @@ -33,11 +33,11 @@ " matches[n] = list(same_key)\n", ), "one writer wins": ( - " elif len({r.status for r in got}) > 1 or any(takers[id(r)] > 1 for r in got):\n", - " elif any(takers[id(r)] > 1 for r in got):\n", + " elif len({r.status for r in got}) > 1 or shared:\n", + " elif shared:\n", ), "a shared result counts twice": ( - " elif len({r.status for r in got}) > 1 or any(takers[id(r)] > 1 for r in got):\n", + " elif len({r.status for r in got}) > 1 or shared:\n", " elif len({r.status for r in got}) > 1:\n", ), "truncate at limit": ( @@ -49,6 +49,20 @@ " return Errored(type(exc).__name__, str(exc)[:200])\n", " return Observed(None)\n", ), + "a repeat counts as a second claim": ( + " takers.setdefault(id(r), set()).add(n)\n", + " takers.setdefault(id(r), set()).add(len(takers.get(id(r), ())))\n", + ), + "a partial read holds nothing else": ( + " if obs.complete is not True:\n" + " return cls.not_checked(subject, partial)\n" + " return cls.held(subject, obs, held)\n", + " return _mint_held(subject, held)\n", + ), + "a partial read hides a change": ( + " if count > 0:\n return cls.refuted(subject, obs, refuted)\n", + " if count > 0 and obs.complete:\n return cls.refuted(subject, obs, refuted)\n", + ), "from_code deny-list": ( " if code in refuted:\n return Status.REFUTED\n return Status.NOT_CHECKED\n", " if code in refuted:\n return Status.REFUTED\n return Status.HELD\n", @@ -97,6 +111,13 @@ def fix(*items: object) -> object: settled = v.settle(fix(*many), results, limit=3) assert len(settled.refuted) == 1 and settled.total == 5, "truncated" + once = held(a) + assert v.settle(fix(a), [once, once]).passes, "a repeat is a second claim" + partial = v.Observed(0, complete=False) + assert R.nothing_else(a, partial).status is v.Status.NOT_CHECKED, "partial holds" + changed = R.nothing_else(a, v.Observed(2, complete=False)).status + assert changed is v.Status.REFUTED, "a partial read hides a change" + def boom() -> object: raise TimeoutError diff --git a/packages/flow/tests/failopen/test_positive_control_migration.py b/packages/flow/tests/failopen/test_positive_control_migration.py new file mode 100644 index 0000000000..36499ed84a --- /dev/null +++ b/packages/flow/tests/failopen/test_positive_control_migration.py @@ -0,0 +1,164 @@ +"""The two positive controls moved onto the kernel keep their verdicts. + +``hard_invariants.judge_hard_invariants`` and ``versions.judge_versions`` +now build their verdicts with ``Result`` and ``settle``. A differential +against the copies vendored from main before the move shows the only change +is the one fail-open fix named below. +""" + +from __future__ import annotations + +import itertools +from typing import Any, Optional + +from hypothesis import given, settings +from hypothesis import strategies as st + +from openadapt_flow.hard_invariants import ( + HardInvariantVerdict, + InvariantResult, + judge_hard_invariants, +) +from openadapt_flow.runtime.effects.versions import ( + FrameVersions, + judge_versions, + seal_versions, +) +from tests.failopen.selftest import _v_hard_invariants_pre as hard_before +from tests.failopen.selftest import _v_versions_pre as versions_before + +COUNTS = (None, 0, 1, 2, True) +FLAGS = (True, False) + + +def test_hard_invariants_are_unchanged_on_every_small_input() -> None: + names = ( + "outside_scope_changes", + "undeclared_deletes", + "before_matches", + "after_matches", + "history_matches", + ) + flags = ( + "scope_complete", + "deletes_complete", + "history_complete", + "search_complete", + ) + checked = 0 + for counts in itertools.product(COUNTS, repeat=len(names)): + for bits in itertools.product(FLAGS, repeat=len(flags)): + kwargs: dict[str, Any] = { + **dict(zip(names, counts)), + **dict(zip(flags, bits)), + } + new = judge_hard_invariants(**kwargs) + old = hard_before.judge_hard_invariants(**kwargs) + assert new.evidence() == old.evidence(), kwargs + checked += 1 + assert checked == len(COUNTS) ** 5 * len(FLAGS) ** 4 + + +def test_a_hand_written_held_never_holds() -> None: + """Only a check the judge built carries a kernel result: three hand-made + "held" checks are not checked, where the old fold said held.""" + + checks = tuple( + InvariantResult(name, "held", "ok") + for name in ("declared_scope", "at_most_one", "no_undeclared_deletes") + ) + assert HardInvariantVerdict(checks).status == "not_checked" + assert hard_before.HardInvariantVerdict(checks).status == "held" + refuted = ( + InvariantResult("declared_scope", "refuted", "outside_scope_changes", 1), + ) + assert HardInvariantVerdict(refuted).status == "refuted" + + +KEY = b"k" * 32 +RECORDS = st.sampled_from(["r1", "r2"]) +VERSIONS = st.sampled_from([None, "", "1", "2", "3", "x"]) +AUTHORS = st.sampled_from([None, "me", "them"]) + + +def _rows(draw: Any) -> Any: + return draw( + st.lists( + st.fixed_dictionaries({"rid": RECORDS, "v": VERSIONS, "by": AUTHORS}), + max_size=4, + ) + ) + + +@st.composite +def _case(draw: Any) -> dict[str, Any]: + return { + "authors": draw(st.booleans()), + "before": _rows(draw), + "after": _rows(draw), + "unread_after": draw(st.booleans()) and draw(st.booleans()), + "targets": draw( + st.lists( + st.tuples( + st.sampled_from([None, "r1", "r2", "r3"]), + st.booleans(), + st.booleans(), + ), + max_size=3, + ) + ), + } + + +#: Problems that used to end a target's check before a refutation was +#: looked for. A refutation found after one of them now stands (the fix). +_EXPLAINED_LATER = {"duplicate_version", "no_new_version", "history_changed"} + + +def _spec(authors: bool) -> FrameVersions: + if authors: + return FrameVersions( + read={}, + record_field="rid", + version_field="v", + author_field="by", + self=["me"], + ) + return FrameVersions(read={}, record_field="rid", version_field="v") + + +@settings(derandomize=True, max_examples=2000, deadline=None) +@given(_case()) +def test_versions_change_only_where_a_refutation_was_hidden( + case: dict[str, Any], +) -> None: + spec = _spec(case["authors"]) + stored = seal_versions(spec, case["before"], KEY) + after: Optional[list[dict[str, Any]]] = ( + None if case["unread_after"] else case["after"] + ) + new = judge_versions(spec, stored, after, case["targets"], KEY) + old = versions_before.judge_versions(spec, stored, after, case["targets"], KEY) + # The targets the old check stopped on before looking for a refutation. + stopped_early = [ + t + for t in case["targets"] + if versions_before.judge_versions(spec, stored, after, [t], KEY).problem + in _EXPLAINED_LATER + ] + if new.status == old.status: + assert new.problem == old.problem, case + assert new.targets == old.targets, case + if not stopped_early: + assert (new.new_versions, new.own_versions) == ( + old.new_versions, + old.own_versions, + ), case + return + # The one change: a target the old check stopped on as unexplained, whose + # versions also show another writer, is refuted now. + assert (old.status, new.status) == ("not_checked", "refuted"), case + assert any( + judge_versions(spec, stored, after, [t], KEY).status == "refuted" + for t in stopped_early + ), case diff --git a/packages/flow/tests/failopen/test_receipt_lines_migration.py b/packages/flow/tests/failopen/test_receipt_lines_migration.py new file mode 100644 index 0000000000..64a3cb1bcf --- /dev/null +++ b/packages/flow/tests/failopen/test_receipt_lines_migration.py @@ -0,0 +1,96 @@ +"""receipt_record's line judge and tally on the kernel: a differential +against the copies vendored from main before the move. ``_line`` is +unchanged on every input; the tally changes only for a line check nobody +listed, which now keeps a run from VERIFIED (C3).""" + +from __future__ import annotations + +from typing import Any + +from hypothesis import given, settings +from hypothesis import strategies as st + +from openadapt_flow import receipt_record +from tests.failopen.selftest import _v_receipt_lines_pre as before + +PROFILE = settings(derandomize=True, max_examples=1500, deadline=None) +HASHES = st.sampled_from(["h1", "h2"]) +READ = st.fixed_dictionaries( + { + "effect_contract_hash": HASHES, + "final_verdict": st.sampled_from( + ["confirmed", "refuted", "indeterminate", "x"] + ), + "verification_tier": st.sampled_from([None, 1, 2, 3, "1", True]), + "observed_effect": st.sampled_from(["present", "absent", None]), + } +) + + +@st.composite +def _write(draw: Any) -> tuple[dict[str, Any], Any]: + hashes = draw(st.lists(HASHES, max_size=4)) + result = { + "effect_contract_hashes": hashes, + "effect_evidence": draw(st.lists(READ, max_size=4)), + "effect_verified": draw(st.sampled_from([True, False, None])), + "postconditions_ok": draw(st.sampled_from([True, False, None])), + "effect_field_checks": draw(st.sampled_from([[], ["f"]])), + "actuation": draw(st.sampled_from(["api", "gui"])), + } + ledger = draw( + st.one_of( + st.none(), + st.fixed_dictionaries( + { + "effects": st.one_of( + st.just([{"contract_hash": h} for h in hashes]), + st.lists( + st.fixed_dictionaries({"contract_hash": HASHES}), max_size=3 + ), + ), + "status": st.sampled_from(["confirmed", "refuted", None]), + } + ), + ) + ) + return result, ledger + + +def _outcome(fn: Any, *args: Any) -> Any: + try: + return fn(*args) + except Exception as exc: # noqa: BLE001 - both must raise alike + return type(exc).__name__ + + +@PROFILE +@given(_write()) +def test_line_is_unchanged_on_any_write(case: tuple[dict[str, Any], Any]) -> None: + result, ledger = case + assert _outcome(receipt_record._line, 3, result, ledger) == _outcome( + before._line, 3, result, ledger + ) + + +CHECKS = st.sampled_from(["confirmed", "refuted", "not_checked"]) + + +@PROFILE +@given(st.lists(CHECKS, max_size=6)) +def test_tally_is_unchanged_on_the_three_checks(checks: list[str]) -> None: + lines = [{"check": c} for c in checks] + tally, settled = receipt_record._tally_lines(lines) + assert tally == before.tally(lines) + assert (bool(settled.total) and not settled.passes) == before.unverified(lines) + + +def test_a_check_nobody_listed_keeps_the_run_from_verified() -> None: + lines = [{"check": "confirmed"}, {"check": "maybe"}] + tally, settled = receipt_record._tally_lines(lines) + assert not before.unverified(lines) # the old tally dropped the line + assert not settled.passes and tally == { + "confirmed": 1, + "refuted": 0, + "not_checked": 1, + } diff --git a/packages/flow/tests/failopen/test_sites.py b/packages/flow/tests/failopen/test_sites.py index d8b33314d8..f707b7c8eb 100644 --- a/packages/flow/tests/failopen/test_sites.py +++ b/packages/flow/tests/failopen/test_sites.py @@ -34,3 +34,11 @@ def test_owned_sites_name_their_owner_and_failures() -> None: assert spec.xfail and "#" in spec.xfail and spec.known, spec.id else: assert not spec.known, spec.id + + +def test_a_site_that_ranks_unread_first_says_why() -> None: + from openadapt_flow.verdict import Status + + for spec in load_all().values(): + if spec.precedence != (Status.REFUTED, Status.NOT_CHECKED): + assert spec.notes.get("precedence"), spec.id diff --git a/packages/flow/tests/failopen/test_verify_run_migration.py b/packages/flow/tests/failopen/test_verify_run_migration.py index 64bac22460..de2e6cc4f2 100644 --- a/packages/flow/tests/failopen/test_verify_run_migration.py +++ b/packages/flow/tests/failopen/test_verify_run_migration.py @@ -12,6 +12,11 @@ from openadapt_flow.runtime.effects.effect import Verdict from tests.failopen.selftest import _v_s9_verify_run_pre as before + +def _plan(items: list[object]) -> list[str]: + return [str(i) for i in range(len(items))] + + PROFILE = settings(derandomize=True, max_examples=300, deadline=None) # The three members the vendored fold knew; a member added later is not # compared, since the old fold would have called it CONFIRMED. @@ -23,14 +28,14 @@ @given(st.lists(VERDICTS, min_size=1, max_size=12)) def test_aggregate_is_unchanged_on_any_effects(verdicts: list[Verdict]) -> None: items = [SimpleNamespace(verdict=v) for v in verdicts] - assert verify_run._aggregate(items) == before._aggregate(items) + assert verify_run._aggregate(_plan(items), items) == before._aggregate(items) @PROFILE @given(st.lists(OBSERVED, min_size=1, max_size=12)) def test_observed_is_unchanged_on_any_effects(seen: list[str]) -> None: items = [SimpleNamespace(observed_effect=s) for s in seen] - assert verify_run._observed(items) == before._observed(items) + assert verify_run._observed(_plan(items), items) == before._observed(items) class _Tier: @@ -60,13 +65,39 @@ def test_readback_class_is_unchanged_when_tiers_pair_with_effects( def test_only_the_empty_and_unpaired_cases_change() -> None: - assert (before._aggregate([]), verify_run._aggregate([])) == ( + assert (before._aggregate([]), verify_run._aggregate([], [])) == ( "CONFIRMED", "INDETERMINATE", ) - assert (before._observed([]), verify_run._observed([])) == ("present", "unknown") + assert (before._observed([]), verify_run._observed([], [])) == ( + "present", + "unknown", + ) assert before.readback_class([], []) == "independent_readback" assert verify_run.readback_class([], []) == "unchecked" one = [SimpleNamespace(unavailable=False, stale=False)] * 2 assert before.readback_class(one, [_Tier(True)]) == "independent_readback" assert verify_run.readback_class(one, [_Tier(True)]) == "unchecked" + + +def test_a_planned_effect_with_no_verdict_never_passes() -> None: + """The fail-open fix: the folds settle against the plan, so a verdict + that went missing, or one nobody planned, is not a pass.""" + + one = [SimpleNamespace(verdict=Verdict.CONFIRMED, observed_effect="present")] + assert verify_run._aggregate(["0", "1"], one) == "INDETERMINATE" + assert verify_run._observed(["0", "1"], one) == "unknown" + assert verify_run._aggregate([], one) == "INDETERMINATE" + assert verify_run._observed([], one) == "unknown" + assert verify_run._aggregate(["0"], one) == "CONFIRMED" + + +def test_an_unlisted_observed_code_is_unknown() -> None: + """The old fold read a code nobody listed as present (C3).""" + + odd = [ + SimpleNamespace(observed_effect="present"), + SimpleNamespace(observed_effect="maybe"), + ] + assert before._observed(odd) == "present" + assert verify_run._observed(_plan(odd), odd) == "unknown" diff --git a/packages/flow/tests/test_tx_wire_tap.py b/packages/flow/tests/test_tx_wire_tap.py index 65ef3f5c32..978709f4ed 100644 --- a/packages/flow/tests/test_tx_wire_tap.py +++ b/packages/flow/tests/test_tx_wire_tap.py @@ -1277,9 +1277,14 @@ def permitted_from_import(node): exact_redaction = node.module == "openadapt_flow.secret_redaction" and { name.name for name in node.names } <= {"MASK", "credential_header", "mask_header"} + # The verdict-site marker is stdlib only and does nothing at run time. + exact_site = node.module == "openadapt_flow.verdict_sites" and [ + name.name for name in node.names + ] == ["verdict_site"] return ( exact_crypto or exact_redaction + or exact_site or node.module.split(".")[0] in stdlib_names or node.module in allowed_non_stdlib ) diff --git a/packages/flow/tests/test_verdict_folds_check.py b/packages/flow/tests/test_verdict_folds_check.py index add50fc003..d9d131d515 100644 --- a/packages/flow/tests/test_verdict_folds_check.py +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -19,6 +19,9 @@ "swallow": "def f(g):\n try:\n return g()\n except Exception:\n return 0\n", "slice_count": "def f(lines):\n n = sum(1 for x in lines[:256] if x)\n return n\n", "else_success": 'def f(x):\n if x:\n y = "REFUTED"\n else:\n y = "CONFIRMED"\n return y\n', + "swallow_wide": "def f(g, log):\n try:\n g()\n except Exception:\n log.error('failed')\n return True\n", + "says_unchanged": 'def f():\n return "no_change"\n', + "empty_change_set": "def f(changes):\n return not changes\n", } @@ -51,6 +54,71 @@ def test_each_exit_of_a_handler_is_judged(tmp_path: Path) -> None: assert "swallow" not in _count(tmp_path, reraise) +@pytest.mark.parametrize( + "handler", + [ + "except Exception:\n log.error('failed')", + "except Exception as exc:\n log.exception(exc)\n x = 1", + "except (ValueError, Exception):\n return 0", + "except builtins.Exception:\n return 0", + "except BaseException:\n if x:\n raise\n log.error('x')", + "except Exception:\n for _ in x:\n break", + ], +) +def test_every_open_way_out_of_a_broad_handler_is_counted( + tmp_path: Path, handler: str +) -> None: + src = f"def f(g, log, x):\n try:\n g()\n {handler}\n return True\n" + got = _count(tmp_path, src) + assert got.get("swallow", 0) + got.get("swallow_wide", 0) == 1, got + + +@pytest.mark.parametrize( + "handler", + [ + "except Exception:\n log.error('failed')\n raise", + "except Exception:\n status = 'not_checked'", + "except Exception as exc:\n out.append(Errored(type(exc).__name__, ''))", + "except Exception:\n if x:\n raise\n else:\n return NOT_CHECKED", + "except ValueError:\n log.error('narrow')", + ], +) +def test_a_closed_handler_is_not_counted(tmp_path: Path, handler: str) -> None: + src = f"def f(g, log, x, out):\n try:\n g()\n {handler}\n return True\n" + got = _count(tmp_path, src) + assert "swallow" not in got and "swallow_wide" not in got, got + + +@pytest.mark.parametrize( + "expr", + [ + "not changes", + "len(collateral) == 0", + "deleted == []", + "not any(c for c in diffs)", + "frame.changes == set()", + ], +) +def test_a_nothing_changed_test_is_counted(tmp_path: Path, expr: str) -> None: + src = f"def f(changes, collateral, deleted, diffs, frame):\n return {expr}\n" + assert _count(tmp_path, src).get("empty_change_set") == 1 + + +def test_a_file_that_does_not_parse_fails_the_check(tmp_path: Path) -> None: + path = tmp_path / "m.py" + path.write_text("def f(:\n") + with pytest.raises(SyntaxError): + folds.count_file(path, CONFIG) + + +def test_a_spec_id_is_an_id_argument_not_any_quoted_word() -> None: + src = ( + "register(SiteSpec(id='a.judge', classes='C1', is_pass=lambda o: o == 'held'))\n" + "register(make_spec(fn, 'b.judge', 'owned'), xfail='#1', known=['M1 P2: x'])\n" + ) + assert folds.spec_ids(src) == {"a.judge", "b.judge"} + + def test_a_site_id_on_two_functions_is_refused(tmp_path: Path) -> None: path = tmp_path / "m.py" path.write_text( From f34a1ec934e9167c8e03dc4732cf0bf34f9701b0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:31:42 -0500 Subject: [PATCH 05/14] fix(flow): close the log-call hole in the swallow check; state the provenance boundary A handler that only logs a not-checked word still swallows; only a call that stores the value records it. M15 must not raise a refuted seed. Observed and Result.held say the adapter establishes which run produced a read. --- packages/flow/docs/FAIL_CLOSED.md | 8 ++++++-- .../flow/openadapt_flow/runtime/effects/versions.py | 7 ++++--- packages/flow/openadapt_flow/verdict.py | 10 ++++++++-- packages/flow/scripts/check_verdict_folds.py | 7 +++++++ packages/flow/tests/failopen/mutators.py | 3 ++- packages/flow/tests/test_verdict_folds_check.py | 2 ++ 6 files changed, 29 insertions(+), 8 deletions(-) diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index e60956b63b..64a2213960 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -46,7 +46,11 @@ found didn't stop the next one, so the shapes are now fixed in one place: nonce, digest). A result whose binding disagrees with the obligation is mismatched, so a result from another run or from a decoy table doesn't count. One result can't settle two obligations: if two claim it, both - are conflicting. + are conflicting. The kernel checks the binding a result carries, not + where its value came from: the adapter that reads the store must + establish that the observation belongs to this run before it builds the + result. An earlier run's read tagged with this run's subject looks like a + fresh one. 6. **Say who signed only from a verified source.** `trust_label(source, verified=...)` names the signer only for a verified `TrustSource`; anything else is "not verified". @@ -256,7 +260,7 @@ Done: `Result.nothing_else`; a hand-written "held" no longer holds. Unchanged on every small input. - [x] `runtime/effects/versions.judge_versions` (C1 C5): one obligation for - the reads and one per target. Fix: a duplicate, missing-history or + reads succeeding and one per target. Fix: a duplicate, missing-history or no-new-version row no longer hides a version by someone else (refuted, not "not checked"). - [x] `verify_run._aggregate` and `_observed` (C1 C2): settled against the diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py index a957b9c87c..86ade2f524 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -264,9 +264,10 @@ def judge_versions( mine = resolved before: Mapping[str, Any] = stored.get("records") or {} out = VersionVerdict("held") - # The obligations come from the plan: the reads themselves, then one per - # target. With no target (all creates) the reads still have to hold, so - # the set is never empty. + # The obligations come from the plan: that the reads succeeded (the + # early return above refused an unreadable one), then one per target. + # With no target (all creates) that one still has to hold, so the set is + # never empty. read = Subject(surface="versions", key="reads") subjects = [read] results = [ diff --git a/packages/flow/openadapt_flow/verdict.py b/packages/flow/openadapt_flow/verdict.py index 9c744aa038..1d398de88b 100644 --- a/packages/flow/openadapt_flow/verdict.py +++ b/packages/flow/openadapt_flow/verdict.py @@ -72,7 +72,11 @@ class Status(str, Enum): @dataclass(frozen=True) class Observed: """A value that was read. ``complete=False`` when the read was partial - (a short page, a capped query): it can refute, never hold.""" + (a short page, a capped query): it can refute, never hold. + + It carries no provenance. The adapter that makes it must establish that + the read belongs to this run (bound to its run id, nonce or digest); + the kernel checks a result's binding, not where its value came from.""" value: object complete: bool = True @@ -238,7 +242,9 @@ def __post_init__(self) -> None: @classmethod def held(cls, subject: Subject, obs: Observation, reason: str = "") -> "Result": - """HELD, from a complete observed value only.""" + """HELD, from a complete observed value only. The caller vouches that + ``obs`` was read for ``subject``'s run: the kernel can't tell a stale + observation tagged with the current subject from a fresh one.""" if not isinstance(obs, Observed) or obs.complete is not True: raise TypeError("HELD needs a complete Observed value") diff --git a/packages/flow/scripts/check_verdict_folds.py b/packages/flow/scripts/check_verdict_folds.py index 84003f05a3..68e58ea828 100644 --- a/packages/flow/scripts/check_verdict_folds.py +++ b/packages/flow/scripts/check_verdict_folds.py @@ -241,8 +241,12 @@ def _records_not_checked(body: list[ast.stmt]) -> bool: node.value is not None and _not_checked_value(node.value) ): return True + # Only a call that stores the value counts: ``out.append(Errored(...))``. + # A log line that mentions "unknown" hands nothing on. if ( isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in _RECORDING and node.args and any(_not_checked_value(a) for a in node.args) ): @@ -250,6 +254,9 @@ def _records_not_checked(body: list[ast.stmt]) -> bool: return False +_RECORDING = frozenset({"append", "add", "extend", "put", "setdefault", "insert"}) + + _COUNTING = frozenset({"sum", "len", "Counter", "tally", "count"}) diff --git a/packages/flow/tests/failopen/mutators.py b/packages/flow/tests/failopen/mutators.py index 4ccd7fa505..d28fac6974 100644 --- a/packages/flow/tests/failopen/mutators.py +++ b/packages/flow/tests/failopen/mutators.py @@ -197,7 +197,8 @@ def mutations(spec: SiteSpec, seed: Seed) -> Iterator[Mutation]: ) if spec.partial is not None: for label, partial in spec.partial(ev): - yield Mutation("M15", f"{label} partial", partial, "not_pass") + # A partial read can still refute, so a refuted seed stays refuted. + yield Mutation("M15", f"{label} partial", partial, "not_pass", adverse=True) if spec.knob is not None and seed.correct_pass: yield Mutation( "M9", f"knob {spec.knob.name}", check=_knob_check(spec, ev), prop="P5" diff --git a/packages/flow/tests/test_verdict_folds_check.py b/packages/flow/tests/test_verdict_folds_check.py index d9d131d515..9b1fc6f5a7 100644 --- a/packages/flow/tests/test_verdict_folds_check.py +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -63,6 +63,8 @@ def test_each_exit_of_a_handler_is_judged(tmp_path: Path) -> None: "except builtins.Exception:\n return 0", "except BaseException:\n if x:\n raise\n log.error('x')", "except Exception:\n for _ in x:\n break", + "except Exception:\n log.error('unknown')", + "except Exception:\n log.warning(NOT_CHECKED)", ], ) def test_every_open_way_out_of_a_broad_handler_is_counted( From c151226dd10ae580b90989bf29e92136741ad281 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:36:39 -0500 Subject: [PATCH 06/14] fix(flow): close the four ratchet and observed gaps Gemini found The empty-change test is read from either side, a [0:N] slice counts like [:N], builtins.all/any count as folds, and an unplanned verdict beside a refuted one makes _observed unknown. --- packages/flow/openadapt_flow/verify_run.py | 6 ++- packages/flow/scripts/check_verdict_folds.py | 40 ++++++++++++++----- .../failopen/test_verify_run_migration.py | 8 ++++ .../flow/tests/test_verdict_folds_check.py | 19 +++++++++ 4 files changed, 61 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 7d3abee240..4463eb2498 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -3027,7 +3027,11 @@ def _observed(planned: Sequence[str], verdicts: Sequence[EffectVerdict]) -> str: settled = settle(obligations, results) if settled.passes: return "present" - if not settled.refuted or settled.total != len(settled.held) + len(settled.refuted): + if ( + not settled.refuted + or settled.unexpected + or settled.total != len(settled.held) + len(settled.refuted) + ): return "unknown" # something planned was not read, or not planned seen = {v.observed_effect for v in verdicts} if "conflicting" in seen or seen == {"absent", "present"}: diff --git a/packages/flow/scripts/check_verdict_folds.py b/packages/flow/scripts/check_verdict_folds.py index 68e58ea828..354ca8caf4 100644 --- a/packages/flow/scripts/check_verdict_folds.py +++ b/packages/flow/scripts/check_verdict_folds.py @@ -310,8 +310,15 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: counts["says_unchanged"] += 1 elif ( isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id in ("all", "any") + and ( + (isinstance(node.func, ast.Name) and node.func.id in ("all", "any")) + or ( + # ``builtins.all(...)`` + isinstance(node.func, ast.Attribute) + and node.func.attr in ("all", "any") + and getattr(node.func.value, "id", "") == "builtins" + ) + ) and node.args and any(fold_names.search(n) for n in _names(node.args[0])) ): @@ -366,7 +373,12 @@ def count_file(path: Path, config: dict[str, Any]) -> Counter[str]: sliced = any( isinstance(n, ast.Subscript) and isinstance(n.slice, ast.Slice) - and n.slice.lower is None + and ( + n.slice.lower is None + or ( + isinstance(n.slice.lower, ast.Constant) and n.slice.lower.value == 0 + ) + ) and n.slice.upper is not None for n in ast.walk(stmt) ) @@ -409,16 +421,22 @@ def about_changes(expr: ast.AST) -> bool: and isinstance(node.ops[0], (ast.Eq, ast.Is)) ): left, right = node.left, node.comparators[0] - empty = ( - (isinstance(right, ast.Constant) and right.value == 0) - or (isinstance(right, (ast.List, ast.Tuple, ast.Set)) and not right.elts) - or ( - isinstance(right, ast.Call) - and getattr(right.func, "id", "") in ("set", "list", "tuple", "dict") - and not right.args + + def empty(expr: ast.AST) -> bool: + return ( + (isinstance(expr, ast.Constant) and expr.value == 0) + or (isinstance(expr, (ast.List, ast.Tuple, ast.Set)) and not expr.elts) + or ( + isinstance(expr, ast.Call) + and getattr(expr.func, "id", "") in ("set", "list", "tuple", "dict") + and not expr.args + ) ) + + # Either side: ``0 == len(changes)`` is the same test. + return (empty(right) and about_changes(left)) or ( + empty(left) and about_changes(right) ) - return empty and about_changes(left) return False diff --git a/packages/flow/tests/failopen/test_verify_run_migration.py b/packages/flow/tests/failopen/test_verify_run_migration.py index de2e6cc4f2..0776318921 100644 --- a/packages/flow/tests/failopen/test_verify_run_migration.py +++ b/packages/flow/tests/failopen/test_verify_run_migration.py @@ -101,3 +101,11 @@ def test_an_unlisted_observed_code_is_unknown() -> None: ] assert before._observed(odd) == "present" assert verify_run._observed(_plan(odd), odd) == "unknown" + + +def test_an_unplanned_verdict_beside_a_refuted_one_is_unknown() -> None: + got = [ + SimpleNamespace(observed_effect="absent"), + SimpleNamespace(observed_effect="present"), + ] + assert verify_run._observed(["0"], got) == "unknown" diff --git a/packages/flow/tests/test_verdict_folds_check.py b/packages/flow/tests/test_verdict_folds_check.py index 9b1fc6f5a7..78238ccd50 100644 --- a/packages/flow/tests/test_verdict_folds_check.py +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -99,6 +99,8 @@ def test_a_closed_handler_is_not_counted(tmp_path: Path, handler: str) -> None: "deleted == []", "not any(c for c in diffs)", "frame.changes == set()", + "0 == len(changes)", + "[] == deleted", ], ) def test_a_nothing_changed_test_is_counted(tmp_path: Path, expr: str) -> None: @@ -106,6 +108,23 @@ def test_a_nothing_changed_test_is_counted(tmp_path: Path, expr: str) -> None: assert _count(tmp_path, src).get("empty_change_set") == 1 +@pytest.mark.parametrize( + "src, kind", + [ + ( + "def f(lines):\n return sum(1 for x in lines[0:256] if x)\n", + "slice_count", + ), + ( + "import builtins\ndef f(results):\n return builtins.all(r.ok for r in results)\n", + "bool_fold", + ), + ], +) +def test_a_spelled_out_form_is_counted(tmp_path: Path, src: str, kind: str) -> None: + assert _count(tmp_path, src).get(kind) == 1 + + def test_a_file_that_does_not_parse_fails_the_check(tmp_path: Path) -> None: path = tmp_path / "m.py" path.write_text("def f(:\n") From 7a5f6e458607c6d0b35e8abedc79b8794b8fcc71 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:45:44 -0500 Subject: [PATCH 07/14] docs(flow): record how the fold baseline was measured and why unread-first stays --- packages/flow/docs/FAIL_CLOSED.md | 30 +++++++++++++++---- .../tests/failopen/sites/receipt_lines.py | 3 +- .../tests/failopen/sites/verify_run_folds.py | 6 ++-- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 64a2213960..236df580f5 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -129,8 +129,12 @@ M10) may move REFUTED to NOT_CHECKED, because the refutation it removed is no longer known, but never to HELD. A site whose order puts an unread result below a refuted one says so in `precedence` with the reason in `notes["precedence"]` (a test enforces the note). `verify_run`'s folds and -`receipt_record._line` do: an effect that wasn't read may have landed, so the -run says "check the record" rather than "refuted" (C7). +`receipt_record._line` do, and keep doing so by decision: when an effect may +have landed unseen, reconciliation beats an assumed refutation. A run with +one refuted effect and one unread effect is INDETERMINATE ("check the +record"), because the unread write may have happened; reporting it as +REFUTED would invite a retry or a plain failure over a change that may be in +the store (C7). M13, a trust-source swap, waits for the signer vectors (follow-up 5). @@ -210,9 +214,25 @@ argument, or a string passed to the spec factory given to `register(...)`; any other quoted word in a spec file doesn't count. The baseline was measured again on this branch after merging main at -`9b6956be3`, because main had gained folds after the first measurement. For -every kind the branch's count is at or below a clean `origin/main` measured -with the same detector, so no kind's allowance rose above main's. +`9b6956be3`, because main had gained folds after the first measurement. The +method: `git archive origin/main` of `packages/flow/openadapt_flow`, +`openadapt`, `scripts/ci` and the outcome vocabulary into an empty folder; +`scan(load_config(), root=)` there and on this branch with the +same detector and config; a per-kind comparison of the two totals; then the +branch's per-file counts written as the baseline. For every kind the branch's +count is at or below clean main's, so no kind's allowance rose above main's: + +| Kind | Clean main | This branch | +|---|---|---| +| says_success | 92 | 89 | +| cmp_literal | 732 | 724 | +| bool_fold | 209 | 201 | +| swallow | 805 | 805 | +| swallow_wide | 377 | 377 | +| slice_count | 40 | 40 | +| else_success | 3 | 3 | +| says_unchanged | 32 | 30 | +| empty_change_set | 40 | 40 | To add verdict code, put it in a `@verdict_site` with a spec; the ratchet doesn't count inside one. diff --git a/packages/flow/tests/failopen/sites/receipt_lines.py b/packages/flow/tests/failopen/sites/receipt_lines.py index 0bfca5e769..a51245ded8 100644 --- a/packages/flow/tests/failopen/sites/receipt_lines.py +++ b/packages/flow/tests/failopen/sites/receipt_lines.py @@ -70,7 +70,8 @@ def _evidence() -> Any: precedence=(Status.NOT_CHECKED, Status.REFUTED), notes={ "precedence": "a line is refuted only when every declared effect " - "was read; an unread one may have landed, so it outranks a refutation" + "was read: when an effect may have landed unseen, reconciliation " + "beats an assumed refutation (C7; FAIL_CLOSED.md P6)" }, seeds=lambda: [ Seed(_write(_read("h1"), _read("h2")), True, "two writes, both confirmed"), diff --git a/packages/flow/tests/failopen/sites/verify_run_folds.py b/packages/flow/tests/failopen/sites/verify_run_folds.py index 6a119530c8..06cbb90b9f 100644 --- a/packages/flow/tests/failopen/sites/verify_run_folds.py +++ b/packages/flow/tests/failopen/sites/verify_run_folds.py @@ -22,8 +22,10 @@ #: plain "refuted". _UNREAD_FIRST = (Status.NOT_CHECKED, Status.REFUTED) _PRECEDENCE_NOTE = ( - "an unread effect outranks a refuted one: it may have changed something, " - "so the run is INDETERMINATE (check the record), not REFUTED" + "an unread effect outranks a refuted one: when an effect may have landed " + "unseen, reconciliation beats an assumed refutation, so the run is " + "INDETERMINATE (check the record), not REFUTED, which would invite a " + "retry over a write that may be in the store (C7; FAIL_CLOSED.md P6)" ) _LEVEL = { From 1e1f79c9ddfea182f6d23e54cadedfd442e3cefe Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:54:49 -0500 Subject: [PATCH 08/14] feat(flow): links, tabs and menu items as steps; the commit point is the step the demo saw writing Adds openadapt_flow.gui, a neutral view of a screen (controls by role, name, state and containers) with adapters for a browser page (links included), an accessibility tree and a form_tx snapshot. gui.steps learns each clicked step's role from what the backend counted in the demonstration (commit, navigate, in place, unknown), never from its words, and judges a live step against it. judge_step is a registered verdict site. --- packages/flow/openadapt_flow/gui/__init__.py | 22 + packages/flow/openadapt_flow/gui/adapters.py | 222 ++++++++++ packages/flow/openadapt_flow/gui/dom.py | 304 ++++++++++++++ packages/flow/openadapt_flow/gui/model.py | 378 ++++++++++++++++++ packages/flow/openadapt_flow/gui/steps.py | 310 ++++++++++++++ .../flow/tests/failopen/sites/gui_steps.py | 124 ++++++ packages/flow/tests/gui/__init__.py | 0 packages/flow/tests/gui/_apps.py | 219 ++++++++++ packages/flow/tests/gui/_grid.py | 143 +++++++ packages/flow/tests/gui/conftest.py | 27 ++ packages/flow/tests/gui/test_gui_steps.py | 323 +++++++++++++++ 11 files changed, 2072 insertions(+) create mode 100644 packages/flow/openadapt_flow/gui/__init__.py create mode 100644 packages/flow/openadapt_flow/gui/adapters.py create mode 100644 packages/flow/openadapt_flow/gui/dom.py create mode 100644 packages/flow/openadapt_flow/gui/model.py create mode 100644 packages/flow/openadapt_flow/gui/steps.py create mode 100644 packages/flow/tests/failopen/sites/gui_steps.py create mode 100644 packages/flow/tests/gui/__init__.py create mode 100644 packages/flow/tests/gui/_apps.py create mode 100644 packages/flow/tests/gui/_grid.py create mode 100644 packages/flow/tests/gui/conftest.py create mode 100644 packages/flow/tests/gui/test_gui_steps.py diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py new file mode 100644 index 0000000000..bbcddd672a --- /dev/null +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -0,0 +1,22 @@ +"""General GUI mechanisms over one neutral view of a screen. + +Programs that fill forms keep meeting the same few interface shapes in every +kind of app: a portal, an EMR chart, a spreadsheet grid, a SaaS settings page. +This package handles each shape once, over :mod:`openadapt_flow.gui.model` +(controls with a role, a name, a state and the containers they sit in), so no +mechanism depends on a browser or names an application: + +- :mod:`openadapt_flow.gui.steps`: a link, a tab or a button can be a step, + and the step that commits is the one the demonstration showed writing. + +Per-app facts (which control, which words, how many writes) are pack data, +learned from a demonstration or declared by the pack author. The engine holds +no word lists of its own. + +Adapters turn a backend's view into a :class:`~openadapt_flow.gui.model.Screen`: +:mod:`openadapt_flow.gui.dom` for a browser page, +:mod:`openadapt_flow.gui.adapters` for an accessibility tree (desktop, +spreadsheet) or a ``form_tx`` snapshot. + +Stdlib only, apart from the browser adapter. +""" diff --git a/packages/flow/openadapt_flow/gui/adapters.py b/packages/flow/openadapt_flow/gui/adapters.py new file mode 100644 index 0000000000..bfa4380fa5 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/adapters.py @@ -0,0 +1,222 @@ +"""Turn other backends' views into a :class:`~openadapt_flow.gui.model.Screen`. + +- :func:`screen_from_tree`: an accessibility tree (UI Automation, AX, AT-SPI, + or a spreadsheet's cell grid exported as one). Each node is a mapping with + ``role``, ``name`` and optional ``handle``, ``value``, ``checked``, + ``disabled``, ``readonly``, ``target``, ``text`` and ``children``. Nodes + whose role is a container role (:data:`CONTAINER_ROLES`) become containers + of the controls under them; a ``dialog`` node also becomes a + :class:`~openadapt_flow.gui.model.Dialog`. +- :func:`screen_from_form_snapshot`: a ``form_tx`` ``FormSnapshot``, read by + attribute so this module does not import ``form_tx``. That snapshot keeps + section and row text, not container handles, so the containers it gives are + named by their text and carry no structure beyond it. + +Role names are mapped through :data:`TREE_ROLES`; an unknown role is +``other`` and never acts as a control a mechanism can use. +""" + +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from openadapt_flow.gui.model import ROLES, Container, Control, Dialog, Screen + +__all__ = [ + "CONTAINER_ROLES", + "TREE_ROLES", + "screen_from_form_snapshot", + "screen_from_tree", +] + +#: Accessibility role names from common trees, mapped to :data:`ROLES`. +TREE_ROLES: Mapping[str, str] = { + "edit": "textbox", + "text field": "textbox", + "textfield": "textbox", + "entry": "textbox", + "searchbox": "textbox", + "spinbutton": "textbox", + "check box": "checkbox", + "check_box": "checkbox", + "toggle button": "switch", + "radio button": "radio", + "radiobutton": "radio", + "combo box": "combobox", + "popupbutton": "combobox", + "list": "listbox", + "push button": "button", + "hyperlink": "link", + "tab item": "tab", + "tabitem": "tab", + "page tab": "tab", + "menu item": "menuitem", + "dataitem": "cell", + "data item": "cell", + "gridcell": "cell", + "table cell": "cell", + "static text": "text", + "statictext": "text", + "label": "text", +} + +#: Tree roles that hold controls rather than being one, and their kind. +CONTAINER_ROLES: Mapping[str, str] = { + "group": "group", + "grouping": "group", + "pane": "region", + "region": "region", + "section": "region", + "form": "form", + "dialog": "dialog", + "window": "region", + "row": "row", + "dataitem row": "row", + "list item": "item", + "listitem": "item", + "table": "region", + "grid": "region", + "sheet": "region", +} + + +def _role(raw: object) -> str: + key = " ".join(str(raw or "").split()).casefold() + if key in ROLES: + return key + return TREE_ROLES.get(key, "other") + + +def screen_from_tree( + root: Mapping[str, Any], + *, + location: str = "", + title: str = "", + complete: bool = True, +) -> Screen: + """Flatten ``root`` into a :class:`Screen`. A node without ``handle`` gets + its index path (``0/2/1``), which is stable only while the tree is.""" + + controls: list[Control] = [] + dialogs: list[Dialog] = [] + texts: list[str] = [] + + def walk( + node: Mapping[str, Any], + path: str, + boxes: tuple[Container, ...], + dialog: str, + ) -> None: + handle = str(node.get("handle") or path) + raw_role = " ".join(str(node.get("role") or "").split()).casefold() + name = str(node.get("name") or "") + kind = CONTAINER_ROLES.get(raw_role) + if node.get("text"): + texts.append(str(node["text"])) + if kind is not None: + box = Container(handle, kind, name, str(node.get("text") or name)) + boxes = boxes + (box,) + if kind == "dialog" and raw_role == "dialog": + dialogs.append(Dialog(handle, name, str(node.get("text") or ""))) + dialog = handle + else: + role = _role(raw_role) + if role != "other": + checked = node.get("checked") + controls.append( + Control( + handle=handle, + role=role, + name=name, + value=str(node.get("value") or ""), + checked=None if checked is None else bool(checked), + disabled=bool(node.get("disabled")), + readonly=bool(node.get("readonly")), + required=bool(node.get("required")), + containers=boxes, + dialog=dialog, + target=str(node.get("target") or ""), + error=str(node.get("error") or ""), + ) + ) + for i, child in enumerate(node.get("children") or ()): + walk(child, f"{path}/{i}", boxes, dialog) + + walk(root, "0", (), "") + return Screen( + controls=tuple(controls), + dialogs=tuple(dialogs), + location=location, + title=title or str(root.get("name") or ""), + text="\n".join(texts), + complete=complete, + ) + + +def _snapshot_role(ctrl: Any) -> str: + role = _role(getattr(ctrl, "role", "")) + if role != "other": + return role + tag = str(getattr(ctrl, "tag", "")).casefold() + kind = str(getattr(ctrl, "input_type", "")).casefold() + if tag == "a": + return "link" + if tag == "button" or kind in ("submit", "button", "reset", "image"): + return "button" + if tag == "select": + return "combobox" + if kind in ("checkbox", "radio"): + return kind + if tag in ("input", "textarea"): + return "textbox" + return "other" + + +def screen_from_form_snapshot(snapshot: Any) -> Screen: + """A ``form_tx`` snapshot as a :class:`Screen`. Containers are the + control's section text and row text, named by that text.""" + + controls = [] + for ctrl in getattr(snapshot, "controls", ()) or (): + if not getattr(ctrl, "visible", True) or getattr(ctrl, "is_secret", False): + continue + boxes: list[Container] = [] + section = str(getattr(ctrl, "section_text", "") or "") + if section: + boxes.append(Container(f"section:{section}", "region", section, section)) + row = str(getattr(ctrl, "row_text", "") or "") + if row: + boxes.append(Container(f"row:{row}", "row", "", row)) + modal = str(getattr(ctrl, "modal_container", "") or "") + checked: Optional[bool] = getattr(ctrl, "checked", None) + controls.append( + Control( + handle=str(getattr(ctrl, "dom_selector")), + role=_snapshot_role(ctrl), + name=str(getattr(ctrl, "label_text", "") or ""), + value=str(getattr(ctrl, "current_value", "") or ""), + checked=checked, + disabled=bool(getattr(ctrl, "disabled", False)), + readonly=bool(getattr(ctrl, "readonly", False)), + required=bool(getattr(ctrl, "required", False)), + containers=tuple(boxes), + dialog=modal, + error=str(getattr(ctrl, "error_text", "") or ""), + ) + ) + dialogs = tuple( + Dialog( + str(getattr(m, "container_selector", "")), + str(getattr(m, "modal_id", "")), + str(getattr(m, "message_text", "") or ""), + ) + for m in getattr(snapshot, "active_modals", ()) or () + ) + return Screen( + controls=tuple(controls), + dialogs=dialogs, + location=str(getattr(snapshot, "url_origin_and_path", "") or ""), + title=str(getattr(snapshot, "title", "") or ""), + text=str(getattr(snapshot, "page_text", "") or ""), + errors=tuple(getattr(snapshot, "banner_errors", ()) or ()), + ) diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py new file mode 100644 index 0000000000..37310161c4 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -0,0 +1,304 @@ +"""Read a browser page as a :class:`~openadapt_flow.gui.model.Screen`, and act on it. + +:data:`OBSERVE_JS` walks the page once and returns every visible control a +person can act on, links included (``a[href]`` and ``role="link"``), with its +role, accessible name, value, checked state, the containers it sits in and +the dialog that holds it. Roles come from the element's ARIA role, else from +its tag and type, never from its text. + +:class:`PageActuator` drives a Playwright ``Page`` (sync API) and counts +writes: every request whose method is not GET, HEAD or OPTIONS, plus GET +requests whose path matches a pattern the pack declares (an app whose commit +is a plain link). Nothing else counts, so a page that saves by some other +route shows no write, and no write means no commit. + +Handles are CSS paths (``#id`` when the id is unique, else ``nth-of-type`` +steps), computed without touching the page. +""" + +from __future__ import annotations + +import re +from typing import Any, Optional, Sequence + +from openadapt_flow.gui.model import ROLES, Container, Control, Dialog, Screen + +__all__ = ["OBSERVE_JS", "PageActuator", "screen_from_dom"] + +#: Cap on the page text kept; a longer page is a partial read. +TEXT_CAP = 20000 + +OBSERVE_JS = r"""(textCap) => { + const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim(); + const visible = (el) => { + if (!el.isConnected) return false; + const st = getComputedStyle(el); + if (st.visibility === 'hidden' || st.display === 'none') return false; + if (el.closest('[hidden], [aria-hidden="true"]')) return false; + return el.getClientRects().length > 0; + }; + const path = (el) => { + if (el.id && document.querySelectorAll('#' + CSS.escape(el.id)).length === 1) + return '#' + CSS.escape(el.id); + const parts = []; + let node = el; + while (node && node.nodeType === 1 && node !== document.documentElement) { + if (node.id && document.querySelectorAll('#' + CSS.escape(node.id)).length === 1) { + parts.unshift('#' + CSS.escape(node.id)); + return parts.join(' > '); + } + const tag = node.tagName.toLowerCase(); + let i = 1; + for (let s = node.previousElementSibling; s; s = s.previousElementSibling) + if (s.tagName === node.tagName) i++; + parts.unshift(tag + ':nth-of-type(' + i + ')'); + node = node.parentElement; + } + return 'html > ' + parts.join(' > '); + }; + const byIds = (ids) => clean(String(ids || '').split(/\s+/).map((id) => { + const n = id && document.getElementById(id); + return n ? n.textContent : ''; + }).join(' ')); + const ownText = (el) => { + const c = el.cloneNode(true); + for (const x of c.querySelectorAll('input, select, textarea')) x.remove(); + return clean(c.textContent); + }; + const roleOf = (el) => { + const aria = (el.getAttribute('role') || '').toLowerCase(); + const map = {textbox: 'textbox', searchbox: 'textbox', checkbox: 'checkbox', + switch: 'switch', radio: 'radio', combobox: 'combobox', listbox: 'listbox', + button: 'button', link: 'link', tab: 'tab', menuitem: 'menuitem', + gridcell: 'cell', cell: 'cell', spinbutton: 'textbox'}; + if (map[aria]) return map[aria]; + const tag = el.tagName.toLowerCase(); + if (tag === 'a') return el.hasAttribute('href') ? 'link' : null; + if (tag === 'button') return 'button'; + if (tag === 'select') return el.multiple ? 'listbox' : 'combobox'; + if (tag === 'textarea') return 'textbox'; + if (tag === 'input') { + const t = (el.getAttribute('type') || 'text').toLowerCase(); + if (t === 'hidden' || t === 'file') return null; + if (t === 'checkbox') return 'checkbox'; + if (t === 'radio') return 'radio'; + if (['submit', 'button', 'reset', 'image'].includes(t)) return 'button'; + return 'textbox'; + } + if (el.isContentEditable && el.getAttribute('contenteditable') !== null) return 'textbox'; + return null; + }; + const nameOf = (el, role) => { + const aria = clean(el.getAttribute('aria-label')) || byIds(el.getAttribute('aria-labelledby')); + if (aria) return aria; + if (el.id) { + const lab = document.querySelector('label[for="' + CSS.escape(el.id) + '"]'); + if (lab) return ownText(lab); + } + const wrap = el.closest('label'); + if (wrap) return ownText(wrap); + if (['button', 'link', 'tab', 'menuitem'].includes(role)) { + if (el.tagName === 'INPUT') return clean(el.value); + return clean(el.textContent) || clean(el.getAttribute('title')); + } + return clean(el.getAttribute('title')) || clean(el.getAttribute('placeholder')) + || clean(el.getAttribute('name')); + }; + const KINDS = [['fieldset', 'group'], ['[role="group"]', 'group'], + ['[role="dialog"], [role="alertdialog"], dialog', 'dialog'], + ['[role="region"], section', 'region'], ['form', 'form'], + ['tr, [role="row"]', 'row'], ['li, [role="listitem"], article', 'item']]; + const containerName = (node, kind) => { + const aria = clean(node.getAttribute('aria-label')) || byIds(node.getAttribute('aria-labelledby')); + if (aria) return aria; + if (kind === 'group' && node.tagName === 'FIELDSET') { + const lg = node.querySelector(':scope > legend'); + if (lg) return clean(lg.textContent); + } + if (kind === 'row') { + const th = node.querySelector(':scope > th, :scope > [role="rowheader"]'); + return th ? clean(th.textContent) : ''; + } + const h = node.querySelector(':scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6, :scope > header h1, :scope > header h2, :scope > header h3, :scope > header h4'); + return h ? clean(h.textContent) : ''; + }; + const chain = (el) => { + const out = []; + for (let n = el.parentElement; n && n !== document.body; n = n.parentElement) { + for (const [sel, kind] of KINDS) { + if (n.matches(sel)) { + out.unshift({handle: path(n), kind, name: containerName(n, kind), + text: clean(n.innerText).slice(0, 300)}); + break; + } + } + } + return out; + }; + const dialogs = []; + for (const d of document.querySelectorAll('[role="dialog"], [role="alertdialog"], dialog[open], [aria-modal="true"]')) { + if (!visible(d)) continue; + dialogs.push({handle: path(d), name: containerName(d, 'dialog'), + text: clean(d.innerText).slice(0, 2000), + modal: d.getAttribute('aria-modal') === 'true' || d.tagName === 'DIALOG' || d.getAttribute('role') === 'alertdialog'}); + } + const dialogOf = (el) => { + const d = el.closest('[role="dialog"], [role="alertdialog"], dialog[open], [aria-modal="true"]'); + return d && visible(d) ? path(d) : ''; + }; + const controls = []; + const seen = new Set(); + for (const el of document.querySelectorAll('input, select, textarea, button, a, [role], [contenteditable]')) { + const role = roleOf(el); + if (!role || seen.has(el) || !visible(el)) continue; + seen.add(el); + let value = ''; + let checked = null; + if (role === 'checkbox' || role === 'switch' || role === 'radio') { + checked = el.tagName === 'INPUT' ? !!el.checked : el.getAttribute('aria-checked') === 'true'; + value = el.tagName === 'INPUT' ? String(el.value || '') : ''; + } else if (el.tagName === 'SELECT') { + const o = el.selectedOptions && el.selectedOptions[0]; + value = o ? clean(o.textContent) : ''; + } else if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') { + if (role !== 'button') value = String(el.value || ''); + } else if (role === 'textbox' || role === 'cell') { + value = clean(el.textContent); + } + const errId = el.getAttribute('aria-errormessage') || ''; + controls.push({ + handle: path(el), role, name: nameOf(el, role), value, checked, + disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', + readonly: !!el.readOnly || el.getAttribute('aria-readonly') === 'true', + required: !!el.required || el.getAttribute('aria-required') === 'true', + containers: chain(el), dialog: dialogOf(el), + target: role === 'link' ? (el.getAttribute('href') || '') : '', + error: el.getAttribute('aria-invalid') === 'true' ? byIds(errId) : '', + }); + } + const errors = []; + for (const a of document.querySelectorAll('[role="alert"]')) { + if (visible(a) && clean(a.textContent)) errors.push(clean(a.textContent)); + } + const text = String(document.body ? document.body.innerText : ''); + return {controls, dialogs, errors, title: document.title, + location: location.pathname + location.search, + text: text.slice(0, textCap), complete: text.length <= textCap}; +}""" + + +def screen_from_dom(raw: dict[str, Any]) -> Screen: + """Build a :class:`Screen` from what :data:`OBSERVE_JS` returned.""" + + controls = [] + for c in raw.get("controls") or (): + role = c.get("role") if c.get("role") in ROLES else "other" + controls.append( + Control( + handle=str(c["handle"]), + role=role, + name=str(c.get("name") or ""), + value=str(c.get("value") or ""), + checked=c.get("checked"), + disabled=bool(c.get("disabled")), + readonly=bool(c.get("readonly")), + required=bool(c.get("required")), + containers=tuple( + Container( + str(b["handle"]), + str(b.get("kind") or "group"), + str(b.get("name") or ""), + str(b.get("text") or ""), + ) + for b in c.get("containers") or () + ), + dialog=str(c.get("dialog") or ""), + target=str(c.get("target") or ""), + error=str(c.get("error") or ""), + ) + ) + return Screen( + controls=tuple(controls), + dialogs=tuple( + Dialog( + str(d["handle"]), + str(d.get("name") or ""), + str(d.get("text") or ""), + bool(d.get("modal")), + ) + for d in raw.get("dialogs") or () + ), + location=str(raw.get("location") or ""), + title=str(raw.get("title") or ""), + text=str(raw.get("text") or ""), + complete=bool(raw.get("complete")), + errors=tuple(str(e) for e in raw.get("errors") or ()), + ) + + +_READ_ONLY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) + + +class PageActuator: + """An :class:`~openadapt_flow.gui.model.Actuator` over a Playwright page. + + ``write_get_paths`` are regular expressions, from the pack, for GET + requests that change state on this app (a commit drawn as a plain link). + """ + + def __init__(self, page: Any, *, write_get_paths: Sequence[str] = ()) -> None: + self.page = page + self._writes = 0 + self._get_writes = tuple(re.compile(p) for p in write_get_paths) + page.on("request", self._on_request) + + def _on_request(self, request: Any) -> None: + method = str(request.method).upper() + if method not in _READ_ONLY_METHODS: + self._writes += 1 + return + if self._get_writes: + from urllib.parse import urlsplit + + path = urlsplit(str(request.url)).path + if any(p.search(path) for p in self._get_writes): + self._writes += 1 + + def _settle(self) -> None: + self.page.wait_for_load_state("load") + self.page.wait_for_load_state("networkidle") + + def observe(self) -> Screen: + """Read the page once it settles. A read cut off by a navigation is + retried on the new page; after three tries the error is raised.""" + + from playwright.sync_api import Error as PlaywrightError + + for attempt in range(3): + self._settle() + try: + return screen_from_dom(self.page.evaluate(OBSERVE_JS, TEXT_CAP)) + except PlaywrightError as exc: + if attempt == 2 or "context was destroyed" not in str(exc): + raise + self.page.wait_for_timeout(100) + raise AssertionError("unreachable") + + def click(self, handle: str) -> None: + self.page.locator(handle).click() + # A click may start a navigation or a request a moment later; give + # it time to start before waiting for the page to settle. + self.page.wait_for_timeout(150) + self._settle() + + def set_text(self, handle: str, value: str) -> None: + self.page.locator(handle).fill(value) + self.page.locator(handle).dispatch_event("change") + self._settle() + + def set_checked(self, handle: str, checked: bool) -> None: + self.page.locator(handle).set_checked(checked) + self._settle() + + def write_count(self) -> Optional[int]: + return self._writes diff --git a/packages/flow/openadapt_flow/gui/model.py b/packages/flow/openadapt_flow/gui/model.py new file mode 100644 index 0000000000..a7f7786438 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/model.py @@ -0,0 +1,378 @@ +"""A neutral view of one screen, and how a pack names a control on it. + +Every backend reads a screen differently: a browser has a DOM, a desktop app +an accessibility tree, a spreadsheet a grid of cells. The mechanisms in this +package read only what they all share: + +- :class:`Control`: one thing a person can act on or read, with a normalised + ``role`` (:data:`ROLES`), its accessible ``name``, its value or checked + state, and the chain of :class:`Container` objects it sits in (a fieldset, + a card, a table row, a dialog), outermost first. +- :class:`Dialog`: an open dialog, and the controls inside it. +- :class:`Screen`: the controls, dialogs and containers seen at one moment. + ``complete`` is False when the backend capped or could not finish the read; + a partial screen can refute a check, never hold one. + +A :class:`ControlSpec` is pack data that names exactly one control by role, +name, containers and (for a link) target. :func:`match_one` resolves it; zero +or several matches are different failures, and neither picks a control. + +:class:`DemoStep` is one action of a demonstration with the screen before and +after it and the number of writes the backend counted in between. +:class:`Actuator` is what a mechanism needs from a live backend. + +Nothing here names an application or holds a word list. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Callable, Literal, Optional, Protocol, runtime_checkable + +__all__ = [ + "ACTIVATABLE", + "EDITABLE", + "ROLES", + "Actuator", + "AmbiguousControl", + "Container", + "Control", + "ControlSpec", + "DemoStep", + "Dialog", + "MissingControl", + "Recorder", + "Screen", + "match_all", + "match_one", + "norm", + "screen_signature", + "spec_for", +] + +#: The roles a backend maps its controls to. Anything else is ``other``. +ROLES = frozenset( + { + "textbox", + "checkbox", + "switch", + "radio", + "combobox", + "listbox", + "button", + "link", + "tab", + "menuitem", + "cell", + "text", + "other", + } +) +#: Roles a person activates to move on, open something or commit. +ACTIVATABLE = frozenset({"button", "link", "tab", "menuitem"}) +#: Roles that hold a value a person enters. +EDITABLE = frozenset( + {"textbox", "checkbox", "switch", "radio", "combobox", "listbox", "cell"} +) + + +def norm(text: object) -> str: + """Whitespace collapsed and case folded: how names are compared.""" + + return " ".join(str(text or "").split()).casefold() + + +@dataclass(frozen=True) +class Container: + """A labelled or structural region around controls. + + ``handle`` is the backend's opaque id for it, stable within one screen + read and across reads of the same element. ``kind`` is what it is + structurally (``group``, ``row``, ``dialog``, ``region``, ``item``, + ``form``); ``name`` its own label or heading, possibly empty; ``text`` its + visible text, capped by the backend.""" + + handle: str + kind: str = "group" + name: str = "" + text: str = "" + + +@dataclass(frozen=True) +class Control: + """One control. ``handle`` is opaque to every mechanism: only the backend + that made it acts on it.""" + + handle: str + role: str + name: str = "" + value: str = "" + checked: Optional[bool] = None + disabled: bool = False + readonly: bool = False + required: bool = False + #: Containers, outermost first. Dialogs appear here too. + containers: tuple[Container, ...] = () + #: Handle of the open dialog that holds the control, or "". + dialog: str = "" + #: Where a link goes, as the backend reports it (opaque), or "". + target: str = "" + #: The control's own error message, if the backend shows one. + error: str = "" + + def __post_init__(self) -> None: + if self.role not in ROLES: + raise ValueError(f"unknown role {self.role!r}") + + @property + def editable(self) -> bool: + return self.role in EDITABLE and not self.disabled and not self.readonly + + @property + def activatable(self) -> bool: + return self.role in ACTIVATABLE and not self.disabled + + def container_names(self) -> tuple[str, ...]: + return tuple(norm(c.name) for c in self.containers if c.name) + + +@dataclass(frozen=True) +class Dialog: + handle: str + name: str = "" + text: str = "" + #: ``modal`` when the backend says the dialog blocks the rest of the screen. + modal: bool = True + + +@dataclass(frozen=True) +class Screen: + controls: tuple[Control, ...] = () + dialogs: tuple[Dialog, ...] = () + #: Where the screen is (a URL path, a window title, a sheet name): opaque. + location: str = "" + title: str = "" + text: str = "" + #: False when the backend capped the read or could not finish it. + complete: bool = True + #: Banner or summary errors the backend shows outside any one control. + errors: tuple[str, ...] = () + + def control(self, handle: str) -> Optional[Control]: + for ctrl in self.controls: + if ctrl.handle == handle: + return ctrl + return None + + def containers(self) -> dict[str, Container]: + out: dict[str, Container] = {} + for ctrl in self.controls: + for box in ctrl.containers: + out.setdefault(box.handle, box) + return out + + def in_dialog(self, dialog: str) -> tuple[Control, ...]: + return tuple(c for c in self.controls if c.dialog == dialog) + + +def screen_signature(screen: Screen) -> tuple[object, ...]: + """What has to change for a step to count as having moved the screen: + the location, the title, the open dialogs and the editable controls (by + role, name and handle). A value typed into a field does not change it.""" + + return ( + screen.location, + screen.title, + tuple(sorted(d.handle for d in screen.dialogs)), + tuple((c.role, norm(c.name), c.handle) for c in screen.controls if c.editable), + ) + + +# -- naming a control ------------------------------------------------------------- + + +class MissingControl(LookupError): + """No control on the screen matches the spec.""" + + +class AmbiguousControl(LookupError): + """More than one control matches the spec.""" + + +@dataclass(frozen=True) +class ControlSpec: + """Pack data naming one control. + + ``role`` is one of :data:`ROLES`, or ``"activatable"`` for any of + :data:`ACTIVATABLE` (a step that one version of an app draws as a button + and another as a link). ``name`` is compared whole after :func:`norm`, never + as a substring. ``containers`` must appear in the control's container names + in this order (other containers may sit between them). ``target``, when + set, must equal the link's target exactly. ``dialog`` says whether the + control must be inside an open dialog (True), outside every dialog + (False) or either (None).""" + + role: str + name: str + containers: tuple[str, ...] = () + target: Optional[str] = None + dialog: Optional[bool] = None + + def __post_init__(self) -> None: + if self.role != "activatable" and self.role not in ROLES: + raise ValueError(f"unknown role {self.role!r}") + if not norm(self.name): + raise ValueError("a control spec needs a name") + + def matches(self, ctrl: Control) -> bool: + if self.role == "activatable": + if ctrl.role not in ACTIVATABLE: + return False + elif ctrl.role != self.role: + return False + if norm(ctrl.name) != norm(self.name): + return False + if self.target is not None and ctrl.target != self.target: + return False + if self.dialog is not None and bool(ctrl.dialog) != self.dialog: + return False + return _in_order( + tuple(norm(c) for c in self.containers), ctrl.container_names() + ) + + +def _in_order(wanted: tuple[str, ...], have: tuple[str, ...]) -> bool: + at = 0 + for name in have: + if at < len(wanted) and name == wanted[at]: + at += 1 + return at == len(wanted) + + +def match_all(spec: ControlSpec, screen: Screen) -> tuple[Control, ...]: + return tuple(c for c in screen.controls if spec.matches(c)) + + +def match_one(spec: ControlSpec, screen: Screen) -> Control: + """The one control ``spec`` names. Raises :class:`MissingControl` or + :class:`AmbiguousControl`; it never picks the first of several.""" + + found = match_all(spec, screen) + if not found: + raise MissingControl(f"no {spec.role} named {spec.name!r}") + if len(found) > 1: + raise AmbiguousControl(f"{len(found)} controls match {spec.role} {spec.name!r}") + return found[0] + + +def spec_for( + ctrl: Control, + screen: Screen, + *, + role: Optional[str] = None, +) -> Optional[ControlSpec]: + """The narrowest spec that names ``ctrl`` alone on ``screen``: its role and + name, then its labelled containers and its link target as needed. None + when even all of them still match another control (two identical rows + with no label between them): the pack author has to say which.""" + + base = ControlSpec( + role=role or ctrl.role, + name=ctrl.name, + dialog=bool(ctrl.dialog), + ) + names = tuple(c.name for c in ctrl.containers if c.name) + tries = [base] + for n in range(1, len(names) + 1): + tries.append(ControlSpec(base.role, base.name, names[-n:], dialog=base.dialog)) + if ctrl.target: + tries += [ + ControlSpec(t.role, t.name, t.containers, ctrl.target, t.dialog) + for t in tries + ] + for spec in tries: + if match_all(spec, screen) == (ctrl,): + return spec + return None + + +# -- demonstrations and live backends --------------------------------------------- + +ActionKind = Literal["click", "type", "check", "uncheck", "select"] + + +@dataclass(frozen=True) +class DemoStep: + """One action of a demonstration. + + ``target`` is the control as seen in ``before``. ``writes`` is how many + writes the backend counted between ``before`` and ``after`` (requests that + change state, a file save, a cell committed), or None when it could not + count them.""" + + action: ActionKind + target: Control + before: Screen + after: Screen + writes: Optional[int] + value: str = "" + + +@runtime_checkable +class Actuator(Protocol): + """What a mechanism needs from a live backend. Every action waits for the + screen to settle before it returns.""" + + def observe(self) -> Screen: ... + + def click(self, handle: str) -> None: ... + + def set_text(self, handle: str, value: str) -> None: ... + + def set_checked(self, handle: str, checked: bool) -> None: ... + + def write_count(self) -> Optional[int]: + """Writes counted since the backend started, or None if it cannot + count them. A backend that cannot count can never show a commit.""" + ... + + +@dataclass +class Recorder: + """Wrap an :class:`Actuator` and keep every action as a :class:`DemoStep`. + + Used to record a demonstration through the same backend a run uses.""" + + actuator: Actuator + steps: list[DemoStep] = field(default_factory=list) + + def _do( + self, + action: ActionKind, + handle: str, + run: Callable[[], None], + value: str = "", + ) -> None: + before = self.actuator.observe() + target = before.control(handle) + if target is None: + raise MissingControl(handle) + w0 = self.actuator.write_count() + run() + w1 = self.actuator.write_count() + after = self.actuator.observe() + writes = None if w0 is None or w1 is None else w1 - w0 + self.steps.append(DemoStep(action, target, before, after, writes, value)) + + def click(self, handle: str) -> None: + self._do("click", handle, lambda: self.actuator.click(handle)) + + def set_text(self, handle: str, value: str) -> None: + self._do("type", handle, lambda: self.actuator.set_text(handle, value), value) + + def set_checked(self, handle: str, checked: bool) -> None: + self._do( + "check" if checked else "uncheck", + handle, + lambda: self.actuator.set_checked(handle, checked), + ) diff --git a/packages/flow/openadapt_flow/gui/steps.py b/packages/flow/openadapt_flow/gui/steps.py new file mode 100644 index 0000000000..71f94058ec --- /dev/null +++ b/packages/flow/openadapt_flow/gui/steps.py @@ -0,0 +1,310 @@ +"""Steps that move a form on, whatever control draws them, and the commit point. + +A form moves on when a person activates something: a "Next" button, a +"Continue" link, a step tab, a menu item. Packs used to list only buttons as +next controls, so a form whose next control was a link stopped with "next +button missing". Here any activatable control (:data:`~openadapt_flow.gui.model.ACTIVATABLE`) +can be a step, and what a step *does* comes from the demonstration, never +from its words: + +- :func:`learn_steps` reads each click of a demonstration and records what the + backend saw it do (:class:`StepRole`): ``commit`` when it counted writes, + ``navigate`` when the screen changed and nothing was written, ``in_place`` + when neither, ``unknown`` when the backend could not count writes. +- The commit points are the steps the demonstration showed writing + (:func:`commit_points`), with the number of writes each made. A link that + commits is a commit point because it wrote, not because it says "Submit". +- :func:`take_step` resolves a learned step on the live screen, clicks it + and asks :func:`judge_step` whether it did what the demonstration showed. + +:func:`judge_step` is a verdict site. A commit step holds only when the +backend counted exactly the writes the demonstration made. A backend that +cannot count writes never shows a commit, so a commit through a plain link +that sends nothing the backend counts stays unproven, as it should: the run +has no evidence the record was saved. A navigation step that wrote, or that +left the screen as it was, is refuted. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + AmbiguousControl, + Control, + ControlSpec, + DemoStep, + MissingControl, + Screen, + match_one, + screen_signature, + spec_for, +) +from openadapt_flow.verdict import Observed, Result, Status, Subject +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "LearnedStep", + "StepEvidence", + "StepOutcome", + "StepRole", + "StepSpec", + "commit_points", + "judge_step", + "learn_steps", + "take_step", +] + + +class StepRole(str, Enum): + COMMIT = "commit" + NAVIGATE = "navigate" + IN_PLACE = "in_place" + UNKNOWN = "unknown" + + +@dataclass(frozen=True) +class StepSpec: + """Pack data for one step: which control, and what it did in the demo. + + ``writes`` is the number of writes the demonstration counted for it: at + least 1 for a commit, 0 otherwise.""" + + step_id: str + control: ControlSpec + role: StepRole + writes: int = 0 + + def __post_init__(self) -> None: + if not isinstance(self.role, StepRole): + raise ValueError(f"unknown step role {self.role!r}") + if self.role is StepRole.COMMIT and self.writes < 1: + raise ValueError("a commit step wrote at least once in the demo") + if self.role is not StepRole.COMMIT and self.writes != 0: + raise ValueError("only a commit step writes") + + +@dataclass(frozen=True) +class LearnedStep: + """What :func:`learn_steps` found for one demonstrated click. ``spec`` is + None when no spec names the control alone (``reason`` says why); the + pack author has to name it.""" + + index: int + control: Control + role: StepRole + writes: Optional[int] + spec: Optional[StepSpec] + reason: str = "" + + +def _role_of(step: DemoStep) -> StepRole: + if step.writes is None or step.writes < 0: + return StepRole.UNKNOWN + if step.writes > 0: + return StepRole.COMMIT + if screen_signature(step.after) != screen_signature(step.before): + return StepRole.NAVIGATE + return StepRole.IN_PLACE + + +def learn_steps(demo: Sequence[DemoStep]) -> tuple[LearnedStep, ...]: + """One :class:`LearnedStep` per click on an activatable control. + + A step's role comes from what the backend counted and saw, so the same + word ("Continue") can be a navigation in one app and a commit in + another, and a link and a button are treated alike.""" + + out = [] + for index, step in enumerate(demo): + if step.action != "click" or not step.target.activatable: + continue + role = _role_of(step) + spec = spec_for(step.target, step.before) + if role is StepRole.UNKNOWN: + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + None, + "the backend could not count writes for this click", + ) + ) + continue + if spec is None: + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + None, + "another control on the screen has the same role, name and containers", + ) + ) + continue + writes = int(step.writes or 0) if role is StepRole.COMMIT else 0 + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + StepSpec(f"step-{index}", spec, role, writes), + ) + ) + return tuple(out) + + +def commit_points(steps: Sequence[LearnedStep]) -> tuple[LearnedStep, ...]: + """The steps the demonstration showed writing, in order.""" + + return tuple(s for s in steps if s.role is StepRole.COMMIT) + + +# -- the verdict ------------------------------------------------------------------ + + +@dataclass(frozen=True) +class StepEvidence: + """What one live step did. ``moved`` is whether the screen signature + changed (None when the after read failed).""" + + step_id: str + role: object + expected_writes: object + writes_before: object + writes_after: object + moved: object + after_complete: object + after_errors: tuple[str, ...] = () + run_id: str = "" + + +def _count(value: object) -> Optional[int]: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + return None + return value + + +@verdict_site("gui.steps.judge_step", classes="C3 C5") +def judge_step(ev: StepEvidence) -> Result: + """Did the step do what the demonstration showed? + + - ``commit``: exactly ``expected_writes`` new writes, on a complete read + with no error shown. No write, or a different number, is refuted. + - ``navigate``: the screen changed and nothing was written. + - ``in_place``: nothing was written. + - ``unknown`` or any role nobody listed: not checked. + + A write count that is missing, negative or not a whole number is not + checked; so is a partial read with nothing to refute.""" + + subject = Subject(run_id=ev.run_id, surface="gui", key=ev.step_id, field="step") + obs = Observed(ev, complete=ev.after_complete is True) + try: + role = StepRole(ev.role) if not isinstance(ev.role, StepRole) else ev.role + except ValueError: + return Result.not_checked(subject, f"unlisted step role {ev.role!r}") + if role is StepRole.UNKNOWN: + return Result.not_checked( + subject, "the demo could not count this step's writes" + ) + before, after = _count(ev.writes_before), _count(ev.writes_after) + if before is None or after is None or after < before: + return Result.not_checked(subject, "the backend could not count writes") + delta = after - before + if ev.after_errors: + return Result.refuted( + subject, obs, f"the screen shows an error: {ev.after_errors[0]}" + ) + if role is StepRole.COMMIT: + want = _count(ev.expected_writes) + if not want: + return Result.not_checked(subject, "no expected write count for a commit") + if delta == 0: + return Result.refuted(subject, obs, "the commit step wrote nothing") + if delta != want: + return Result.refuted( + subject, + obs, + f"the commit step wrote {delta} times; the demo wrote {want}", + ) + elif delta: + return Result.refuted(subject, obs, f"a {role.value} step wrote {delta} times") + elif role is StepRole.NAVIGATE: + if ev.moved is False: + return Result.refuted(subject, obs, "the screen did not change") + if ev.moved is not True: + return Result.not_checked(subject, "the screen after the step was not read") + if ev.after_complete is not True: + return Result.not_checked(subject, "the screen after the step was read in part") + return Result.held(subject, obs, f"{role.value} as demonstrated") + + +# -- running a step --------------------------------------------------------------- + + +@dataclass(frozen=True) +class StepOutcome: + result: Result + clicked: bool + control: Optional[Control] = None + after: Optional[Screen] = None + + @property + def held(self) -> bool: + return self.result.status is Status.HELD + + +def take_step( + actuator: Actuator, + spec: StepSpec, + *, + run_id: str = "", + screen: Optional[Screen] = None, +) -> StepOutcome: + """Resolve ``spec`` on the live screen, click it, and judge it. + + Nothing is clicked when the control is missing or ambiguous, or when the + step is a commit and the backend cannot count writes (a commit there + could never be shown, so it is not attempted).""" + + subject = Subject(run_id=run_id, surface="gui", key=spec.step_id, field="step") + before_screen = screen if screen is not None else actuator.observe() + try: + ctrl = match_one(spec.control, before_screen) + except (MissingControl, AmbiguousControl) as exc: + return StepOutcome(Result.not_checked(subject, str(exc)), clicked=False) + if not ctrl.activatable: + return StepOutcome( + Result.not_checked(subject, "the control is disabled"), False, ctrl + ) + w0 = actuator.write_count() + if spec.role is StepRole.COMMIT and w0 is None: + return StepOutcome( + Result.not_checked(subject, "this backend cannot count writes; no commit"), + False, + ctrl, + ) + actuator.click(ctrl.handle) + w1 = actuator.write_count() + after = actuator.observe() + ev = StepEvidence( + step_id=spec.step_id, + role=spec.role, + expected_writes=spec.writes if spec.role is StepRole.COMMIT else 0, + writes_before=w0, + writes_after=w1, + moved=screen_signature(after) != screen_signature(before_screen), + after_complete=after.complete, + after_errors=tuple(after.errors) + + tuple(c.error for c in after.controls if c.error), + run_id=run_id, + ) + return StepOutcome(judge_step(ev), True, ctrl, after) diff --git a/packages/flow/tests/failopen/sites/gui_steps.py b/packages/flow/tests/failopen/sites/gui_steps.py new file mode 100644 index 0000000000..902a7d1a04 --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_steps.py @@ -0,0 +1,124 @@ +"""gui.steps.judge_step (C3 C5): did a step (a link, a tab, a button) do what +the demonstration showed? + +A commit holds only on exactly the demonstrated number of writes; a +navigation only when the screen moved and nothing was written. Write counts +that are not whole numbers, and roles nobody listed, are not checked. + +No M8: the evidence is gathered in-process by ``take_step`` from the live +backend in the same call, not read back from a store another run could have +written, so there is no stored binding to swap. +""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.gui.steps import StepEvidence, judge_step +from openadapt_flow.verdict import Status +from tests.failopen.harness import CodeCase, Lens, Seed, SiteSpec, register + +#: The fields each role's verdict depends on. +RELEVANT = { + "commit": ( + "role", + "expected_writes", + "writes_before", + "writes_after", + "after_complete", + ), + "navigate": ("role", "writes_before", "writes_after", "moved", "after_complete"), + "in_place": ("role", "writes_before", "writes_after", "after_complete"), +} + + +def _ev(role: str, **over: Any) -> dict[str, Any]: + base = { + "step_id": "s1", + "role": role, + "expected_writes": 1 if role == "commit" else 0, + "writes_before": 3, + "writes_after": 4 if role == "commit" else 3, + "moved": role == "navigate", + "after_complete": True, + "after_errors": (), + } + return {**base, **over} + + +def _relevant(ev: dict[str, Any]) -> tuple[str, ...]: + return RELEVANT.get(str(ev.get("role")), ("role",)) + + +def _fields() -> Lens: + def get(ev: dict[str, Any]) -> dict[str, Any]: + return {k: ev[k] for k in _relevant(ev) if k in ev} + + def put(ev: dict[str, Any], value: dict[str, Any]) -> None: + for k in _relevant(ev): + ev.pop(k, None) + ev.update(value) + + return Lens(get, put) + + +def _value(name: str) -> Lens: + def get(ev: dict[str, Any]) -> Any: + if name not in _relevant(ev): + raise KeyError(name) + return ev[name] + + def put(ev: dict[str, Any], value: Any) -> None: + from tests.failopen.harness import ABSENT + + if value is ABSENT: + ev.pop(name, None) + else: + ev[name] = value + + return Lens(get, put) + + +register( + SiteSpec( + id="gui.steps.judge_step", + classes="C3 C5", + target="openadapt_flow.gui.steps:judge_step", + run=lambda ev: judge_step(StepEvidence(**ev)), + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_ev("commit"), True, "one write, as demonstrated"), + Seed(_ev("navigate"), True, "moved, nothing written"), + Seed(_ev("in_place"), True, "nothing written"), + Seed(_ev("commit", writes_after=3), False, "a commit that wrote nothing"), + Seed(_ev("commit", writes_after=5), False, "two writes for one"), + Seed(_ev("navigate", writes_after=4), False, "a navigation that wrote"), + Seed(_ev("navigate", moved=False), False, "did not move"), + Seed(_ev("commit", after_errors=("Card declined",)), False, "error shown"), + Seed(_ev("unknown"), False, "the demo could not count writes"), + ], + fields=_fields(), + values=tuple( + _value(n) + for n in ( + "role", + "expected_writes", + "writes_before", + "writes_after", + "moved", + "after_complete", + ) + ), + partial=lambda ev: [("after_complete", {**ev, "after_complete": False})], + codes=lambda: [ + CodeCase( + evidence={**_ev("commit"), "role": "submitted"}, + may_have_changed=True, + forbidden=lambda out: False, + label="a step role nobody listed", + unknown=True, + ) + ], + ) +) diff --git a/packages/flow/tests/gui/__init__.py b/packages/flow/tests/gui/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/tests/gui/_apps.py b/packages/flow/tests/gui/_apps.py new file mode 100644 index 0000000000..997af6ec2d --- /dev/null +++ b/packages/flow/tests/gui/_apps.py @@ -0,0 +1,219 @@ +"""Synthetic apps for the GUI mechanism tests, served through Playwright routes. + +Each app is a small in-memory server on a ``.test`` host: requests never +leave the browser process. The apps are of different kinds on purpose (a web +form, an EMR-like chart, a SaaS settings page), and none of them copies a +benchmark portal. Every record is synthetic. +""" + +from __future__ import annotations + +import contextlib +import json +from dataclasses import dataclass, field +from typing import Any, Callable, Iterator, Optional +from urllib.parse import parse_qs, urlsplit + +Handler = Callable[["App", str, str, dict[str, list[str]]], tuple[int, str]] + +PAGE = """{title} +{body}""" + + +@dataclass +class App: + host: str + routes: dict[tuple[str, str], Handler] + state: dict[str, Any] = field(default_factory=dict) + log: list[tuple[str, str]] = field(default_factory=list) + + @property + def origin(self) -> str: + return f"http://{self.host}" + + def handle(self, route: Any) -> None: + req = route.request + parts = urlsplit(req.url) + method = req.method.upper() + body = req.post_data or "" + form = parse_qs(body) if body and not body.startswith("{") else {} + if body.startswith("{"): + form = {k: [str(v)] for k, v in json.loads(body).items()} + form.update(parse_qs(parts.query)) + self.log.append((method, parts.path)) + fn = self.routes.get((method, parts.path)) or self.routes.get((method, "*")) + if fn is None: + route.fulfill(status=404, body="not found") + return + status, html = fn(self, parts.path, method, form) + if status in (302, 303): + route.fulfill(status=status, headers={"Location": html}, body="") + return + route.fulfill(status=status, body=html, content_type="text/html") + + +@contextlib.contextmanager +def serve(page: Any, app: App) -> Iterator[App]: + page.context.route(f"{app.origin}/**", app.handle) + try: + yield app + finally: + page.context.unroute(f"{app.origin}/**") + + +def page(title: str, body: str) -> str: + return PAGE.format(title=title, body=body) + + +# -- a web form: an event registration wizard whose next control is a link -------- + + +def registration_app( + *, next_writes: bool = False, commit_posts: int = 1, error_after: bool = False +) -> App: + """Contact details, then a ticket, then Register. "Continue" is a link that + keeps the values in session storage. ``next_writes`` makes the link also + post a draft (an app that changed); ``commit_posts`` is how many requests + Register sends; ``error_after`` shows an alert after the commit.""" + + draft = "fetch('/draft',{method:'POST',body:'{}'});" if next_writes else "" + + def contact(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page( + "Your details", + f"""

Your details

+
Contact + +
+ +
""", + ) + + def ticket(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + sends = "".join( + "fetch('/register',{method:'POST',body:JSON.stringify(data())});" + for _ in range(commit_posts - 1) + ) + return 200, page( + "Ticket", + f"""

Ticket

+ + +Back
+
""", + ) + + def register(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state.setdefault("records", []).append( + {k: v[0] for k, v in form.items() if v} + ) + return done(app, path, method, form) + + def done(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + alert = '

Payment could not be taken

' if error_after else "" + return 200, page("Done", f"

Registration received

{alert}
") + + def draft_ok(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, "{}" + + return App( + "reg.test", + { + ("GET", "/contact"): contact, + ("GET", "/ticket"): ticket, + ("POST", "/register"): register, + ("GET", "/done"): done, + ("POST", "/draft"): draft_ok, + }, + ) + + +# -- an EMR-like chart whose commit is a plain link --------------------------------- + + +def chart_app() -> App: + """A patient chart. "Save draft" posts in place; "Sign note" is a link + whose GET signs the note on the server.""" + + def chart(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + note = app.state.get("draft", "") + return 200, page( + "Chart", + f"""

Chart: Test Patient A

+

Progress note

+ + +Sign note
+
""", + ) + + def save_draft(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state["draft"] = form.get("note", [""])[0] + return 200, "{}" + + def sign(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state["signed"] = app.state.get("draft", "") + return 200, page("Signed", "

Note signed

") + + def patients(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page("Patients", "

Patients

") + + return App( + "chart.test", + { + ("GET", "/patient/7"): chart, + ("POST", "/notes/7/draft"): save_draft, + ("GET", "/notes/7/sign"): sign, + ("GET", "/patients"): patients, + }, + ) + + +# -- a SaaS settings page with tabs and a link that publishes ------------------------ + + +def settings_app() -> App: + def settings(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page( + "Settings", + """

Workspace settings

+
+
+
+ +Publish changes +

+
""", + ) + + def api(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state["settings"] = {k: v[0] for k, v in form.items()} + return 200, "{}" + + return App( + "app.test", + {("GET", "/settings"): settings, ("POST", "/api/settings"): api}, + ) + + +def wait_idle(page_: Any, ms: int = 50) -> None: + page_.wait_for_timeout(ms) + + +def first(seq: Any, pred: Callable[[Any], bool]) -> Optional[Any]: + for x in seq: + if pred(x): + return x + return None diff --git a/packages/flow/tests/gui/_grid.py b/packages/flow/tests/gui/_grid.py new file mode 100644 index 0000000000..0d13e96420 --- /dev/null +++ b/packages/flow/tests/gui/_grid.py @@ -0,0 +1,143 @@ +"""A spreadsheet-like grid surface with no browser. + +It exposes its screen as an accessibility tree (sheet tabs, a grid of rows +and cells, a toolbar, an optional dialog) and reads it through +:func:`openadapt_flow.gui.adapters.screen_from_tree`, the path a desktop +backend would use. Writes are counted when the workbook is saved, so the +grid can show a commit; ``count_writes=False`` makes a backend that cannot. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Optional + +from openadapt_flow.gui.adapters import screen_from_tree +from openadapt_flow.gui.model import Screen + + +@dataclass +class Sheet: + name: str + columns: tuple[str, ...] + rows: list[list[str]] = field(default_factory=list) + + +@dataclass +class GridApp: + sheets: list[Sheet] + count_writes: bool = True + active: int = 0 + saved: list[dict[str, list[list[str]]]] = field(default_factory=list) + #: Extra toolbar items: (handle, role, name, action key). + extra_tools: list[tuple[str, str, str, str]] = field(default_factory=list) + dialog: Optional[dict[str, Any]] = None + checks: dict[str, bool] = field(default_factory=dict) + _writes: int = 0 + + # -- the tree --------------------------------------------------------------- + + def tree(self) -> dict[str, Any]: + sheet = self.sheets[self.active] + rows = [] + for r, row in enumerate(sheet.rows): + cells = [ + { + "role": "cell", + "name": col, + "value": row[c], + "handle": f"cell:{sheet.name}:{r}:{c}", + } + for c, col in enumerate(sheet.columns) + ] + rows.append( + { + "role": "row", + "name": f"Row {r + 1}", + "handle": f"row:{sheet.name}:{r}", + "text": " ".join(row), + "children": cells, + } + ) + tools = [ + {"role": "menu item", "name": "Save", "handle": "tool:save"}, + {"role": "push button", "name": "Insert row", "handle": "tool:insert"}, + ] + [ + {"role": role, "name": name, "handle": handle} + for handle, role, name, _ in self.extra_tools + ] + children: list[dict[str, Any]] = [ + { + "role": "group", + "name": "Sheets", + "handle": "tabs", + "children": [ + {"role": "tab item", "name": s.name, "handle": f"tab:{i}"} + for i, s in enumerate(self.sheets) + ], + }, + { + "role": "group", + "name": "Toolbar", + "handle": "toolbar", + "children": tools, + }, + { + "role": "grid", + "name": sheet.name, + "handle": f"grid:{sheet.name}", + "children": rows, + }, + ] + if self.dialog is not None: + children.append(self.dialog) + return { + "role": "window", + "name": f"Workbook - {sheet.name}", + "children": children, + } + + # -- the actuator ------------------------------------------------------------- + + def observe(self) -> Screen: + return screen_from_tree( + self.tree(), location=f"sheet:{self.sheets[self.active].name}" + ) + + def click(self, handle: str) -> None: + if handle.startswith("tab:"): + self.active = int(handle.split(":")[1]) + elif handle == "tool:save": + self.saved.append({s.name: [list(r) for r in s.rows] for s in self.sheets}) + self._writes += 1 + elif handle == "tool:insert": + sheet = self.sheets[self.active] + sheet.rows.append([""] * len(sheet.columns)) + else: + for h, _, _, action in self.extra_tools: + if h == handle: + self.on_tool(action) + return + if self.dialog is not None: + self.on_dialog_click(handle) + return + raise KeyError(handle) + + def on_tool(self, action: str) -> None: # overridden by tests + raise KeyError(action) + + def on_dialog_click(self, handle: str) -> None: # overridden by tests + raise KeyError(handle) + + def set_text(self, handle: str, value: str) -> None: + kind, sheet_name, r, c = handle.split(":") + if kind != "cell": + raise KeyError(handle) + sheet = next(s for s in self.sheets if s.name == sheet_name) + sheet.rows[int(r)][int(c)] = value + + def set_checked(self, handle: str, checked: bool) -> None: + self.checks[handle] = checked + + def write_count(self) -> Optional[int]: + return self._writes if self.count_writes else None diff --git a/packages/flow/tests/gui/conftest.py b/packages/flow/tests/gui/conftest.py new file mode 100644 index 0000000000..17104e290a --- /dev/null +++ b/packages/flow/tests/gui/conftest.py @@ -0,0 +1,27 @@ +"""A headless browser page for the GUI mechanism tests.""" + +from __future__ import annotations + +from typing import Any, Iterator + +import pytest + + +@pytest.fixture(scope="module") +def _browser() -> Iterator[Any]: + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as pw: + browser = pw.chromium.launch(headless=True) + try: + yield browser + finally: + browser.close() + + +@pytest.fixture +def page(_browser: Any) -> Iterator[Any]: + context = _browser.new_context() + try: + yield context.new_page() + finally: + context.close() diff --git a/packages/flow/tests/gui/test_gui_steps.py b/packages/flow/tests/gui/test_gui_steps.py new file mode 100644 index 0000000000..06f52b05bf --- /dev/null +++ b/packages/flow/tests/gui/test_gui_steps.py @@ -0,0 +1,323 @@ +"""Links, tabs and menu items as steps, and the commit point, on four kinds of app. + +- a web form whose next control is a link (registration wizard); +- an EMR-like chart whose commit is a plain link (a GET that signs the note); +- a SaaS settings page with tabs and a link that publishes by POST; +- a spreadsheet-like grid with no browser (sheet tabs, a Save menu item). + +Each app is recorded once through the same backend a run uses, the steps are +learned from that demonstration, and a second run with other values replays +them. The negative cases change the app after the demonstration. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +import openadapt_flow +from openadapt_flow.gui.adapters import screen_from_form_snapshot +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.model import ControlSpec, Recorder, match_one +from openadapt_flow.gui.steps import ( + StepEvidence, + StepRole, + StepSpec, + commit_points, + judge_step, + learn_steps, + take_step, +) +from openadapt_flow.verdict import Status +from tests.gui import _apps +from tests.gui._grid import GridApp, Sheet + + +def test_code_under_test_is_this_checkout() -> None: + flow = Path(__file__).resolve().parents[2] + assert Path(openadapt_flow.__file__).resolve().is_relative_to(flow) + + +def _handle(screen, role: str, name: str) -> str: + return match_one(ControlSpec(role, name), screen).handle + + +def _record_registration(page, app) -> list: + act = PageActuator(page) + page.goto(f"{app.origin}/contact") + rec = Recorder(act) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Full name"), "Ada Example") + rec.set_text(_handle(s, "textbox", "Email"), "ada@example.test") + rec.click(_handle(s, "link", "Continue")) + s = act.observe() + page.select_option(_handle(s, "combobox", "Ticket type"), "std") + rec.click(_handle(act.observe(), "button", "Register")) + return rec.steps + + +# -- web form: the next control is a link ------------------------------------------ + + +def test_web_form_link_is_a_navigation_step_and_the_button_commits(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + learned = learn_steps(_record_registration(page, app)) + roles = [(s.control.role, s.control.name, s.role) for s in learned] + assert roles == [ + ("link", "Continue", StepRole.NAVIGATE), + ("button", "Register", StepRole.COMMIT), + ] + nxt = learned[0].spec + assert nxt is not None and nxt.control.role == "link" + assert nxt.control.target == "/ticket" or nxt.control.target is None + (commit,) = commit_points(learned) + assert commit.spec is not None and commit.spec.writes == 1 + + +def test_web_form_replays_learned_link_and_commit_with_new_values(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + app2 = _apps.registration_app() + with _apps.serve(page, app2): + act = PageActuator(page) + page.goto(f"{app2.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + out = take_step(act, steps[0], run_id="r1") + assert out.held, out.result.reason + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + out = take_step(act, steps[1], run_id="r1") + assert out.held, out.result.reason + assert app2.state["records"] == [ + {"name": "Bo Sample", "email": "bo@example.test", "ticket": "vip"} + ] + + +def test_a_link_that_starts_writing_is_refuted(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + nxt = learn_steps(_record_registration(page, app))[0].spec + changed = _apps.registration_app(next_writes=True) + with _apps.serve(page, changed): + act = PageActuator(page) + page.goto(f"{changed.origin}/contact") + out = take_step(act, nxt) + assert out.clicked and out.result.status is Status.REFUTED + assert "navigate step wrote" in out.result.reason + + +@pytest.mark.parametrize( + ("variant", "reason"), + [ + ({"commit_posts": 2}, "wrote 2 times; the demo wrote 1"), + ({"error_after": True}, "shows an error"), + ], +) +def test_a_commit_that_differs_from_the_demo_is_refuted(page, variant, reason) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + commit = learn_steps(_record_registration(page, app))[1].spec + changed = _apps.registration_app(**variant) + with _apps.serve(page, changed): + act = PageActuator(page) + page.goto(f"{changed.origin}/ticket") + out = take_step(act, commit) + assert out.result.status is Status.REFUTED + assert reason in out.result.reason + + +def test_a_missing_renamed_or_doubled_link_is_never_clicked(page) -> None: + spec = StepSpec("next", ControlSpec("link", "Continue"), StepRole.NAVIGATE) + app = _apps.registration_app() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/contact") + page.evaluate("document.getElementById('next').textContent = 'Next'") + out = take_step(act, spec) + assert not out.clicked and out.result.status is Status.NOT_CHECKED + page.evaluate( + "document.getElementById('next').textContent = 'Continue';" + "document.querySelector('nav').insertAdjacentHTML('beforeend'," + "'Continue')" + ) + out = take_step(act, spec) + assert not out.clicked and "2 controls match" in out.result.reason + pinned = StepSpec( + "next", ControlSpec("link", "Continue", target="/ticket"), StepRole.NAVIGATE + ) + page.evaluate("document.getElementById('next').setAttribute('href','/other')") + out = take_step(act, pinned) + assert not out.clicked + assert ("GET", "/elsewhere") not in app.log and ("GET", "/other") not in app.log + + +# -- EMR-like chart: the commit is a GET link ---------------------------------------- + + +def _record_chart(page, app, *, write_get_paths=()) -> list: + act = PageActuator(page, write_get_paths=write_get_paths) + page.goto(f"{app.origin}/patient/7") + rec = Recorder(act) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Note"), "Seen today; stable.") + rec.click(_handle(s, "button", "Save draft")) + rec.click(_handle(act.observe(), "link", "Sign note")) + return rec.steps + + +def test_emr_sign_link_is_a_commit_only_when_its_request_is_declared(page) -> None: + with _apps.serve(page, _apps.chart_app()) as app: + declared = learn_steps( + _record_chart(page, app, write_get_paths=[r"^/notes/\d+/sign$"]) + ) + assert [(s.control.name, s.role) for s in declared] == [ + ("Save draft", StepRole.COMMIT), + ("Sign note", StepRole.COMMIT), + ] + assert [s.control.name for s in commit_points(declared)] == [ + "Save draft", + "Sign note", + ] + with _apps.serve(page, _apps.chart_app()) as app: + undeclared = learn_steps(_record_chart(page, app)) + # A GET the backend does not count is not evidence of a commit: the link + # is learned as a navigation, and the program has one commit point fewer. + assert [(s.control.name, s.role) for s in undeclared][1] == ( + "Sign note", + StepRole.NAVIGATE, + ) + + +def test_emr_learned_sign_link_replays_and_signs(page) -> None: + paths = [r"^/notes/\d+/sign$"] + with _apps.serve(page, _apps.chart_app()) as app: + steps = [ + s.spec for s in learn_steps(_record_chart(page, app, write_get_paths=paths)) + ] + app2 = _apps.chart_app() + with _apps.serve(page, app2): + act = PageActuator(page, write_get_paths=paths) + page.goto(f"{app2.origin}/patient/7") + act.set_text(_handle(act.observe(), "textbox", "Note"), "Follow up in 2 weeks.") + assert take_step(act, steps[0]).held + out = take_step(act, steps[1]) + assert out.held, out.result.reason + assert app2.state["signed"] == "Follow up in 2 weeks." + + +# -- SaaS settings: tabs move between panels, a link publishes ------------------------ + + +def test_saas_tabs_navigate_and_a_publish_link_commits(page) -> None: + app = _apps.settings_app() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/settings") + rec = Recorder(act) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Workspace name"), "North team") + rec.click(_handle(s, "tab", "Billing")) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Billing email"), "ap@example.test") + rec.click(_handle(s, "link", "Publish changes")) + learned = learn_steps(rec.steps) + assert [(s.control.role, s.role) for s in learned] == [ + ("tab", StepRole.NAVIGATE), + ("link", StepRole.COMMIT), + ] + assert app.state["settings"] == {"ws": "North team", "be": "ap@example.test"} + + +# -- spreadsheet-like grid: no browser ------------------------------------------------- + + +def _grid() -> GridApp: + return GridApp( + [ + Sheet("Q1", ("Item", "Amount"), [["Rent", "1200"]]), + Sheet("Q2", ("Item", "Amount"), [["Rent", ""]]), + ] + ) + + +def test_grid_sheet_tab_navigates_and_save_menu_item_commits() -> None: + grid = _grid() + rec = Recorder(grid) + rec.click("tab:1") + rec.set_text("cell:Q2:0:1", "1250") + rec.click("tool:save") + learned = learn_steps(rec.steps) + assert [(s.control.role, s.control.name, s.role) for s in learned] == [ + ("tab", "Q2", StepRole.NAVIGATE), + ("menuitem", "Save", StepRole.COMMIT), + ] + replay = _grid() + for step in learned: + assert take_step(replay, step.spec).held + assert replay.saved[-1]["Q2"] == [["Rent", ""]] + + +def test_a_backend_that_cannot_count_writes_never_attempts_a_commit() -> None: + grid = _grid() + rec = Recorder(grid) + rec.click("tool:save") + (learned,) = learn_steps(rec.steps) + blind = _grid() + blind.count_writes = False + out = take_step(blind, learned.spec) + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert blind.saved == [] + rec2 = Recorder(blind) + rec2.click("tool:save") + (unknown,) = learn_steps(rec2.steps) + assert unknown.role is StepRole.UNKNOWN and unknown.spec is None + + +# -- the verdict and the form_tx adapter ------------------------------------------------ + + +def test_judge_step_needs_exact_whole_counts() -> None: + base = dict( + step_id="s", + role=StepRole.COMMIT, + expected_writes=1, + writes_before=3, + writes_after=4, + moved=True, + after_complete=True, + ) + assert judge_step(StepEvidence(**base)).status is Status.HELD + for change in ( + {"writes_after": "4"}, + {"writes_after": True}, + {"writes_before": None}, + {"writes_after": 2}, + {"role": "submit"}, + {"expected_writes": 0}, + {"after_complete": False}, + ): + got = judge_step(StepEvidence(**{**base, **change})) + assert got.status is not Status.HELD, change + + +def test_form_snapshot_links_become_link_controls() -> None: + from openadapt_flow.form_tx.types import FormSnapshot, ObservedControl + + snap = FormSnapshot( + url_origin_and_path="/hub", + controls=( + ObservedControl( + control_id="a1", dom_selector="#a1", tag="a", label_text="Continue" + ), + ObservedControl( + control_id="b1", dom_selector="#b1", tag="button", label_text="Back" + ), + ), + ) + screen = screen_from_form_snapshot(snap) + assert [(c.role, c.name) for c in screen.controls] == [ + ("link", "Continue"), + ("button", "Back"), + ] + spec = ControlSpec("activatable", "Continue") + assert match_one(spec, screen).handle == "#a1" From c6d6cb1834af110503cf0b0b1ff7ba2b4bedff52 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:56:25 -0500 Subject: [PATCH 09/14] docs(flow): record gui.steps in CAPABILITIES, the changelog and the fail-closed list --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 7 +++++++ packages/flow/docs/FAIL_CLOSED.md | 2 ++ 4 files changed, 11 insertions(+) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index c41d3a6527..efadedeecc 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -179,6 +179,7 @@ improvising or retrying when something is off. | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 15 generic mutations against every registered `@verdict_site` and checks the verdict at three levels (refuted, not checked, held); and a CI ratchet that fails when the repository-wide count of a hand-written fold kind rises, including swallowed exceptions and "nothing else changed" tests over a possibly partial read | On main | Synthetic: the harness flags 14 fail-open bugs rebuilt from this repository's history (pinned pre-fix copies) plus one live connector site, and passes every fix; 8 registered sites (the hard-invariant layer, the version check, `verify-run`'s folds and the receipt's line judge and tally among them) and 2 owned; 12 of 12 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Steps drawn as links, tabs or menu items, and the commit point learned from the demonstration: a step's role (commit, navigate, in place) comes from the writes the backend counted, never its words; a commit holds only on exactly the demonstrated writes, and a backend that cannot count writes never attempts one | On main ([#2499](https://github.com/OpenAdaptAI/OpenAdapt/pull/2499)) | Synthetic: a web form, an EMR-like chart, a SaaS settings page (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.steps`, `packages/flow/tests/gui` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | 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. 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/llms-full.txt b/llms-full.txt index 175d7ad35c..504fccab0e 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -619,6 +619,7 @@ improvising or retrying when something is off. | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 15 generic mutations against every registered `@verdict_site` and checks the verdict at three levels (refuted, not checked, held); and a CI ratchet that fails when the repository-wide count of a hand-written fold kind rises, including swallowed exceptions and "nothing else changed" tests over a possibly partial read | On main | Synthetic: the harness flags 14 fail-open bugs rebuilt from this repository's history (pinned pre-fix copies) plus one live connector site, and passes every fix; 8 registered sites (the hard-invariant layer, the version check, `verify-run`'s folds and the receipt's line judge and tally among them) and 2 owned; 12 of 12 kernel mutants killed | [FAIL_CLOSED.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Steps drawn as links, tabs or menu items, and the commit point learned from the demonstration: a step's role (commit, navigate, in place) comes from the writes the backend counted, never its words; a commit holds only on exactly the demonstrated writes, and a backend that cannot count writes never attempts one | On main ([#2499](https://github.com/OpenAdaptAI/OpenAdapt/pull/2499)) | Synthetic: a web form, an EMR-like chart, a SaaS settings page (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.steps`, `packages/flow/tests/gui` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | | 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. 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 8253240692..9e11407f7d 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -19,6 +19,13 @@ ### Features +- 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 + commit holds only on exactly the demonstrated writes. `openadapt_flow.gui` + is a neutral view of a screen (role, name, state, containers) with adapters + for a browser page, an accessibility tree and a `form_tx` snapshot. + - One verdict kernel, `openadapt_flow.verdict`, for every check that turns evidence into held, refuted or not checked. It fixes the obligations from the plan first, settles results against them, and never passes an empty diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 236df580f5..fc9ec70c56 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -291,6 +291,8 @@ Done: - [x] `receipt_record._tally_lines` (C2 C3): fix: a line check nobody listed keeps the run from VERIFIED and counts as not checked. - [x] `tx/wire_tap.relay_redirect_location` (C6): registered after #2470. +- [x] `gui.steps.judge_step` (C3 C5): new. A commit holds only on exactly + the demonstrated writes; an unlisted step role is not checked. Next, most bug-prone first: From f72b015dcde4af136e13b97731a1c5b4cccbdfcf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:47:55 -0500 Subject: [PATCH 10/14] fix(flow): take no step on a backend that cannot count writes; refute an in-place step that moves the screen From Gemini's review of #2499. A navigation must be shown not to write, so without a write count no step is judged and none is clicked. An in-place step that moved the screen did something the demo did not. --- packages/flow/openadapt_flow/gui/steps.py | 19 ++++++++++++++----- .../flow/tests/failopen/sites/gui_steps.py | 3 ++- packages/flow/tests/gui/test_gui_steps.py | 19 ++++++++++++++----- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/packages/flow/openadapt_flow/gui/steps.py b/packages/flow/openadapt_flow/gui/steps.py index 71f94058ec..f669604865 100644 --- a/packages/flow/openadapt_flow/gui/steps.py +++ b/packages/flow/openadapt_flow/gui/steps.py @@ -199,7 +199,7 @@ def judge_step(ev: StepEvidence) -> Result: - ``commit``: exactly ``expected_writes`` new writes, on a complete read with no error shown. No write, or a different number, is refuted. - ``navigate``: the screen changed and nothing was written. - - ``in_place``: nothing was written. + - ``in_place``: nothing was written and the screen did not move. - ``unknown`` or any role nobody listed: not checked. A write count that is missing, negative or not a whole number is not @@ -242,6 +242,11 @@ def judge_step(ev: StepEvidence) -> Result: return Result.refuted(subject, obs, "the screen did not change") if ev.moved is not True: return Result.not_checked(subject, "the screen after the step was not read") + elif role is StepRole.IN_PLACE: + if ev.moved is True: + return Result.refuted(subject, obs, "an in-place step moved the screen") + if ev.moved is not False: + return Result.not_checked(subject, "the screen after the step was not read") if ev.after_complete is not True: return Result.not_checked(subject, "the screen after the step was read in part") return Result.held(subject, obs, f"{role.value} as demonstrated") @@ -272,8 +277,8 @@ def take_step( """Resolve ``spec`` on the live screen, click it, and judge it. Nothing is clicked when the control is missing or ambiguous, or when the - step is a commit and the backend cannot count writes (a commit there - could never be shown, so it is not attempted).""" + backend cannot count writes (no step could be judged there, so none is + attempted).""" subject = Subject(run_id=run_id, surface="gui", key=spec.step_id, field="step") before_screen = screen if screen is not None else actuator.observe() @@ -286,9 +291,13 @@ def take_step( Result.not_checked(subject, "the control is disabled"), False, ctrl ) w0 = actuator.write_count() - if spec.role is StepRole.COMMIT and w0 is None: + if w0 is None: + # Without a write count no step can be judged (a navigation must be + # shown not to write), so none is taken. return StepOutcome( - Result.not_checked(subject, "this backend cannot count writes; no commit"), + Result.not_checked( + subject, "this backend cannot count writes; no step is taken" + ), False, ctrl, ) diff --git a/packages/flow/tests/failopen/sites/gui_steps.py b/packages/flow/tests/failopen/sites/gui_steps.py index 902a7d1a04..e63047eab5 100644 --- a/packages/flow/tests/failopen/sites/gui_steps.py +++ b/packages/flow/tests/failopen/sites/gui_steps.py @@ -28,7 +28,7 @@ "after_complete", ), "navigate": ("role", "writes_before", "writes_after", "moved", "after_complete"), - "in_place": ("role", "writes_before", "writes_after", "after_complete"), + "in_place": ("role", "writes_before", "writes_after", "moved", "after_complete"), } @@ -97,6 +97,7 @@ def put(ev: dict[str, Any], value: Any) -> None: Seed(_ev("navigate", moved=False), False, "did not move"), Seed(_ev("commit", after_errors=("Card declined",)), False, "error shown"), Seed(_ev("unknown"), False, "the demo could not count writes"), + Seed(_ev("in_place", moved=True), False, "an in-place step moved"), ], fields=_fields(), values=tuple( diff --git a/packages/flow/tests/gui/test_gui_steps.py b/packages/flow/tests/gui/test_gui_steps.py index 06f52b05bf..3f731312bb 100644 --- a/packages/flow/tests/gui/test_gui_steps.py +++ b/packages/flow/tests/gui/test_gui_steps.py @@ -257,16 +257,18 @@ def test_grid_sheet_tab_navigates_and_save_menu_item_commits() -> None: assert replay.saved[-1]["Q2"] == [["Rent", ""]] -def test_a_backend_that_cannot_count_writes_never_attempts_a_commit() -> None: +def test_a_backend_that_cannot_count_writes_never_takes_a_step() -> None: grid = _grid() rec = Recorder(grid) + rec.click("tab:1") rec.click("tool:save") - (learned,) = learn_steps(rec.steps) + tab, save = learn_steps(rec.steps) blind = _grid() blind.count_writes = False - out = take_step(blind, learned.spec) - assert not out.clicked and out.result.status is Status.NOT_CHECKED - assert blind.saved == [] + for step in (save, tab): + out = take_step(blind, step.spec) + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert blind.saved == [] and blind.active == 0 rec2 = Recorder(blind) rec2.click("tool:save") (unknown,) = learn_steps(rec2.steps) @@ -276,6 +278,13 @@ def test_a_backend_that_cannot_count_writes_never_attempts_a_commit() -> None: # -- the verdict and the form_tx adapter ------------------------------------------------ +def test_an_in_place_step_that_moves_the_screen_is_refuted() -> None: + ev = StepEvidence("s", StepRole.IN_PLACE, 0, 2, 2, True, True) + assert judge_step(ev).status is Status.REFUTED + held = StepEvidence("s", StepRole.IN_PLACE, 0, 2, 2, False, True) + assert judge_step(held).status is Status.HELD + + def test_judge_step_needs_exact_whole_counts() -> None: base = dict( step_id="s", From 0158fe70d22399b84270ccdc4b2dc869105f65aa Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 10:44:47 -0500 Subject: [PATCH 11/14] fix(gui): count only 2xx/3xx same-origin write responses and refute 4xx/5xx/failed writes --- CAPABILITIES.md | 6 +- capabilities/CAPABILITIES.md.sha256 | 2 +- llms-full.txt | 34 +++++--- packages/flow/openadapt_flow/gui/dom.py | 73 +++++++++++++++-- packages/flow/openadapt_flow/gui/steps.py | 8 +- packages/flow/tests/gui/_apps.py | 8 +- packages/flow/tests/gui/test_gui_steps.py | 98 +++++++++++++++++++++++ 7 files changed, 206 insertions(+), 23 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 0694f95760..046a342325 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -346,6 +346,7 @@ improvising or retrying when something is off. | Score a candidate before it saves anything: `openadapt-flow readiness` imports 20 to 50 tasks a person did (the save from the browser recording's network capture, else a read-back through the verify config's reader, else refused), runs the candidate agent (`--agent-cmd`) or compiled program (`--program`) on each task in its own headless browser (DevTools on a pipe only, reached through a loopback relay that refuses any request without the run's random token; the page can reach only the app's origins) where the shadow hold refuses every non-GET request to the app origin (autosaves, drafts and locks included) after recording the write it would have made, and a browser-level hold hands every request of every other tab, popup, browser context and worker to the same hold (a write from one of them makes the case `NOT_CHECKED`, reason `extra_target`, and `scope_ok` false). It compares the write field by field with the person's save (identifiers such as `02134` compare as exact text; any extra held write fails the match; uncompared never counts as matched; a prefilled form or other contamination makes a case not comparable), and writes a one-page `scorecard.html` and an aggregates-only `scorecard.json` (matched N of M, risks, field errors, agent and human time, model cost and its source, estimated savings with its formula). Each candidate runs under the flight recorder's egress (`--egress scrubbed` by default, `blocked` or `unscrubbed`) with the OS egress block, and cost is metered by the proxy; a candidate that reports model calls the proxy didn't see is refused for that task. Each imported task names its target record in the candidate's inputs (`record_`). `--keep-session` carries a signed-in session across tasks. A card whose scope failed states what failed in place of the claim. What is checked: no non-GET request to the app origin left any tab, popup, browser context or worker except listed sign-in requests; not covered: GET requests with side effects, WebSocket writes, writes before attach | On main ([#2498](https://github.com/OpenAdaptAI/OpenAdapt/pull/2498)) | Synthetic (MockMed, 20 recorded tasks; scripted agent with 5 planted field errors and 2 wrong-record cases: precision and recall 1.0, 0 writes in the app's own store; an adversarial agent's six routes around the tab (popup form, `window.open`, `Target.createTarget`, a new browser context, a shared worker, a dedicated worker) land 0 writes in the store) | `openadapt-flow readiness`, [READINESS.md](packages/flow/docs/READINESS.md), [benchmark/readiness](packages/flow/benchmark/readiness/README.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Try `openadapt wrap` with one command: `uvx --python 3.12 'openadapt[wrap]@latest' wrap --example` (the `wrap` extra brings the agent SDK; the base launcher leaves it out) starts a bundled synthetic clinic app (MockMed) on 127.0.0.1, has OpenAdapt's built-in Claude agent save one note in a headless browser, reads the save back, compiles the run, runs a canary, and admits it with a throwaway key made in the example's own folder (the proposed checks are confirmed automatically, which only a synthetic app allows). Then a new note runs the compiled program over its emitted MCP server with no model calls, and it prints the app's record and the cost of both runs. It needs `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` with `--provider openai`, `--model` and reviewed `--price` values); the task is packaged data (`openadapt_flow/wrap/examples/`). Because the data is synthetic, screenshots go to the model unscrubbed under the recorded opt-out. Emitted MCP tools now run the program off the server's event loop, so a compiled browser program runs when called over MCP (it failed with Playwright's "Sync API inside the asyncio loop" error before) | In PR | Synthetic (the bundled app, headless Chromium and the real `build_agent` Claude loop with its token-count reservation and spend cap; CI uses a scripted model client in place of the Anthropic SDK). One real run (Claude Opus 5.5, macOS, before release): run 1 made 5 model calls for $0.15 and was admitted; run 2 made none and was read back `VERIFIED` ([benchmark/wrap_example](packages/flow/benchmark/wrap_example/real-run-2026-11-21.json)) | [WRAP.md](packages/flow/docs/WRAP.md), `openadapt_flow.wrap.example`, `openadapt_flow.compile_agent.run_compiled_tool`, `packages/flow/tests/e2e/test_wrap_example_e2e.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | @@ -378,8 +379,8 @@ improvising or retrying when something is off. | Each package installs on its own within a size budget, checked in CI (privacy without desktop, capture without plotting) | Released ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270), [#1271](https://github.com/OpenAdaptAI/OpenAdapt/pull/1271), [#1279](https://github.com/OpenAdaptAI/OpenAdapt/pull/1279)) | CI | `.github/workflows/packages.yml` | | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | @@ -494,6 +495,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index a121e3ae63..4d03e41523 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -e43b02968b96995aa15093365c5405a2ef95166f04506c3137b21ba63f3a6afb +f7fe14aa18e871fdb1b90196d60ad25b73fdf73cad14691031ab56d483843c48 diff --git a/llms-full.txt b/llms-full.txt index f4e616d698..72152c8c73 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -817,6 +817,7 @@ improvising or retrying when something is off. | Score a candidate before it saves anything: `openadapt-flow readiness` imports 20 to 50 tasks a person did (the save from the browser recording's network capture, else a read-back through the verify config's reader, else refused), runs the candidate agent (`--agent-cmd`) or compiled program (`--program`) on each task in its own headless browser (DevTools on a pipe only, reached through a loopback relay that refuses any request without the run's random token; the page can reach only the app's origins) where the shadow hold refuses every non-GET request to the app origin (autosaves, drafts and locks included) after recording the write it would have made, and a browser-level hold hands every request of every other tab, popup, browser context and worker to the same hold (a write from one of them makes the case `NOT_CHECKED`, reason `extra_target`, and `scope_ok` false). It compares the write field by field with the person's save (identifiers such as `02134` compare as exact text; any extra held write fails the match; uncompared never counts as matched; a prefilled form or other contamination makes a case not comparable), and writes a one-page `scorecard.html` and an aggregates-only `scorecard.json` (matched N of M, risks, field errors, agent and human time, model cost and its source, estimated savings with its formula). Each candidate runs under the flight recorder's egress (`--egress scrubbed` by default, `blocked` or `unscrubbed`) with the OS egress block, and cost is metered by the proxy; a candidate that reports model calls the proxy didn't see is refused for that task. Each imported task names its target record in the candidate's inputs (`record_`). `--keep-session` carries a signed-in session across tasks. A card whose scope failed states what failed in place of the claim. What is checked: no non-GET request to the app origin left any tab, popup, browser context or worker except listed sign-in requests; not covered: GET requests with side effects, WebSocket writes, writes before attach | On main ([#2498](https://github.com/OpenAdaptAI/OpenAdapt/pull/2498)) | Synthetic (MockMed, 20 recorded tasks; scripted agent with 5 planted field errors and 2 wrong-record cases: precision and recall 1.0, 0 writes in the app's own store; an adversarial agent's six routes around the tab (popup form, `window.open`, `Target.createTarget`, a new browser context, a shared worker, a dedicated worker) land 0 writes in the store) | `openadapt-flow readiness`, [READINESS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/READINESS.md), [benchmark/readiness](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/readiness/README.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Try `openadapt wrap` with one command: `uvx --python 3.12 'openadapt[wrap]@latest' wrap --example` (the `wrap` extra brings the agent SDK; the base launcher leaves it out) starts a bundled synthetic clinic app (MockMed) on 127.0.0.1, has OpenAdapt's built-in Claude agent save one note in a headless browser, reads the save back, compiles the run, runs a canary, and admits it with a throwaway key made in the example's own folder (the proposed checks are confirmed automatically, which only a synthetic app allows). Then a new note runs the compiled program over its emitted MCP server with no model calls, and it prints the app's record and the cost of both runs. It needs `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` with `--provider openai`, `--model` and reviewed `--price` values); the task is packaged data (`openadapt_flow/wrap/examples/`). Because the data is synthetic, screenshots go to the model unscrubbed under the recorded opt-out. Emitted MCP tools now run the program off the server's event loop, so a compiled browser program runs when called over MCP (it failed with Playwright's "Sync API inside the asyncio loop" error before) | In PR | Synthetic (the bundled app, headless Chromium and the real `build_agent` Claude loop with its token-count reservation and spend cap; CI uses a scripted model client in place of the Anthropic SDK). One real run (Claude Opus 5.5, macOS, before release): run 1 made 5 model calls for $0.15 and was admitted; run 2 made none and was read back `VERIFIED` ([benchmark/wrap_example](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_example/real-run-2026-11-21.json)) | [WRAP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP.md), `openadapt_flow.wrap.example`, `openadapt_flow.compile_agent.run_compiled_tool`, `packages/flow/tests/e2e/test_wrap_example_e2e.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | @@ -849,8 +850,8 @@ improvising or retrying when something is off. | Each package installs on its own within a size budget, checked in CI (privacy without desktop, capture without plotting) | Released ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270), [#1271](https://github.com/OpenAdaptAI/OpenAdapt/pull/1271), [#1279](https://github.com/OpenAdaptAI/OpenAdapt/pull/1279)) | CI | `.github/workflows/packages.yml` | | See a compiled program as a map (every step, exact edge, loop and stop rule, with each step's checks) and play a recorded run over it; one React package that Desktop, app.openadapt.ai and openadapt.ai share | On main ([packages/program-graph](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/program-graph/README.md)) | Real compiled OpenEMR referral program and a recorded scoreboard run, both on synthetic data | `@openadapt/program-graph`; `openadapt-flow visualize --format json` | | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | -| Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | -| Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Encrypt PHI at rest by default: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, desktop recordings once converted, and every run directory; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | +| Encryption at rest by default, through a key hierarchy (sealed-set v3): each recording, bundle and run has its own data key, wrapped with HPKE (P-256, HKDF-SHA256, AES-256-GCM) to a per-set bucket key, whose record is wrapped to the device runtime key (only while the set is written), the device viewer key, organization keys (P-256 or RSA-OAEP-3072, required in organization mode with a key archive, from a machine policy) and a solo recovery key; files are Tink AES-256-GCM-HKDF 1 MiB streams. The device key is a software P-256 key in the OS keychain (or a 0600 file with a warning): the Secure Enclave, TPM, Touch ID and Windows Hello providers are interfaces with test doubles, not built. `at-rest shred` authenticates the set's header, then destroys its tracked bucket-key copies, in the archive the set was written to (an archive counts only with its marker file), and the run's checkpoints, which are keyed from the run's own data key. Receipts stay plaintext, over the plaintext report digest. `OPENADAPT_ENCRYPT_AT_REST=0` or `--no-encrypt` turns it off with a one-line warning and a ledger line | On main ([#2423](https://github.com/OpenAdaptAI/OpenAdapt/pull/2423)) | Synthetic (hierarchy, fail-closed, org-mode, recovery, shred, unmounted and moved archive, whole-set substitution, backlog race and forged-header tests with test-double device keys and an injected keychain; payload checked against Tink); one headless MockMed quickstart with only ciphertext screenshots on disk | `openadapt-flow at-rest`; `openadapt_flow.key_hierarchy`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#key-hierarchy) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | @@ -965,6 +966,7 @@ A test fails when a command has no file or this list is out of date. **Run on premises:** +- `at-rest`: Encryption at rest: the device keys, policy and recipients by fingerprint, a solo recovery key, `restore` for a backup only the recovery code opens, and `shred`, which destroys an encrypted run's bucket key so nobody can open it. - `no-outbound` - `service` @@ -2426,6 +2428,14 @@ postconditions, model requests, effect queries, logs, and reports. Keep those observations inside the declared execution boundary and apply storage, retention, access, and egress controls there. +Encryption at rest is on by default: recordings, bundles and run +directories (screenshots, frames, typed values, reports) are ciphertext on +disk, each under its own data key, wrapped through a per-set bucket key to +this computer's device key and, in organization mode, the organization's key +([`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md)). It protects +files at rest, not a running session: anyone who can run commands as the +signed-in person can read them, as Flow does. + See [`SANITIZED_ARTIFACTS.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SANITIZED_ARTIFACTS.md) for the review and exact-hash workflow, [`PRIVACY.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/PRIVACY.md) for the field-level data map, and [`ENTERPRISE_ARCHITECTURE.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENTERPRISE_ARCHITECTURE.md) for component @@ -2450,13 +2460,19 @@ host hardening, storage encryption, backups, retention, access control, monitoring, effect-verifier integration, update validation, and disaster recovery. -The repository supplies integrity manifests, optional encryption at rest for -bundles, web recordings and the run directories of sealed bundles, destination -policy, local egress checks, and audit primitives. Encryption at rest does not -cover data in process memory, the target application's own storage, file names -and sizes, desktop recordings, or commands outside the list in -[`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md), which refuse sealed input; the key is a -passphrase in the environment, not a KMS. A content digest +The repository supplies integrity manifests, encryption at rest by default +for recordings, bundles and run directories, destination policy, local egress +checks, and audit primitives. Encryption at rest does not cover data in +process memory, the target application's own storage, file names and sizes, a +desktop recording's raw capture session while it records, cross-window +(`record --surface`) recordings, the receipt page, the logged artifacts in +[`phi_at_rest.md`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md), or commands outside its list, which refuse +sealed input. Without an organization policy only this computer's device key +(and a recovery key, if made) opens what it wrote. The device key is a +software key in the OS keychain (or a 0600 file where there is none) until the +Secure Enclave and TPM providers are built: code running as the signed-in +person can use it. Losing it loses the data unless an organization policy or a +recovery key exists. A content digest proves byte identity, not publisher identity. A local hash chain is tamper evident against ordinary changes, not tamper proof against an administrator who can rewrite it. Local approvals record provenance but are not enterprise-IdP diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py index 37310161c4..a76594f3af 100644 --- a/packages/flow/openadapt_flow/gui/dom.py +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -239,30 +239,89 @@ def screen_from_dom(raw: dict[str, Any]) -> Screen: _READ_ONLY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) +def _origin_of(url: str) -> str: + """Return normalized ``scheme://netloc`` for an HTTP(S) URL, or empty string.""" + from urllib.parse import urlsplit + + parts = urlsplit(url) + if parts.scheme not in ("http", "https") or not parts.netloc: + return "" + return f"{parts.scheme.lower()}://{parts.netloc.lower()}" + + class PageActuator: """An :class:`~openadapt_flow.gui.model.Actuator` over a Playwright page. ``write_get_paths`` are regular expressions, from the pack, for GET requests that change state on this app (a commit drawn as a plain link). + ``allowed_origins`` are extra origins (from the pack) whose write responses + count in addition to the page's own origin; third-party beacons to other + origins are ignored. """ - def __init__(self, page: Any, *, write_get_paths: Sequence[str] = ()) -> None: + def __init__( + self, + page: Any, + *, + write_get_paths: Sequence[str] = (), + allowed_origins: Sequence[str] = (), + ) -> None: self.page = page self._writes = 0 + self._write_errors: list[str] = [] self._get_writes = tuple(re.compile(p) for p in write_get_paths) - page.on("request", self._on_request) + self._allowed_origins = frozenset( + o for o in (_origin_of(raw) for raw in allowed_origins) if o + ) + page.on("response", self._on_response) + page.on("requestfailed", self._on_request_failed) - def _on_request(self, request: Any) -> None: + def _is_counted_write_request(self, request: Any) -> bool: + req_url = str(request.url) + req_origin = _origin_of(req_url) + page_origin = _origin_of(str(getattr(self.page, "url", "") or "")) + if not req_origin: + return False + if req_origin != page_origin and req_origin not in self._allowed_origins: + return False method = str(request.method).upper() if method not in _READ_ONLY_METHODS: - self._writes += 1 - return + return True if self._get_writes: from urllib.parse import urlsplit - path = urlsplit(str(request.url)).path + path = urlsplit(req_url).path if any(p.search(path) for p in self._get_writes): - self._writes += 1 + return True + return False + + def _on_response(self, response: Any) -> None: + request = response.request + if not self._is_counted_write_request(request): + return + status = int(response.status) + if 200 <= status < 400: + self._writes += 1 + elif status >= 400: + from urllib.parse import urlsplit + + method = str(request.method).upper() + path = urlsplit(str(request.url)).path or "/" + self._write_errors.append(f"{method} {path} returned HTTP {status}") + + def _on_request_failed(self, request: Any) -> None: + if not self._is_counted_write_request(request): + return + from urllib.parse import urlsplit + + method = str(request.method).upper() + path = urlsplit(str(request.url)).path or "/" + failure = getattr(request, "failure", None) or "request failed" + self._write_errors.append(f"{method} {path} failed: {failure}") + + def write_errors(self) -> tuple[str, ...]: + """Refuting HTTP 4xx/5xx or failed write-request errors observed so far.""" + return tuple(self._write_errors) def _settle(self) -> None: self.page.wait_for_load_state("load") diff --git a/packages/flow/openadapt_flow/gui/steps.py b/packages/flow/openadapt_flow/gui/steps.py index f669604865..4d686553a1 100644 --- a/packages/flow/openadapt_flow/gui/steps.py +++ b/packages/flow/openadapt_flow/gui/steps.py @@ -301,9 +301,12 @@ def take_step( False, ctrl, ) + err_fn = getattr(actuator, "write_errors", None) + err0 = len(err_fn()) if callable(err_fn) else 0 actuator.click(ctrl.handle) - w1 = actuator.write_count() after = actuator.observe() + w1 = actuator.write_count() + write_errors = tuple(err_fn()[err0:]) if callable(err_fn) else () ev = StepEvidence( step_id=spec.step_id, role=spec.role, @@ -313,7 +316,8 @@ def take_step( moved=screen_signature(after) != screen_signature(before_screen), after_complete=after.complete, after_errors=tuple(after.errors) - + tuple(c.error for c in after.controls if c.error), + + tuple(c.error for c in after.controls if c.error) + + write_errors, run_id=run_id, ) return StepOutcome(judge_step(ev), True, ctrl, after) diff --git a/packages/flow/tests/gui/_apps.py b/packages/flow/tests/gui/_apps.py index 997af6ec2d..cef7519d6f 100644 --- a/packages/flow/tests/gui/_apps.py +++ b/packages/flow/tests/gui/_apps.py @@ -76,7 +76,11 @@ def registration_app( post a draft (an app that changed); ``commit_posts`` is how many requests Register sends; ``error_after`` shows an alert after the commit.""" - draft = "fetch('/draft',{method:'POST',body:'{}'});" if next_writes else "" + draft = ( + "(function(){var x=new XMLHttpRequest();x.open('POST','/draft',false);x.send('{}');})();" + if next_writes + else "" + ) def contact(app: App, path: str, method: str, form: dict) -> tuple[int, str]: return 200, page( @@ -93,7 +97,7 @@ def contact(app: App, path: str, method: str, form: dict) -> tuple[int, str]: def ticket(app: App, path: str, method: str, form: dict) -> tuple[int, str]: sends = "".join( - "fetch('/register',{method:'POST',body:JSON.stringify(data())});" + "(function(){var x=new XMLHttpRequest();x.open('POST','/register',false);x.send(JSON.stringify(data()));})();" for _ in range(commit_posts - 1) ) return 200, page( diff --git a/packages/flow/tests/gui/test_gui_steps.py b/packages/flow/tests/gui/test_gui_steps.py index 3f731312bb..c3c5bd4b7d 100644 --- a/packages/flow/tests/gui/test_gui_steps.py +++ b/packages/flow/tests/gui/test_gui_steps.py @@ -330,3 +330,101 @@ def test_form_snapshot_links_become_link_controls() -> None: ] spec = ControlSpec("activatable", "Continue") assert match_one(spec, screen).handle == "#a1" + + +def test_commit_server_500_without_alert_is_refuted(page) -> None: + """A 500 response on a commit POST must refute even with no role=alert.""" + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + app2 = _apps.registration_app() + with _apps.serve(page, app2): + act = PageActuator(page) + page.goto(f"{app2.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + assert take_step(act, steps[0], run_id="r500").held + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + page.route( + f"{app2.origin}/register", + lambda route: route.fulfill( + status=500, + content_type="text/html", + body="

Internal Server Error

", + ), + ) + try: + out = take_step(act, steps[1], run_id="r500") + finally: + page.unroute(f"{app2.origin}/register") + assert out.clicked and out.result.status is Status.REFUTED + assert "HTTP 500" in out.result.reason + assert act.write_count() == 0 + assert not app2.state.get("records") + + +def test_commit_third_party_beacon_does_not_count_as_write_or_commit(page) -> None: + """A third-party beacon POST must neither satisfy a commit nor teach one.""" + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + + beacon_hits: list[str] = [] + page.route( + "http://analytics.test/collect", + lambda route: ( + beacon_hits.append(route.request.method), + route.fulfill( + status=200, + headers={"Access-Control-Allow-Origin": "*"}, + body="ok", + ), + ), + ) + try: + app2 = _apps.registration_app() + with _apps.serve(page, app2): + act = PageActuator(page) + page.goto(f"{app2.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + assert take_step(act, steps[0], run_id="rbeacon").held + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + # Replace submit with a third-party beacon that prevents the real POST. + page.evaluate( + """() => { + const form = document.querySelector('form'); + form.addEventListener('submit', (ev) => { + ev.preventDefault(); + fetch('http://analytics.test/collect', {method: 'POST', body: 'ping'}); + }); + }""" + ) + out = take_step(act, steps[1], run_id="rbeacon") + assert beacon_hits == ["POST"] + assert out.clicked and out.result.status is Status.REFUTED + assert act.write_count() == 0 + assert not app2.state.get("records") + + # Also verify learn_steps does not learn a third-party-only beacon as COMMIT. + app3 = _apps.registration_app() + with _apps.serve(page, app3): + act3 = PageActuator(page) + page.goto(f"{app3.origin}/ticket") + page.evaluate( + """() => { + const form = document.querySelector('form'); + form.addEventListener('submit', (ev) => { + ev.preventDefault(); + fetch('http://analytics.test/collect', {method: 'POST', body: 'demo'}); + }); + }""" + ) + rec = Recorder(act3) + rec.click(_handle(act3.observe(), "button", "Register")) + learned = learn_steps(rec.steps) + assert len(learned) == 1 + assert learned[0].role is not StepRole.COMMIT + assert act3.write_count() == 0 + finally: + page.unroute("http://analytics.test/collect") From 0ff9b4361e22e7732f6c6297858fe95d107ac5eb Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Mon, 23 Nov 2026 11:12:27 -0500 Subject: [PATCH 12/14] fix(gui): match each commit write's outcome to the demo A replay whose save answered 302 to a sign-in page was held, because any 2xx or 3xx counted as a successful write. PageActuator now records what each counted write returned ("2xx", or "3xx "), the Recorder keeps it per demonstrated step, StepSpec carries it, and judge_step refutes a commit whose outcomes differ from the demo's. A 3xx with no usable Location is a write error. A commit spec with no recorded outcomes, or a backend that does not report them, is not clicked. The page origin used to decide which writes are the page's own is now read when an action starts, not when a response arrives. Tests: demo 200 / replay 302 to sign-in, demo 302 to /done / replay 302 to /login (and to /done, held), an old commit spec without outcomes, and a fetch-then-navigate fixture that pins today's ERR_ABORTED refutation. The failopen site gains the outcome fields and three seeds. --- packages/flow/openadapt_flow/gui/dom.py | 69 ++++++++++++-- packages/flow/openadapt_flow/gui/model.py | 24 ++++- packages/flow/openadapt_flow/gui/steps.py | 95 +++++++++++++++++-- .../flow/tests/failopen/sites/gui_steps.py | 29 +++++- packages/flow/tests/gui/_apps.py | 44 +++++++-- packages/flow/tests/gui/_grid.py | 8 +- packages/flow/tests/gui/test_gui_steps.py | 76 +++++++++++++++ 7 files changed, 317 insertions(+), 28 deletions(-) diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py index a76594f3af..f19a7bd75a 100644 --- a/packages/flow/openadapt_flow/gui/dom.py +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -12,6 +12,18 @@ is a plain link). Nothing else counts, so a page that saves by some other route shows no write, and no write means no commit. +A write counts only when it answered 2xx or 3xx, and the actuator keeps what +each counted write returned (:meth:`PageActuator.write_outcomes`): ``"2xx"``, +or ``"3xx "`` with the redirect's ``Location`` path, so a replay that +is bounced to a sign-in page does not pass for one that saved. A 4xx or 5xx, +a 3xx with no ``Location``, and a request that failed are write errors. The +page's own origin is read when an action starts, not when a response comes. + +Known limit: a page that starts a ``fetch()`` write and then navigates away +aborts its own request (``net::ERR_ABORTED``). That shows as a write error, +so such a step is refuted on every run, failing closed, even when the +server got the write. + Handles are CSS paths (``#id`` when the id is unique, else ``nth-of-type`` steps), computed without touching the page. """ @@ -249,6 +261,17 @@ def _origin_of(url: str) -> str: return f"{parts.scheme.lower()}://{parts.netloc.lower()}" +def _location_key(request_url: str, target: str) -> str: + """A redirect target as the demo and a replay compare it: the path, + without a trailing slash, prefixed by the origin when it leaves the + request's origin. Query and fragment are dropped.""" + from urllib.parse import urlsplit + + path = urlsplit(target).path.rstrip("/") or "/" + origin = _origin_of(target) + return path if origin == _origin_of(request_url) else f"{origin}{path}" + + class PageActuator: """An :class:`~openadapt_flow.gui.model.Actuator` over a Playwright page. @@ -269,6 +292,8 @@ def __init__( self.page = page self._writes = 0 self._write_errors: list[str] = [] + self._outcomes: list[str] = [] + self._step_origin = "" self._get_writes = tuple(re.compile(p) for p in write_get_paths) self._allowed_origins = frozenset( o for o in (_origin_of(raw) for raw in allowed_origins) if o @@ -279,7 +304,7 @@ def __init__( def _is_counted_write_request(self, request: Any) -> bool: req_url = str(request.url) req_origin = _origin_of(req_url) - page_origin = _origin_of(str(getattr(self.page, "url", "") or "")) + page_origin = self._step_origin or self._page_origin() if not req_origin: return False if req_origin != page_origin and req_origin not in self._allowed_origins: @@ -295,18 +320,42 @@ def _is_counted_write_request(self, request: Any) -> bool: return True return False + def _page_origin(self) -> str: + return _origin_of(str(getattr(self.page, "url", "") or "")) + + def _start_action(self) -> None: + # The page's origin when the action starts: a response that arrives + # mid-navigation must not make the new page's origin "own". + self._step_origin = self._page_origin() + def _on_response(self, response: Any) -> None: + from urllib.parse import urljoin, urlsplit + request = response.request if not self._is_counted_write_request(request): return status = int(response.status) - if 200 <= status < 400: + method = str(request.method).upper() + req_url = str(request.url) + path = urlsplit(req_url).path or "/" + if 200 <= status < 300: + self._writes += 1 + self._outcomes.append("2xx") + elif 300 <= status < 400: + headers = getattr(response, "headers", None) or {} + location = next( + (str(v) for k, v in headers.items() if str(k).lower() == "location"), + "", + ).strip() + target = urljoin(req_url, location) if location else "" + if not _origin_of(target): + self._write_errors.append( + f"{method} {path} returned HTTP {status} with no usable Location" + ) + return self._writes += 1 + self._outcomes.append(f"3xx {_location_key(req_url, target)}") elif status >= 400: - from urllib.parse import urlsplit - - method = str(request.method).upper() - path = urlsplit(str(request.url)).path or "/" self._write_errors.append(f"{method} {path} returned HTTP {status}") def _on_request_failed(self, request: Any) -> None: @@ -319,6 +368,11 @@ def _on_request_failed(self, request: Any) -> None: failure = getattr(request, "failure", None) or "request failed" self._write_errors.append(f"{method} {path} failed: {failure}") + def write_outcomes(self) -> tuple[str, ...]: + """What each counted write returned, in arrival order: ``"2xx"`` or + ``"3xx "``.""" + return tuple(self._outcomes) + def write_errors(self) -> tuple[str, ...]: """Refuting HTTP 4xx/5xx or failed write-request errors observed so far.""" return tuple(self._write_errors) @@ -344,6 +398,7 @@ def observe(self) -> Screen: raise AssertionError("unreachable") def click(self, handle: str) -> None: + self._start_action() self.page.locator(handle).click() # A click may start a navigation or a request a moment later; give # it time to start before waiting for the page to settle. @@ -351,11 +406,13 @@ def click(self, handle: str) -> None: self._settle() def set_text(self, handle: str, value: str) -> None: + self._start_action() self.page.locator(handle).fill(value) self.page.locator(handle).dispatch_event("change") self._settle() def set_checked(self, handle: str, checked: bool) -> None: + self._start_action() self.page.locator(handle).set_checked(checked) self._settle() diff --git a/packages/flow/openadapt_flow/gui/model.py b/packages/flow/openadapt_flow/gui/model.py index a7f7786438..af6b7974b8 100644 --- a/packages/flow/openadapt_flow/gui/model.py +++ b/packages/flow/openadapt_flow/gui/model.py @@ -48,6 +48,7 @@ "norm", "screen_signature", "spec_for", + "write_outcomes_of", ] #: The roles a backend maps its controls to. Anything else is ``other``. @@ -308,7 +309,8 @@ class DemoStep: ``target`` is the control as seen in ``before``. ``writes`` is how many writes the backend counted between ``before`` and ``after`` (requests that change state, a file save, a cell committed), or None when it could not - count them.""" + count them. ``write_outcomes`` is what each of those writes returned + (``"2xx"``, ``"3xx /done"``), or None when the backend does not say.""" action: ActionKind target: Control @@ -316,6 +318,7 @@ class DemoStep: after: Screen writes: Optional[int] value: str = "" + write_outcomes: Optional[tuple[str, ...]] = None @runtime_checkable @@ -337,6 +340,14 @@ def write_count(self) -> Optional[int]: ... +def write_outcomes_of(actuator: object) -> Optional[tuple[str, ...]]: + """What each write so far returned, from a backend's optional + ``write_outcomes()``, or None when it does not report them.""" + fn = getattr(actuator, "write_outcomes", None) + got = fn() if callable(fn) else None + return tuple(got) if isinstance(got, (tuple, list)) else None + + @dataclass class Recorder: """Wrap an :class:`Actuator` and keep every action as a :class:`DemoStep`. @@ -357,12 +368,19 @@ def _do( target = before.control(handle) if target is None: raise MissingControl(handle) + o0 = write_outcomes_of(self.actuator) w0 = self.actuator.write_count() run() - w1 = self.actuator.write_count() after = self.actuator.observe() + # Read after the screen settles, as a run does, so a late write is + # counted in the demo too. + w1 = self.actuator.write_count() writes = None if w0 is None or w1 is None else w1 - w0 - self.steps.append(DemoStep(action, target, before, after, writes, value)) + o1 = write_outcomes_of(self.actuator) + outcomes = None if o0 is None or o1 is None else o1[len(o0) :] + self.steps.append( + DemoStep(action, target, before, after, writes, value, outcomes) + ) def click(self, handle: str) -> None: self._do("click", handle, lambda: self.actuator.click(handle)) diff --git a/packages/flow/openadapt_flow/gui/steps.py b/packages/flow/openadapt_flow/gui/steps.py index 4d686553a1..c5184a02fb 100644 --- a/packages/flow/openadapt_flow/gui/steps.py +++ b/packages/flow/openadapt_flow/gui/steps.py @@ -18,10 +18,14 @@ and asks :func:`judge_step` whether it did what the demonstration showed. :func:`judge_step` is a verdict site. A commit step holds only when the -backend counted exactly the writes the demonstration made. A backend that -cannot count writes never shows a commit, so a commit through a plain link -that sends nothing the backend counts stays unproven, as it should: the run -has no evidence the record was saved. A navigation step that wrote, or that +backend counted exactly the writes the demonstration made, and each returned +what the demonstrated one did: the same status class and, for a redirect, +the same ``Location`` path. A save bounced to a sign-in page is a 302 like a +save that went to its confirmation page; only the path tells them apart. A +commit spec with no recorded outcomes (an older pack) is never clicked. A +backend that cannot count writes never shows a commit, so a commit through a +plain link that sends nothing the backend counts stays unproven, as it +should: the run has no evidence the record was saved. A navigation step that wrote, or that left the screen as it was, is refuted. """ @@ -42,6 +46,7 @@ match_one, screen_signature, spec_for, + write_outcomes_of, ) from openadapt_flow.verdict import Observed, Result, Status, Subject from openadapt_flow.verdict_sites import verdict_site @@ -71,12 +76,16 @@ class StepSpec: """Pack data for one step: which control, and what it did in the demo. ``writes`` is the number of writes the demonstration counted for it: at - least 1 for a commit, 0 otherwise.""" + least 1 for a commit, 0 otherwise. ``outcomes`` is what each of a + commit's writes returned in the demo, sorted (``"2xx"``, + ``"3xx /done"``); None on a spec learned before outcomes were recorded, + and such a commit is not taken.""" step_id: str control: ControlSpec role: StepRole writes: int = 0 + outcomes: Optional[tuple[str, ...]] = None def __post_init__(self) -> None: if not isinstance(self.role, StepRole): @@ -85,6 +94,10 @@ def __post_init__(self) -> None: raise ValueError("a commit step wrote at least once in the demo") if self.role is not StepRole.COMMIT and self.writes != 0: raise ValueError("only a commit step writes") + if self.outcomes is not None and ( + self.role is not StepRole.COMMIT or len(self.outcomes) != self.writes + ): + raise ValueError("a commit records one outcome per demonstrated write") @dataclass(frozen=True) @@ -149,13 +162,28 @@ def learn_steps(demo: Sequence[DemoStep]) -> tuple[LearnedStep, ...]: ) continue writes = int(step.writes or 0) if role is StepRole.COMMIT else 0 + outcomes = None + if role is StepRole.COMMIT: + outcomes = _outcomes(step.write_outcomes) + if outcomes is None or len(outcomes) != writes: + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + None, + "the backend did not report what this commit's writes returned", + ) + ) + continue out.append( LearnedStep( index, step.target, role, step.writes, - StepSpec(f"step-{index}", spec, role, writes), + StepSpec(f"step-{index}", spec, role, writes, outcomes), ) ) return tuple(out) @@ -184,6 +212,9 @@ class StepEvidence: after_complete: object after_errors: tuple[str, ...] = () run_id: str = "" + #: What the demo's writes returned, and what this step's writes did. + expected_outcomes: object = None + outcomes: object = None def _count(value: object) -> Optional[int]: @@ -192,12 +223,24 @@ def _count(value: object) -> Optional[int]: return value +def _outcomes(value: object) -> Optional[tuple[str, ...]]: + """``value`` as a sorted tuple of non-empty strings, else None.""" + if not isinstance(value, (tuple, list)): + return None + if not all(isinstance(v, str) and v for v in value): + return None + return tuple(sorted(value)) + + @verdict_site("gui.steps.judge_step", classes="C3 C5") def judge_step(ev: StepEvidence) -> Result: """Did the step do what the demonstration showed? - ``commit``: exactly ``expected_writes`` new writes, on a complete read - with no error shown. No write, or a different number, is refuted. + with no error shown, each returning what the demo's did (status class, + and the ``Location`` path of a redirect). No write, a different + number, or a different outcome is refuted; outcomes missing on either + side are not checked. - ``navigate``: the screen changed and nothing was written. - ``in_place``: nothing was written and the screen did not move. - ``unknown`` or any role nobody listed: not checked. @@ -235,6 +278,22 @@ def judge_step(ev: StepEvidence) -> Result: obs, f"the commit step wrote {delta} times; the demo wrote {want}", ) + want_out, got_out = _outcomes(ev.expected_outcomes), _outcomes(ev.outcomes) + if want_out is None or len(want_out) != want: + return Result.not_checked( + subject, "the demo did not record what its writes returned" + ) + if got_out is None or len(got_out) != delta: + return Result.not_checked( + subject, "the backend did not report what the writes returned" + ) + if got_out != want_out: + return Result.refuted( + subject, + obs, + f"the commit's writes returned {', '.join(got_out)}; " + f"the demo's returned {', '.join(want_out)}", + ) elif delta: return Result.refuted(subject, obs, f"a {role.value} step wrote {delta} times") elif role is StepRole.NAVIGATE: @@ -276,9 +335,10 @@ def take_step( ) -> StepOutcome: """Resolve ``spec`` on the live screen, click it, and judge it. - Nothing is clicked when the control is missing or ambiguous, or when the + Nothing is clicked when the control is missing or ambiguous, when the backend cannot count writes (no step could be judged there, so none is - attempted).""" + attempted), or for a commit when the spec or the backend has no record of + what the writes returned.""" subject = Subject(run_id=run_id, surface="gui", key=spec.step_id, field="step") before_screen = screen if screen is not None else actuator.observe() @@ -301,12 +361,27 @@ def take_step( False, ctrl, ) + o0 = write_outcomes_of(actuator) + if spec.role is StepRole.COMMIT and (spec.outcomes is None or o0 is None): + # Without the demo's outcomes, or a backend that reports them, a + # commit bounced to a sign-in page looks like one that saved. + return StepOutcome( + Result.not_checked( + subject, + "the spec or the backend has no record of what the commit's " + "writes returned; the commit is not taken", + ), + False, + ctrl, + ) err_fn = getattr(actuator, "write_errors", None) err0 = len(err_fn()) if callable(err_fn) else 0 actuator.click(ctrl.handle) after = actuator.observe() w1 = actuator.write_count() write_errors = tuple(err_fn()[err0:]) if callable(err_fn) else () + o1 = write_outcomes_of(actuator) + outcomes = None if o0 is None or o1 is None else o1[len(o0) :] ev = StepEvidence( step_id=spec.step_id, role=spec.role, @@ -319,5 +394,7 @@ def take_step( + tuple(c.error for c in after.controls if c.error) + write_errors, run_id=run_id, + expected_outcomes=spec.outcomes if spec.role is StepRole.COMMIT else None, + outcomes=outcomes, ) return StepOutcome(judge_step(ev), True, ctrl, after) diff --git a/packages/flow/tests/failopen/sites/gui_steps.py b/packages/flow/tests/failopen/sites/gui_steps.py index e63047eab5..68fcdb14ee 100644 --- a/packages/flow/tests/failopen/sites/gui_steps.py +++ b/packages/flow/tests/failopen/sites/gui_steps.py @@ -1,7 +1,9 @@ """gui.steps.judge_step (C3 C5): did a step (a link, a tab, a button) do what the demonstration showed? -A commit holds only on exactly the demonstrated number of writes; a +A commit holds only on exactly the demonstrated number of writes, each +returning what the demonstrated one did (a 302 to a sign-in page is not the +302 to the confirmation page the demo saw); a navigation only when the screen moved and nothing was written. Write counts that are not whole numbers, and roles nobody listed, are not checked. @@ -26,6 +28,8 @@ "writes_before", "writes_after", "after_complete", + "expected_outcomes", + "outcomes", ), "navigate": ("role", "writes_before", "writes_after", "moved", "after_complete"), "in_place": ("role", "writes_before", "writes_after", "moved", "after_complete"), @@ -42,6 +46,8 @@ def _ev(role: str, **over: Any) -> dict[str, Any]: "moved": role == "navigate", "after_complete": True, "after_errors": (), + "expected_outcomes": ("2xx",) if role == "commit" else None, + "outcomes": ("2xx",) if role == "commit" else None, } return {**base, **over} @@ -93,6 +99,25 @@ def put(ev: dict[str, Any], value: Any) -> None: Seed(_ev("in_place"), True, "nothing written"), Seed(_ev("commit", writes_after=3), False, "a commit that wrote nothing"), Seed(_ev("commit", writes_after=5), False, "two writes for one"), + Seed( + _ev("commit", outcomes=("3xx /login",)), + False, + "a redirect to sign-in where the demo saved", + ), + Seed( + _ev( + "commit", + expected_outcomes=("3xx /done",), + outcomes=("3xx /login",), + ), + False, + "a redirect elsewhere than the demo's", + ), + Seed( + _ev("commit", expected_outcomes=None), + False, + "a spec with no recorded outcomes", + ), Seed(_ev("navigate", writes_after=4), False, "a navigation that wrote"), Seed(_ev("navigate", moved=False), False, "did not move"), Seed(_ev("commit", after_errors=("Card declined",)), False, "error shown"), @@ -109,6 +134,8 @@ def put(ev: dict[str, Any], value: Any) -> None: "writes_after", "moved", "after_complete", + "expected_outcomes", + "outcomes", ) ), partial=lambda ev: [("after_complete", {**ev, "after_complete": False})], diff --git a/packages/flow/tests/gui/_apps.py b/packages/flow/tests/gui/_apps.py index cef7519d6f..b373fb4b44 100644 --- a/packages/flow/tests/gui/_apps.py +++ b/packages/flow/tests/gui/_apps.py @@ -69,18 +69,33 @@ def page(title: str, body: str) -> str: def registration_app( - *, next_writes: bool = False, commit_posts: int = 1, error_after: bool = False + *, + next_writes: bool = False, + commit_posts: int = 1, + error_after: bool = False, + fetch_writes: bool = False, + redirect: str = "", ) -> App: """Contact details, then a ticket, then Register. "Continue" is a link that keeps the values in session storage. ``next_writes`` makes the link also post a draft (an app that changed); ``commit_posts`` is how many requests - Register sends; ``error_after`` shows an alert after the commit.""" + Register sends; ``error_after`` shows an alert after the commit. + + The extra writes are synchronous XHR, which finish before the page + navigates; ``fetch_writes`` sends them with ``fetch()`` instead, which the + navigation aborts. ``redirect="/done"`` saves and answers 302 to the + confirmation page; ``redirect="/login"`` saves nothing and answers 302 to + a plain sign-in page (an expired session), with no alert.""" + + def _post(path: str, body: str) -> str: + if fetch_writes: + return f"fetch('{path}',{{method:'POST',body:{body}}});" + return ( + "(function(){var x=new XMLHttpRequest();" + f"x.open('POST','{path}',false);x.send({body});}})();" + ) - draft = ( - "(function(){var x=new XMLHttpRequest();x.open('POST','/draft',false);x.send('{}');})();" - if next_writes - else "" - ) + draft = _post("/draft", "'{}'") if next_writes else "" def contact(app: App, path: str, method: str, form: dict) -> tuple[int, str]: return 200, page( @@ -97,7 +112,7 @@ def contact(app: App, path: str, method: str, form: dict) -> tuple[int, str]: def ticket(app: App, path: str, method: str, form: dict) -> tuple[int, str]: sends = "".join( - "(function(){var x=new XMLHttpRequest();x.open('POST','/register',false);x.send(JSON.stringify(data()));})();" + _post("/register", "JSON.stringify(data())") for _ in range(commit_posts - 1) ) return 200, page( @@ -116,11 +131,23 @@ def ticket(app: App, path: str, method: str, form: dict) -> tuple[int, str]: ) def register(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + if redirect == "/login": + return 302, "/login" app.state.setdefault("records", []).append( {k: v[0] for k, v in form.items() if v} ) + if redirect: + return 302, redirect return done(app, path, method, form) + def login(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page( + "Sign in", + """

Sign in

Your session expired.

+ +
""", + ) + def done(app: App, path: str, method: str, form: dict) -> tuple[int, str]: alert = '

Payment could not be taken

' if error_after else "" return 200, page("Done", f"

Registration received

{alert}
") @@ -135,6 +162,7 @@ def draft_ok(app: App, path: str, method: str, form: dict) -> tuple[int, str]: ("GET", "/ticket"): ticket, ("POST", "/register"): register, ("GET", "/done"): done, + ("GET", "/login"): login, ("POST", "/draft"): draft_ok, }, ) diff --git a/packages/flow/tests/gui/_grid.py b/packages/flow/tests/gui/_grid.py index 0d13e96420..89fba85bea 100644 --- a/packages/flow/tests/gui/_grid.py +++ b/packages/flow/tests/gui/_grid.py @@ -4,7 +4,8 @@ and cells, a toolbar, an optional dialog) and reads it through :func:`openadapt_flow.gui.adapters.screen_from_tree`, the path a desktop backend would use. Writes are counted when the workbook is saved, so the -grid can show a commit; ``count_writes=False`` makes a backend that cannot. +grid can show a commit, and each save reports the outcome ``"saved"``; +``count_writes=False`` makes a backend that cannot. """ from __future__ import annotations @@ -34,6 +35,7 @@ class GridApp: dialog: Optional[dict[str, Any]] = None checks: dict[str, bool] = field(default_factory=dict) _writes: int = 0 + _outcomes: list[str] = field(default_factory=list) # -- the tree --------------------------------------------------------------- @@ -110,6 +112,7 @@ def click(self, handle: str) -> None: elif handle == "tool:save": self.saved.append({s.name: [list(r) for r in s.rows] for s in self.sheets}) self._writes += 1 + self._outcomes.append("saved") elif handle == "tool:insert": sheet = self.sheets[self.active] sheet.rows.append([""] * len(sheet.columns)) @@ -141,3 +144,6 @@ def set_checked(self, handle: str, checked: bool) -> None: def write_count(self) -> Optional[int]: return self._writes if self.count_writes else None + + def write_outcomes(self) -> Optional[tuple[str, ...]]: + return tuple(self._outcomes) if self.count_writes else None diff --git a/packages/flow/tests/gui/test_gui_steps.py b/packages/flow/tests/gui/test_gui_steps.py index c3c5bd4b7d..f0a8d5a60d 100644 --- a/packages/flow/tests/gui/test_gui_steps.py +++ b/packages/flow/tests/gui/test_gui_steps.py @@ -126,6 +126,74 @@ def test_a_commit_that_differs_from_the_demo_is_refuted(page, variant, reason) - assert reason in out.result.reason +def test_fetch_then_navigate_is_refuted_as_aborted(page) -> None: + """Pins a known limit: a link that fires ``fetch()`` and then navigates + aborts its own request, so the step is refuted for ERR_ABORTED (failing + closed) rather than for the write it started.""" + with _apps.serve(page, _apps.registration_app()) as app: + nxt = learn_steps(_record_registration(page, app))[0].spec + changed = _apps.registration_app(next_writes=True, fetch_writes=True) + with _apps.serve(page, changed): + act = PageActuator(page) + page.goto(f"{changed.origin}/contact") + out = take_step(act, nxt) + assert out.clicked and out.result.status is Status.REFUTED + assert "ERR_ABORTED" in out.result.reason + + +def _replay_commit(page, steps, app, run_id: str): + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + assert take_step(act, steps[0], run_id=run_id).held + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + return take_step(act, steps[1], run_id=run_id) + + +def test_a_commit_bounced_to_sign_in_is_not_held(page) -> None: + """Demo POST answers 200; replay answers 302 to a plain sign-in page with + no alert and saves nothing. The redirect is not the demo's outcome.""" + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("2xx",) + app2 = _apps.registration_app(redirect="/login") + out = _replay_commit(page, steps, app2, "r302") + assert out.clicked and out.result.status is not Status.HELD + assert out.result.status is Status.REFUTED, out.result.reason + assert "3xx /login" in out.result.reason + assert not app2.state.get("records") + + +def test_a_redirect_to_another_path_than_the_demo_is_not_held(page) -> None: + """Demo POST answers 302 to /done; replay answers 302 to /login.""" + with _apps.serve(page, _apps.registration_app(redirect="/done")) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("3xx /done",) + app2 = _apps.registration_app(redirect="/login") + out = _replay_commit(page, steps, app2, "r302b") + assert out.clicked and out.result.status is Status.REFUTED, out.result.reason + assert not app2.state.get("records") + app3 = _apps.registration_app(redirect="/done") + out = _replay_commit(page, steps, app3, "r302c") + assert out.held, out.result.reason + assert app3.state["records"] == [ + {"name": "Bo Sample", "email": "bo@example.test", "ticket": "vip"} + ] + + +def test_a_commit_spec_without_recorded_outcomes_is_never_clicked(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + old = StepSpec(steps[1].step_id, steps[1].control, StepRole.COMMIT, 1) + app2 = _apps.registration_app() + out = _replay_commit(page, [steps[0], old], app2, "rold") + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert not app2.state.get("records") + + def test_a_missing_renamed_or_doubled_link_is_never_clicked(page) -> None: spec = StepSpec("next", ControlSpec("link", "Continue"), StepRole.NAVIGATE) app = _apps.registration_app() @@ -294,9 +362,17 @@ def test_judge_step_needs_exact_whole_counts() -> None: writes_after=4, moved=True, after_complete=True, + expected_outcomes=("2xx",), + outcomes=("2xx",), ) assert judge_step(StepEvidence(**base)).status is Status.HELD for change in ( + {"outcomes": ("3xx /login",)}, + {"outcomes": None}, + {"outcomes": "2xx"}, + {"outcomes": ("2xx", "2xx")}, + {"expected_outcomes": None}, + {"expected_outcomes": ()}, {"writes_after": "4"}, {"writes_after": True}, {"writes_before": None}, From a1e1d8b248c5216e521399aa3eceb46bf09d2241 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Mon, 23 Nov 2026 12:16:13 -0500 Subject: [PATCH 13/14] fix(gui): key redirects by path and query, with minted ids replaced A save answered 302 to /register?status=session-expired was held when the demo's went to /register?status=saved, because the redirect key was the path alone. The key now keeps the query: the sorted key=value pairs, decoded and re-quoted, dropping only the fragment, so a same-path redirect with another query is refuted. A post-redirect-get to the record just created (/records/101 in the demo, /records/102 on replay) was refuted on every run. An id the server mints is now replaced by {id} before comparing: a path segment that is all digits, a UUID or 16+ hex characters, and a query value that is a UUID or 16+ hex characters. Words are never replaced. An all-digit query value is kept as it is, because a number in a query is as often a result code (?saved=1 vs ?saved=0) as an id; ?id=101 vs ?id=102 fails closed, and the limit is documented. A redirect outcome is now "redirect ". An outcome in the old "3xx " form is not compared: take_step does not click such a commit, judge_step gives not_checked, and learn_steps does not make a spec from it. PageActuator clears the action's origin once observe() has read the settled page, so a later response is judged against the page as it is. Tests: same path with another query (refuted, and held when it matches), a post-redirect-get to the new id (held, record saved), a redirect to sign-in where the demo went to a record (refuted), an old path-only spec (not clicked), browser-free location_key tables, the origin reset with a fake page, and three failopen seeds. --- packages/flow/openadapt_flow/gui/dom.py | 112 ++++++++-- packages/flow/openadapt_flow/gui/model.py | 2 +- packages/flow/openadapt_flow/gui/steps.py | 50 +++-- .../flow/tests/failopen/sites/gui_steps.py | 36 +++- packages/flow/tests/gui/_apps.py | 26 ++- packages/flow/tests/gui/test_gui_steps.py | 204 +++++++++++++++++- 6 files changed, 382 insertions(+), 48 deletions(-) diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py index f19a7bd75a..27c30b52b0 100644 --- a/packages/flow/openadapt_flow/gui/dom.py +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -14,15 +14,39 @@ A write counts only when it answered 2xx or 3xx, and the actuator keeps what each counted write returned (:meth:`PageActuator.write_outcomes`): ``"2xx"``, -or ``"3xx "`` with the redirect's ``Location`` path, so a replay that -is bounced to a sign-in page does not pass for one that saved. A 4xx or 5xx, -a 3xx with no ``Location``, and a request that failed are write errors. The -page's own origin is read when an action starts, not when a response comes. - -Known limit: a page that starts a ``fetch()`` write and then navigates away -aborts its own request (``net::ERR_ABORTED``). That shows as a write error, -so such a step is refuted on every run, failing closed, even when the -server got the write. +or ``"redirect "`` for a 3xx, so a replay that is bounced to a sign-in +page does not pass for one that saved. A 4xx or 5xx, a 3xx with no +``Location``, and a request that failed are write errors. The page's own +origin is read when an action starts and cleared when :meth:`PageActuator.observe` +has read the settled page, so a later response is not judged against it. + +The redirect key (:func:`location_key`) is the ``Location`` path, without a +trailing slash, then ``?`` and the query's ``key=value`` pairs, decoded, +re-quoted and sorted (a blank value kept, a repeated key kept once per +value). Only the fragment is dropped, so ``/register?status=saved`` and +``/register?status=session-expired`` differ, as do ``?page=done`` and +``?page=login``. A target on another origin than the request's is prefixed +with that origin. An id the server mints is replaced by ``{id}`` before the +two are compared: a path segment that is all digits, a UUID, or 16 or more +hex characters, and a query value that is a UUID or 16 or more hex +characters. So a post-redirect-get to the new record (``/records/101`` in +the demo, ``/records/102`` on replay) matches, and ``/records/{id}`` still +differs from ``/login``. Words are never replaced. + +An outcome learned before this format (``"3xx "``, path only) is not +compared: :func:`~openadapt_flow.gui.steps.take_step` does not click such a +commit, and :func:`~openadapt_flow.gui.steps.judge_step` does not check it. + +Known limits: + +- A query value that is all digits is kept as it is, because a number in a + query is as often a result code (``?saved=1`` vs ``?saved=0``) as a + record id. A redirect to ``?id=101`` in the demo and ``?id=102`` on replay + is refuted on every run, failing closed. +- A page that starts a ``fetch()`` write and then navigates away aborts its + own request (``net::ERR_ABORTED``). That shows as a write error, so such a + step is refuted on every run, failing closed, even when the server got the + write. Handles are CSS paths (``#id`` when the id is unique, else ``nth-of-type`` steps), computed without touching the page. @@ -35,7 +59,7 @@ from openadapt_flow.gui.model import ROLES, Container, Control, Dialog, Screen -__all__ = ["OBSERVE_JS", "PageActuator", "screen_from_dom"] +__all__ = ["OBSERVE_JS", "REDIRECT", "PageActuator", "location_key", "screen_from_dom"] #: Cap on the page text kept; a longer page is a partial read. TEXT_CAP = 20000 @@ -261,15 +285,57 @@ def _origin_of(url: str) -> str: return f"{parts.scheme.lower()}://{parts.netloc.lower()}" -def _location_key(request_url: str, target: str) -> str: - """A redirect target as the demo and a replay compare it: the path, - without a trailing slash, prefixed by the origin when it leaves the - request's origin. Query and fragment are dropped.""" - from urllib.parse import urlsplit +#: The prefix of a redirect outcome: ``"redirect "``. +REDIRECT = "redirect " + +#: What an id the server mints is replaced by in a redirect key. +ID_PLACEHOLDER = "{id}" + +_UUID = re.compile( + r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" +) +_LONG_HEX = re.compile(r"[0-9a-fA-F]{16,}") +_DIGITS = re.compile(r"[0-9]+") + + +def _minted(value: str, *, digits: bool) -> bool: + """Whether a whole, decoded path segment or query value is an id.""" + if _UUID.fullmatch(value) or _LONG_HEX.fullmatch(value): + return True + return digits and _DIGITS.fullmatch(value) is not None + - path = urlsplit(target).path.rstrip("/") or "/" +def _part(value: str, *, digits: bool) -> str: + from urllib.parse import quote + + return ID_PLACEHOLDER if _minted(value, digits=digits) else quote(value, safe="") + + +def location_key(request_url: str, target: str) -> str: + """A redirect target as the demo and a replay compare it. + + The path, without a trailing slash, each segment decoded and re-quoted, + and an id segment (all digits, a UUID, 16+ hex) replaced by ``{id}``; + then ``?`` and the sorted ``key=value`` query pairs, decoded and + re-quoted, with a UUID or 16+ hex value replaced by ``{id}``. The + fragment is dropped. A target on another origin than the request's is + prefixed with that origin.""" + from urllib.parse import parse_qsl, quote, unquote, urlsplit + + parts = urlsplit(target) + segments = [ + _part(unquote(seg), digits=True) if seg else "" + for seg in parts.path.rstrip("/").split("/") + ] + path = "/".join(segments) or "/" + pairs = sorted( + (quote(k, safe=""), _part(v, digits=False)) + for k, v in parse_qsl(parts.query, keep_blank_values=True) + ) + query = "&".join(f"{k}={v}" for k, v in pairs) + key = f"{path}?{query}" if query else path origin = _origin_of(target) - return path if origin == _origin_of(request_url) else f"{origin}{path}" + return key if origin == _origin_of(request_url) else f"{origin}{key}" class PageActuator: @@ -354,7 +420,7 @@ def _on_response(self, response: Any) -> None: ) return self._writes += 1 - self._outcomes.append(f"3xx {_location_key(req_url, target)}") + self._outcomes.append(REDIRECT + location_key(req_url, target)) elif status >= 400: self._write_errors.append(f"{method} {path} returned HTTP {status}") @@ -370,7 +436,7 @@ def _on_request_failed(self, request: Any) -> None: def write_outcomes(self) -> tuple[str, ...]: """What each counted write returned, in arrival order: ``"2xx"`` or - ``"3xx "``.""" + ``"redirect "`` (see :func:`location_key`).""" return tuple(self._outcomes) def write_errors(self) -> tuple[str, ...]: @@ -390,11 +456,17 @@ def observe(self) -> Screen: for attempt in range(3): self._settle() try: - return screen_from_dom(self.page.evaluate(OBSERVE_JS, TEXT_CAP)) + screen = screen_from_dom(self.page.evaluate(OBSERVE_JS, TEXT_CAP)) except PlaywrightError as exc: if attempt == 2 or "context was destroyed" not in str(exc): raise self.page.wait_for_timeout(100) + continue + # The action's page is read; a response from here on is judged + # against the page as it is then, not the origin the action + # started on. + self._step_origin = "" + return screen raise AssertionError("unreachable") def click(self, handle: str) -> None: diff --git a/packages/flow/openadapt_flow/gui/model.py b/packages/flow/openadapt_flow/gui/model.py index af6b7974b8..6e688f9326 100644 --- a/packages/flow/openadapt_flow/gui/model.py +++ b/packages/flow/openadapt_flow/gui/model.py @@ -310,7 +310,7 @@ class DemoStep: writes the backend counted between ``before`` and ``after`` (requests that change state, a file save, a cell committed), or None when it could not count them. ``write_outcomes`` is what each of those writes returned - (``"2xx"``, ``"3xx /done"``), or None when the backend does not say.""" + (``"2xx"``, ``"redirect /done"``), or None when the backend does not say.""" action: ActionKind target: Control diff --git a/packages/flow/openadapt_flow/gui/steps.py b/packages/flow/openadapt_flow/gui/steps.py index c5184a02fb..097fee5356 100644 --- a/packages/flow/openadapt_flow/gui/steps.py +++ b/packages/flow/openadapt_flow/gui/steps.py @@ -20,9 +20,12 @@ :func:`judge_step` is a verdict site. A commit step holds only when the backend counted exactly the writes the demonstration made, and each returned what the demonstrated one did: the same status class and, for a redirect, -the same ``Location`` path. A save bounced to a sign-in page is a 302 like a -save that went to its confirmation page; only the path tells them apart. A -commit spec with no recorded outcomes (an older pack) is never clicked. A +the same ``Location`` key (path and query, with minted ids replaced; see +:func:`~openadapt_flow.gui.dom.location_key`). A save bounced to a sign-in +page is a 302 like a save that went to its confirmation page; only the +``Location`` tells them apart. A commit spec with no recorded outcomes, or +with an outcome in the old path-only ``"3xx "`` form (an older pack), +is never clicked. A backend that cannot count writes never shows a commit, so a commit through a plain link that sends nothing the backend counts stays unproven, as it should: the run has no evidence the record was saved. A navigation step that wrote, or that @@ -78,8 +81,9 @@ class StepSpec: ``writes`` is the number of writes the demonstration counted for it: at least 1 for a commit, 0 otherwise. ``outcomes`` is what each of a commit's writes returned in the demo, sorted (``"2xx"``, - ``"3xx /done"``); None on a spec learned before outcomes were recorded, - and such a commit is not taken.""" + ``"redirect /done"``); None on a spec learned before outcomes were + recorded. Such a commit is not taken, and nor is one with an outcome in + the old ``"3xx "`` form.""" step_id: str control: ControlSpec @@ -165,7 +169,7 @@ def learn_steps(demo: Sequence[DemoStep]) -> tuple[LearnedStep, ...]: outcomes = None if role is StepRole.COMMIT: outcomes = _outcomes(step.write_outcomes) - if outcomes is None or len(outcomes) != writes: + if outcomes is None or len(outcomes) != writes or _legacy(outcomes): out.append( LearnedStep( index, @@ -223,6 +227,19 @@ def _count(value: object) -> Optional[int]: return value +#: The prefix of a redirect outcome learned before the query and minted ids +#: were part of the key. Such an outcome is never compared: its path-only +#: key could match a replay that went somewhere else. +LEGACY_REDIRECT = "3xx " + + +def _legacy(outcomes: object) -> bool: + """Whether any outcome is in the old path-only redirect form.""" + return isinstance(outcomes, (tuple, list)) and any( + isinstance(o, str) and o.startswith(LEGACY_REDIRECT) for o in outcomes + ) + + def _outcomes(value: object) -> Optional[tuple[str, ...]]: """``value`` as a sorted tuple of non-empty strings, else None.""" if not isinstance(value, (tuple, list)): @@ -238,9 +255,9 @@ def judge_step(ev: StepEvidence) -> Result: - ``commit``: exactly ``expected_writes`` new writes, on a complete read with no error shown, each returning what the demo's did (status class, - and the ``Location`` path of a redirect). No write, a different + and the ``Location`` key of a redirect). No write, a different number, or a different outcome is refuted; outcomes missing on either - side are not checked. + side, or in the old path-only ``"3xx "`` form, are not checked. - ``navigate``: the screen changed and nothing was written. - ``in_place``: nothing was written and the screen did not move. - ``unknown`` or any role nobody listed: not checked. @@ -283,6 +300,11 @@ def judge_step(ev: StepEvidence) -> Result: return Result.not_checked( subject, "the demo did not record what its writes returned" ) + if _legacy(want_out) or _legacy(got_out): + return Result.not_checked( + subject, + "an outcome is in the old path-only redirect form; relearn the step", + ) if got_out is None or len(got_out) != delta: return Result.not_checked( subject, "the backend did not report what the writes returned" @@ -338,7 +360,8 @@ def take_step( Nothing is clicked when the control is missing or ambiguous, when the backend cannot count writes (no step could be judged there, so none is attempted), or for a commit when the spec or the backend has no record of - what the writes returned.""" + what the writes returned, or the spec has it only in the old path-only + redirect form.""" subject = Subject(run_id=run_id, surface="gui", key=spec.step_id, field="step") before_screen = screen if screen is not None else actuator.observe() @@ -362,9 +385,12 @@ def take_step( ctrl, ) o0 = write_outcomes_of(actuator) - if spec.role is StepRole.COMMIT and (spec.outcomes is None or o0 is None): - # Without the demo's outcomes, or a backend that reports them, a - # commit bounced to a sign-in page looks like one that saved. + if spec.role is StepRole.COMMIT and ( + spec.outcomes is None or o0 is None or _legacy(spec.outcomes) + ): + # Without the demo's outcomes in the current form, or a backend that + # reports them, a commit bounced to a sign-in page looks like one + # that saved. return StepOutcome( Result.not_checked( subject, diff --git a/packages/flow/tests/failopen/sites/gui_steps.py b/packages/flow/tests/failopen/sites/gui_steps.py index 68fcdb14ee..cdf01ca27c 100644 --- a/packages/flow/tests/failopen/sites/gui_steps.py +++ b/packages/flow/tests/failopen/sites/gui_steps.py @@ -3,7 +3,8 @@ A commit holds only on exactly the demonstrated number of writes, each returning what the demonstrated one did (a 302 to a sign-in page is not the -302 to the confirmation page the demo saw); a +302 to the confirmation page the demo saw, and an outcome in the old +path-only ``"3xx "`` form is not checked); a navigation only when the screen moved and nothing was written. Write counts that are not whole numbers, and roles nobody listed, are not checked. @@ -100,19 +101,46 @@ def put(ev: dict[str, Any], value: Any) -> None: Seed(_ev("commit", writes_after=3), False, "a commit that wrote nothing"), Seed(_ev("commit", writes_after=5), False, "two writes for one"), Seed( - _ev("commit", outcomes=("3xx /login",)), + _ev("commit", outcomes=("redirect /login",)), False, "a redirect to sign-in where the demo saved", ), Seed( _ev( "commit", - expected_outcomes=("3xx /done",), - outcomes=("3xx /login",), + expected_outcomes=("redirect /done",), + outcomes=("redirect /login",), ), False, "a redirect elsewhere than the demo's", ), + Seed( + _ev( + "commit", + expected_outcomes=("redirect /register?status=saved",), + outcomes=("redirect /register?status=session-expired",), + ), + False, + "a redirect to the same path with another query", + ), + Seed( + _ev( + "commit", + expected_outcomes=("redirect /records/{id}",), + outcomes=("redirect /records/{id}",), + ), + True, + "a redirect to the record just created", + ), + Seed( + _ev( + "commit", + expected_outcomes=("3xx /done",), + outcomes=("3xx /done",), + ), + False, + "an outcome learned in the old path-only form", + ), Seed( _ev("commit", expected_outcomes=None), False, diff --git a/packages/flow/tests/gui/_apps.py b/packages/flow/tests/gui/_apps.py index b373fb4b44..9efff93639 100644 --- a/packages/flow/tests/gui/_apps.py +++ b/packages/flow/tests/gui/_apps.py @@ -75,6 +75,8 @@ def registration_app( error_after: bool = False, fetch_writes: bool = False, redirect: str = "", + saves: Optional[bool] = None, + first_id: int = 101, ) -> App: """Contact details, then a ticket, then Register. "Continue" is a link that keeps the values in session storage. ``next_writes`` makes the link also @@ -85,7 +87,12 @@ def registration_app( navigates; ``fetch_writes`` sends them with ``fetch()`` instead, which the navigation aborts. ``redirect="/done"`` saves and answers 302 to the confirmation page; ``redirect="/login"`` saves nothing and answers 302 to - a plain sign-in page (an expired session), with no alert.""" + a plain sign-in page (an expired session), with no alert. ``saves`` says + whether Register saves (by default, unless the redirect is ``/login``). + ``{id}`` in ``redirect`` is the new record's id, counted from + ``first_id`` (a post-redirect-get to the record just created).""" + + keeps = redirect != "/login" if saves is None else saves def _post(path: str, body: str) -> str: if fetch_writes: @@ -131,13 +138,12 @@ def ticket(app: App, path: str, method: str, form: dict) -> tuple[int, str]: ) def register(app: App, path: str, method: str, form: dict) -> tuple[int, str]: - if redirect == "/login": - return 302, "/login" - app.state.setdefault("records", []).append( - {k: v[0] for k, v in form.items() if v} - ) + if not keeps: + return 302, redirect or "/login" + records = app.state.setdefault("records", []) + records.append({k: v[0] for k, v in form.items() if v}) if redirect: - return 302, redirect + return 302, redirect.replace("{id}", str(first_id + len(records) - 1)) return done(app, path, method, form) def login(app: App, path: str, method: str, form: dict) -> tuple[int, str]: @@ -152,6 +158,11 @@ def done(app: App, path: str, method: str, form: dict) -> tuple[int, str]: alert = '

Payment could not be taken

' if error_after else "" return 200, page("Done", f"

Registration received

{alert}
") + def landing(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + # Any other page a redirect lands on: a record, or a status page. + status = form.get("status", [""])[0] + return 200, page("Result", f"

{path}

{status}

") + def draft_ok(app: App, path: str, method: str, form: dict) -> tuple[int, str]: return 200, "{}" @@ -164,6 +175,7 @@ def draft_ok(app: App, path: str, method: str, form: dict) -> tuple[int, str]: ("GET", "/done"): done, ("GET", "/login"): login, ("POST", "/draft"): draft_ok, + ("GET", "*"): landing, }, ) diff --git a/packages/flow/tests/gui/test_gui_steps.py b/packages/flow/tests/gui/test_gui_steps.py index f0a8d5a60d..720ab4b3c0 100644 --- a/packages/flow/tests/gui/test_gui_steps.py +++ b/packages/flow/tests/gui/test_gui_steps.py @@ -18,7 +18,7 @@ import openadapt_flow from openadapt_flow.gui.adapters import screen_from_form_snapshot -from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.dom import PageActuator, location_key from openadapt_flow.gui.model import ControlSpec, Recorder, match_one from openadapt_flow.gui.steps import ( StepEvidence, @@ -163,7 +163,7 @@ def test_a_commit_bounced_to_sign_in_is_not_held(page) -> None: out = _replay_commit(page, steps, app2, "r302") assert out.clicked and out.result.status is not Status.HELD assert out.result.status is Status.REFUTED, out.result.reason - assert "3xx /login" in out.result.reason + assert "redirect /login" in out.result.reason assert not app2.state.get("records") @@ -171,7 +171,7 @@ def test_a_redirect_to_another_path_than_the_demo_is_not_held(page) -> None: """Demo POST answers 302 to /done; replay answers 302 to /login.""" with _apps.serve(page, _apps.registration_app(redirect="/done")) as app: steps = [s.spec for s in learn_steps(_record_registration(page, app))] - assert steps[1].outcomes == ("3xx /done",) + assert steps[1].outcomes == ("redirect /done",) app2 = _apps.registration_app(redirect="/login") out = _replay_commit(page, steps, app2, "r302b") assert out.clicked and out.result.status is Status.REFUTED, out.result.reason @@ -194,6 +194,71 @@ def test_a_commit_spec_without_recorded_outcomes_is_never_clicked(page) -> None: assert not app2.state.get("records") +def test_a_same_path_redirect_with_another_query_is_refuted(page) -> None: + """Demo POST saves and answers 302 to ``/register?status=saved``; the + replay saves nothing and answers 302 to the same path with + ``?status=session-expired``. Only the query tells them apart.""" + demo = _apps.registration_app(redirect="/register?status=saved") + with _apps.serve(page, demo) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("redirect /register?status=saved",) + app2 = _apps.registration_app( + redirect="/register?status=session-expired", saves=False + ) + out = _replay_commit(page, steps, app2, "rq1") + assert out.clicked and out.result.status is Status.REFUTED, out.result.reason + assert "status=session-expired" in out.result.reason + assert not app2.state.get("records") + app3 = _apps.registration_app(redirect="/register?status=saved") + out = _replay_commit(page, steps, app3, "rq2") + assert out.held, out.result.reason + assert len(app3.state["records"]) == 1 + + +def test_a_redirect_to_the_record_just_created_is_held(page) -> None: + """Post-redirect-get to the new record: ``/records/101`` in the demo, + ``/records/102`` on replay. The minted id is not part of the outcome.""" + demo = _apps.registration_app(redirect="/records/{id}", first_id=101) + with _apps.serve(page, demo) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("redirect /records/{id}",) + app2 = _apps.registration_app(redirect="/records/{id}", first_id=102) + out = _replay_commit(page, steps, app2, "rprg") + assert out.held, out.result.reason + assert app2.state["records"] == [ + {"name": "Bo Sample", "email": "bo@example.test", "ticket": "vip"} + ] + assert page.url.endswith("/records/102") + + +def test_a_redirect_to_sign_in_where_the_demo_went_to_a_record_is_refuted( + page, +) -> None: + demo = _apps.registration_app(redirect="/records/{id}") + with _apps.serve(page, demo) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + app2 = _apps.registration_app(redirect="/login") + out = _replay_commit(page, steps, app2, "rprg2") + assert out.clicked and out.result.status is Status.REFUTED, out.result.reason + assert "redirect /login" in out.result.reason + assert not app2.state.get("records") + + +def test_a_commit_spec_with_an_old_path_only_redirect_is_never_clicked(page) -> None: + """A spec learned when the key was the path alone (``"3xx /done"``) + could match a replay that went to the same path with another query, so + it is not taken, even where the replay would have matched.""" + with _apps.serve(page, _apps.registration_app(redirect="/done")) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + old = StepSpec( + steps[1].step_id, steps[1].control, StepRole.COMMIT, 1, ("3xx /done",) + ) + app2 = _apps.registration_app(redirect="/done") + out = _replay_commit(page, [steps[0], old], app2, "rlegacy") + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert not app2.state.get("records") + + def test_a_missing_renamed_or_doubled_link_is_never_clicked(page) -> None: spec = StepSpec("next", ControlSpec("link", "Continue"), StepRole.NAVIGATE) app = _apps.registration_app() @@ -367,7 +432,14 @@ def test_judge_step_needs_exact_whole_counts() -> None: ) assert judge_step(StepEvidence(**base)).status is Status.HELD for change in ( - {"outcomes": ("3xx /login",)}, + {"outcomes": ("redirect /login",)}, + {"outcomes": ("redirect /register?status=session-expired",)}, + { + "expected_outcomes": ("redirect /register?status=saved",), + "outcomes": ("redirect /register?status=session-expired",), + }, + {"expected_outcomes": ("3xx /done",), "outcomes": ("3xx /done",)}, + {"expected_outcomes": ("3xx /done",), "outcomes": ("redirect /done",)}, {"outcomes": None}, {"outcomes": "2xx"}, {"outcomes": ("2xx", "2xx")}, @@ -385,6 +457,130 @@ def test_judge_step_needs_exact_whole_counts() -> None: assert got.status is not Status.HELD, change +def test_judge_step_does_not_check_an_old_path_only_redirect() -> None: + ev = StepEvidence( + "s", + StepRole.COMMIT, + 1, + 3, + 4, + True, + True, + expected_outcomes=("3xx /done",), + outcomes=("3xx /done",), + ) + got = judge_step(ev) + assert got.status is Status.NOT_CHECKED and "old path-only" in got.reason + + +REQ = "http://app.test/records" + + +@pytest.mark.parametrize( + ("a", "b"), + [ + ("/records/101", "/records/102"), + ("/records/7/", "/records/8"), + ( + "/r/3f2b8c1e-0a4d-4e5f-9b6a-7c8d9e0f1a2b", + "/r/00000000-0000-4000-8000-000000000000", + ), + ("/r/0123456789abcdef", "/r/fedcba9876543210ABCD"), + ("/view?id=0123456789abcdef0123", "/view?id=ffffffffffffffff"), + ("/done?b=2&a=1", "/done?a=1&b=2"), + ("/done?msg=two%20words", "/done?msg=two+words"), + ("/done?error=", "/done?error="), + ("/done#top", "/done"), + ("/done/", "http://app.test/done"), + ], +) +def test_location_keys_that_match(a: str, b: str) -> None: + assert location_key(REQ, a) == location_key(REQ, b) + + +@pytest.mark.parametrize( + ("a", "b"), + [ + ("/register?status=saved", "/register?status=session-expired"), + ("/index.php?page=done", "/index.php?page=login"), + ("/records/101", "/login"), + ("/records/101", "/records/new"), + ("/done?saved=1", "/done?saved=0"), + ("/view?id=101", "/view?id=102"), + ("/r/deadbeef", "/r/cafebabe"), + ("/r/{id}", "/r/101"), + ("/done?error=", "/done"), + ("/done?a=1&a=2", "/done?a=1"), + ("/done?a=1%262", "/done?a=1&2="), + ("/done", "http://other.test/done"), + ], +) +def test_location_keys_that_differ(a: str, b: str) -> None: + assert location_key(REQ, a) != location_key(REQ, b) + + +def test_location_key_format() -> None: + assert location_key(REQ, "/records/101/?b=x&a=0123456789abcdef#f") == ( + "/records/{id}?a={id}&b=x" + ) + assert location_key(REQ, "https://Sso.Example.test/login?next=%2Fa") == ( + "https://sso.example.test/login?next=%2Fa" + ) + + +class _FakeRequest: + def __init__(self, method: str, url: str) -> None: + self.method, self.url = method, url + + +class _FakeResponse: + def __init__(self, method: str, url: str, status: int = 200) -> None: + self.request, self.status, self.headers = _FakeRequest(method, url), status, {} + + +class _FakePage: + def __init__(self, url: str) -> None: + self.url = url + self.handlers: dict = {} + + def on(self, event: str, fn) -> None: + self.handlers[event] = fn + + def wait_for_load_state(self, state: str) -> None: + pass + + def wait_for_timeout(self, ms: int) -> None: + pass + + def evaluate(self, js: str, arg) -> dict: + return {"controls": [], "complete": True} + + def locator(self, handle: str): + page = self + + class _Loc: + def click(self) -> None: + page.handlers["response"](_FakeResponse("POST", "http://a.test/save")) + + return _Loc() + + +def test_the_step_origin_is_cleared_once_the_page_is_read() -> None: + """After an action's page is read, a response is judged against the page + the caller is on now, not the origin the action started on.""" + fake = _FakePage("http://a.test/form") + act = PageActuator(fake) + act.click("#save") + assert act.write_count() == 1 + act.observe() + fake.url = "http://b.test/other" + fake.handlers["response"](_FakeResponse("POST", "http://a.test/late")) + assert act.write_count() == 1 + fake.handlers["response"](_FakeResponse("POST", "http://b.test/save")) + assert act.write_count() == 2 + assert act.write_outcomes() == ("2xx", "2xx") + + def test_form_snapshot_links_become_link_controls() -> None: from openadapt_flow.form_tx.types import FormSnapshot, ObservedControl From 97dc0cbd4639e66031aca6fad855ef587098a578 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 05:00:25 -0500 Subject: [PATCH 14/14] test(gui): serve synthetic test apps on loopback HTTP so 302 redirects resolve --- packages/flow/tests/gui/_apps.py | 62 +++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 13 deletions(-) diff --git a/packages/flow/tests/gui/_apps.py b/packages/flow/tests/gui/_apps.py index 9efff93639..4159ef98b5 100644 --- a/packages/flow/tests/gui/_apps.py +++ b/packages/flow/tests/gui/_apps.py @@ -9,7 +9,9 @@ from __future__ import annotations import contextlib +import http.server import json +import threading from dataclasses import dataclass, field from typing import Any, Callable, Iterator, Optional from urllib.parse import parse_qs, urlsplit @@ -26,26 +28,28 @@ class App: routes: dict[tuple[str, str], Handler] state: dict[str, Any] = field(default_factory=dict) log: list[tuple[str, str]] = field(default_factory=list) + _origin: str = "" @property def origin(self) -> str: - return f"http://{self.host}" + return self._origin or f"http://{self.host}" - def handle(self, route: Any) -> None: - req = route.request - parts = urlsplit(req.url) - method = req.method.upper() - body = req.post_data or "" + def dispatch(self, method: str, target: str, body: str = "") -> tuple[int, str]: + parts = urlsplit(target) + verb = method.upper() form = parse_qs(body) if body and not body.startswith("{") else {} if body.startswith("{"): form = {k: [str(v)] for k, v in json.loads(body).items()} form.update(parse_qs(parts.query)) - self.log.append((method, parts.path)) - fn = self.routes.get((method, parts.path)) or self.routes.get((method, "*")) + self.log.append((verb, parts.path)) + fn = self.routes.get((verb, parts.path)) or self.routes.get((verb, "*")) if fn is None: - route.fulfill(status=404, body="not found") - return - status, html = fn(self, parts.path, method, form) + return 404, "not found" + return fn(self, parts.path, verb, form) + + def handle(self, route: Any) -> None: + req = route.request + status, html = self.dispatch(req.method, req.url, req.post_data or "") if status in (302, 303): route.fulfill(status=status, headers={"Location": html}, body="") return @@ -54,11 +58,43 @@ def handle(self, route: Any) -> None: @contextlib.contextmanager def serve(page: Any, app: App) -> Iterator[App]: - page.context.route(f"{app.origin}/**", app.handle) + class _Handler(http.server.BaseHTTPRequestHandler): + def _run(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length).decode("utf-8") if length else "" + status, payload = app.dispatch(self.command, self.path, body) + if status in (302, 303): + self.send_response(status) + self.send_header("Location", payload) + self.send_header("Content-Length", "0") + self.end_headers() + return + encoded = payload.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + do_GET = _run + do_POST = _run + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + return + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + prev_origin = app._origin + app._origin = f"http://127.0.0.1:{port}" try: yield app finally: - page.context.unroute(f"{app.origin}/**") + server.shutdown() + server.server_close() + thread.join(timeout=2.0) + app._origin = prev_origin def page(title: str, body: str) -> str: