From 8ac01cb338f78f97e83f2ce424a91b3c0ea9374a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:48:06 -0500 Subject: [PATCH 01/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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 ff2b63f12ca468d4cf4f80d270a402dc932d5706 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:02:49 -0500 Subject: [PATCH 10/19] feat(flow): checkbox attestations declared in pack data and ticked only on a person's grant gui.attestations plans every checkbox and switch on a screen: a field binding's, an attestation to tick, a box the pack leaves alone, or a stop. An undeclared box, a changed statement, a missing grant, an attestation bound to a field or a box ticked before the run touched it all stop the run before anything is ticked. Grants are their own type, so no intake value or derived fact can tick one. judge_attestations settles the planned boxes against a fresh read and is a registered verdict site. --- .../flow/openadapt_flow/gui/attestations.py | 544 ++++++++++++++++++ packages/flow/openadapt_flow/gui/dom.py | 5 +- .../tests/failopen/sites/gui_attestations.py | 133 +++++ .../flow/tests/gui/test_gui_attestations.py | 428 ++++++++++++++ 4 files changed, 1109 insertions(+), 1 deletion(-) create mode 100644 packages/flow/openadapt_flow/gui/attestations.py create mode 100644 packages/flow/tests/failopen/sites/gui_attestations.py create mode 100644 packages/flow/tests/gui/test_gui_attestations.py diff --git a/packages/flow/openadapt_flow/gui/attestations.py b/packages/flow/openadapt_flow/gui/attestations.py new file mode 100644 index 0000000000..0042c6c19e --- /dev/null +++ b/packages/flow/openadapt_flow/gui/attestations.py @@ -0,0 +1,544 @@ +"""Checkbox attestations: declared in pack data, ticked only on a person's grant. + +Some checkboxes are not data. "I confirm the information above is true", "I +attest that I reviewed this list", "I understand this cannot be undone": a +tick there is a statement someone makes. Packs used to bind such a box to an +intake fact (``confirm_details: true``) or a derived flag, so the run ticked +it on its own. This module separates the two: + +- An :class:`AttestationSpec` is pack data: which box, and the SHA-256 of its + statement as the demonstration showed it (:func:`statement_digest`). +- An :class:`AttestationGrant` is given to the run by the person who + attests, for one statement digest. It is its own type: an intake value, a + derived fact, a bool or a mapping is refused (:func:`plan_checkboxes` + raises ``TypeError``), so nothing can tick an attestation through a fact. +- :func:`check_pack` refuses a pack whose field bindings name a declared + attestation. + +:func:`plan_checkboxes` decides, for every checkbox or switch on the screen: + +- ``field``: a field binding covers it; it is not an attestation. +- ``tick``: it matches exactly one declared attestation whose statement still + hashes to the pinned digest, the run holds a grant for that digest, and the + box is not ticked yet. +- ``leave``: the pack lists it as knowingly left alone (``ignored``), and it + shows the state the pack declared. +- ``stop``: anything else. An undeclared checkbox, a changed statement, a + missing or mismatched grant, an attestation bound to a field, a box ticked + before the run touched it, or two specs matching one box. The run stops + before acting on any box. + +:func:`judge_attestations` is a verdict site. Its obligations are the plan's +boxes (other than ``field`` ones), fixed before any tick, and it settles them +against a fresh read: each must show the planned state with the same +statement, and a box the plan never saw is unexpected. + +Words are never matched against a list: an attestation is whatever the pack +declares, and the engine knows no "I agree" vocabulary. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from enum import Enum +from typing import Any, Iterable, Literal, Mapping, Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + Control, + ControlSpec, + DemoStep, + Screen, + norm, +) +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Settlement, + Status, + Subject, + settle, +) +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "AttestationCandidate", + "AttestationGrant", + "AttestationPlan", + "AttestationSpec", + "BoxDecision", + "BoxPlan", + "IgnoredBox", + "PackError", + "apply_attestations", + "check_pack", + "judge_attestations", + "learn_attestations", + "judge_screen", + "plan_checkboxes", + "plan_rows", + "statement_digest", + "statement_of", +] + +BOX_ROLES = frozenset({"checkbox", "switch"}) +#: Longest statement read from a container; a longer one is not read whole. +STATEMENT_CAP = 2000 + + +def statement_digest(text: str) -> str: + """SHA-256 of a statement after :func:`~openadapt_flow.gui.model.norm`.""" + + return hashlib.sha256(norm(text).encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class AttestationSpec: + """Pack data: one attestation box and the digest of its statement. + + ``statement_from`` says where the statement is: the box's own label + (``name``), or the text of the innermost container around it + (``container``), for a box labelled "I agree" under a paragraph.""" + + attestation_id: str + control: ControlSpec + statement_sha256: str + statement_from: Literal["name", "container"] = "name" + + def __post_init__(self) -> None: + if self.control.role not in BOX_ROLES: + raise ValueError("an attestation is a checkbox or a switch") + if len(self.statement_sha256) != 64: + raise ValueError("statement_sha256 is a SHA-256 hex digest") + if self.statement_from not in ("name", "container"): + raise ValueError(f"unknown statement source {self.statement_from!r}") + + +def statement_of(ctrl: Control, source: str = "name") -> Optional[str]: + """The statement a box carries: its label, or its innermost container's + text. None when there is none, or it may have been cut short.""" + + if source == "name": + return ctrl.name or None + if source != "container" or not ctrl.containers: + return None + text = ctrl.containers[-1].text + if not text or len(text) >= STATEMENT_CAP: + return None + return text + + +@dataclass(frozen=True) +class AttestationGrant: + """A person's attestation for one run: this statement, by this person. + + Built from the run request by whoever collects the attestation, never + from intake values.""" + + attestation_id: str + statement_sha256: str + granted_by: str + + def __post_init__(self) -> None: + if not self.granted_by.strip(): + raise ValueError("a grant names the person who attests") + + +@dataclass(frozen=True) +class IgnoredBox: + """A checkbox the pack knowingly leaves alone, and the state it must show.""" + + control: ControlSpec + checked: bool = False + + +class PackError(ValueError): + """The pack binds a declared attestation to a field.""" + + +def check_pack( + attestations: Sequence[AttestationSpec], + field_controls: Iterable[ControlSpec], +) -> None: + """Refuse a pack whose field bindings name a declared attestation's box + (same role and name). Raises :class:`PackError`.""" + + declared = {(a.control.role, norm(a.control.name)): a for a in attestations} + for spec in field_controls: + hit = declared.get((spec.role, norm(spec.name))) + if hit is not None: + raise PackError( + f"attestation {hit.attestation_id!r} is bound to a field; " + "an attestation is ticked only on a grant" + ) + ids = [a.attestation_id for a in attestations] + if len(ids) != len(set(ids)): + raise PackError("two attestations share an id") + + +class BoxDecision(str, Enum): + FIELD = "field" + TICK = "tick" + LEAVE = "leave" + STOP = "stop" + + +@dataclass(frozen=True) +class BoxPlan: + handle: str + name: str + decision: BoxDecision + digest: str + #: The state the box must show after the plan is applied (None: a field's). + want_checked: Optional[bool] + attestation_id: Optional[str] = None + granted_by: str = "" + reason: str = "" + statement_from: str = "name" + + +@dataclass(frozen=True) +class AttestationPlan: + boxes: tuple[BoxPlan, ...] + run_id: str = "" + + @property + def stops(self) -> tuple[BoxPlan, ...]: + return tuple(b for b in self.boxes if b.decision is BoxDecision.STOP) + + @property + def ticks(self) -> tuple[BoxPlan, ...]: + return tuple(b for b in self.boxes if b.decision is BoxDecision.TICK) + + +def _stop(ctrl: Control, reason: str, att: Optional[str] = None) -> BoxPlan: + return BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.STOP, + statement_digest(ctrl.name), + None, + att, + reason=reason, + ) + + +def _grants_by_id(grants: Iterable[object]) -> dict[str, AttestationGrant]: + out: dict[str, AttestationGrant] = {} + for grant in grants: + if not isinstance(grant, AttestationGrant): + raise TypeError( + "attestations are ticked only on an AttestationGrant, " + f"not on {type(grant).__name__}" + ) + if grant.attestation_id in out: + raise ValueError(f"two grants for {grant.attestation_id!r}") + out[grant.attestation_id] = grant + return out + + +def plan_checkboxes( + screen: Screen, + *, + attestations: Sequence[AttestationSpec], + grants: Iterable[object] = (), + bound: Iterable[str] = (), + ignored: Sequence[IgnoredBox] = (), + run_id: str = "", +) -> AttestationPlan: + """Decide every checkbox and switch on ``screen`` (see the module doc). + + ``bound`` holds the handles the pack's field bindings resolved to on this + screen. ``grants`` must all be :class:`AttestationGrant`.""" + + by_id = _grants_by_id(grants) + bound_set = set(bound) + boxes: list[BoxPlan] = [] + for ctrl in screen.controls: + if ctrl.role not in BOX_ROLES: + continue + specs = [a for a in attestations if a.control.matches(ctrl)] + if ctrl.handle in bound_set: + if specs: + boxes.append( + _stop( + ctrl, + "a declared attestation is bound to a field", + specs[0].attestation_id, + ) + ) + else: + boxes.append( + BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.FIELD, + statement_digest(ctrl.name), + None, + ) + ) + continue + if len(specs) > 1: + boxes.append(_stop(ctrl, "two declared attestations match this box")) + continue + if not specs: + leave = [i for i in ignored if i.control.matches(ctrl)] + if len(leave) == 1 and ctrl.checked is leave[0].checked: + boxes.append( + BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.LEAVE, + statement_digest(ctrl.name), + leave[0].checked, + ) + ) + elif len(leave) == 1: + boxes.append( + _stop( + ctrl, "a box the pack leaves alone is not in its declared state" + ) + ) + else: + boxes.append(_stop(ctrl, "a checkbox the pack does not declare")) + continue + spec = specs[0] + statement = statement_of(ctrl, spec.statement_from) + digest = statement_digest(statement or "") + grant = by_id.get(spec.attestation_id) + if statement is None: + boxes.append( + _stop( + ctrl, "the statement could not be read whole", spec.attestation_id + ) + ) + elif digest != spec.statement_sha256: + boxes.append( + _stop( + ctrl, + "the statement differs from the declared one", + spec.attestation_id, + ) + ) + elif grant is None: + boxes.append( + _stop( + ctrl, + "no one attested this statement for this run", + spec.attestation_id, + ) + ) + elif grant.statement_sha256 != digest: + boxes.append( + _stop( + ctrl, "the grant is for a different statement", spec.attestation_id + ) + ) + elif ctrl.checked is not False: + boxes.append( + _stop( + ctrl, + "the box was ticked before the run touched it", + spec.attestation_id, + ) + ) + elif ctrl.disabled or ctrl.readonly: + boxes.append(_stop(ctrl, "the box cannot be ticked", spec.attestation_id)) + else: + boxes.append( + BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.TICK, + digest, + True, + spec.attestation_id, + grant.granted_by, + statement_from=spec.statement_from, + ) + ) + return AttestationPlan(tuple(boxes), run_id) + + +def apply_attestations(actuator: Actuator, plan: AttestationPlan) -> Screen: + """Tick the plan's ``tick`` boxes and return a fresh read. Refuses a plan + with any ``stop``: nothing is ticked.""" + + if plan.stops: + raise ValueError(f"the plan stops: {plan.stops[0].reason}") + for box in plan.ticks: + actuator.set_checked(box.handle, True) + return actuator.observe() + + +# -- the verdict ------------------------------------------------------------------ + + +def _obs_of(screen: Screen, plan: AttestationPlan) -> list[dict[str, Any]]: + """A fresh read of every box, bound to the run that read it. Each box's + statement is read from where the plan read it.""" + + source = {b.handle: b.statement_from for b in plan.boxes} + return [ + { + "handle": c.handle, + "statement": statement_of(c, source.get(c.handle, "name")), + "checked": c.checked, + "run_id": plan.run_id, + } + for c in screen.controls + if c.role in BOX_ROLES + ] + + +@dataclass(frozen=True) +class AttestationVerdict: + settlement: Settlement + status: Status + + +@verdict_site("gui.attestations.judge", classes="C1 C2 C5") +def judge_attestations( + plan: Sequence[Mapping[str, Any]], + after: Sequence[Mapping[str, Any]], + *, + run_id: str, + complete: bool = True, +) -> AttestationVerdict: + """Settle the plan's boxes against a fresh read of the screen. + + ``plan`` rows carry ``handle``, ``decision``, ``digest`` and + ``want_checked``; ``after`` rows carry ``handle``, ``statement``, + ``checked`` and ``run_id``. ``field`` rows are a binding's business and are left out. + A ``stop`` row is an obligation that can never hold. A box must show the + planned state with a statement that still hashes to the planned digest; + a read whose ``checked`` is not a bool is not checked, and a box the plan + never saw is unexpected. ``complete=False`` (a capped read) can refute, + never hold.""" + + planned = [p for p in plan if p.get("decision") != BoxDecision.FIELD.value] + fields = { + p.get("handle") for p in plan if p.get("decision") == BoxDecision.FIELD.value + } + obligations = Obligations.fix( + ( + Subject(run_id=run_id, surface="gui", key=str(p.get("handle")), field="box") + for p in planned + ), + source="attestation plan", + ) + by_handle = {str(p.get("handle")): p for p in planned} + results = [] + for row in after: + handle = str(row.get("handle")) + if handle in fields: + continue + subject = Subject( + run_id=str(row.get("run_id") or ""), surface="gui", key=handle, field="box" + ) + obs = Observed(dict(row), complete=complete is True) + want = by_handle.get(handle) + if want is None: + results.append(Result.refuted(subject, obs, "a box the plan never saw")) + continue + checked = row.get("checked") + decision = want.get("decision") + if decision not in (BoxDecision.TICK.value, BoxDecision.LEAVE.value): + results.append( + Result.not_checked(subject, f"the plan stops here: {decision!r}") + ) + elif not isinstance(checked, bool): + results.append(Result.not_checked(subject, "the box's state was not read")) + elif not isinstance(row.get("statement"), str): + results.append(Result.not_checked(subject, "the statement was not read")) + elif statement_digest(row["statement"]) != want.get("digest"): + results.append(Result.refuted(subject, obs, "the statement changed")) + elif checked is not want.get("want_checked"): + results.append( + Result.refuted(subject, obs, "the box does not show the planned state") + ) + elif complete is not True: + results.append(Result.not_checked(subject, "the screen was read in part")) + else: + results.append(Result.held(subject, obs, "as planned")) + settlement = settle(obligations, results) + status = settlement.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) + # A box seen in the wrong state stays refuted even when another read of + # it disagrees (the two are then "conflicting" in the settlement). + seen_wrong = [r for r in results if r.status is Status.REFUTED] + if status is not Status.HELD and seen_wrong: + status = Status.REFUTED + return AttestationVerdict(settlement, status) + + +def plan_rows(plan: AttestationPlan) -> list[dict[str, Any]]: + """The plan as the rows :func:`judge_attestations` reads.""" + + return [ + { + "handle": b.handle, + "decision": b.decision.value, + "digest": b.digest, + "want_checked": b.want_checked, + } + for b in plan.boxes + ] + + +def judge_screen(plan: AttestationPlan, after: Screen) -> AttestationVerdict: + """:func:`judge_attestations` on a fresh :class:`Screen`.""" + + return judge_attestations( + plan_rows(plan), + _obs_of(after, plan), + run_id=plan.run_id, + complete=after.complete, + ) + + +# -- from a demonstration ---------------------------------------------------------- + + +@dataclass(frozen=True) +class AttestationCandidate: + """A box the demonstration ticked that no field binding covers. A + suggestion: the pack author decides whether it is an attestation.""" + + control: ControlSpec + statement_sha256: str + name: str + + +def learn_attestations( + demo: Sequence[DemoStep], bound: Iterable[str] = () +) -> tuple[tuple[AttestationCandidate, ...], tuple[IgnoredBox, ...]]: + """Suggest attestations (boxes the demo ticked, not bound) and boxes to + leave alone (boxes the demo saw but never touched, with the state they + showed). Nothing here goes into a pack without the author.""" + + bound_set = set(bound) + ticked: dict[str, Control] = {} + seen: dict[str, Control] = {} + for step in demo: + for ctrl in step.before.controls: + if ctrl.role in BOX_ROLES: + seen.setdefault(ctrl.handle, ctrl) + if step.action == "check" and step.target.role in BOX_ROLES: + ticked[step.target.handle] = step.target + candidates = tuple( + AttestationCandidate( + ControlSpec(c.role, c.name, tuple(x.name for x in c.containers if x.name)), + statement_digest(c.name), + c.name, + ) + for h, c in ticked.items() + if h not in bound_set + ) + leave = tuple( + IgnoredBox(ControlSpec(c.role, c.name), bool(c.checked)) + for h, c in seen.items() + if h not in ticked and h not in bound_set and c.name + ) + return candidates, leave diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py index 37310161c4..a29a386390 100644 --- a/packages/flow/openadapt_flow/gui/dom.py +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -101,6 +101,9 @@ if (el.tagName === 'INPUT') return clean(el.value); return clean(el.textContent) || clean(el.getAttribute('title')); } + // ARIA widgets other than native inputs take their name from content. + if (!['INPUT', 'SELECT', 'TEXTAREA'].includes(el.tagName) + && ['checkbox', 'switch', 'radio'].includes(role)) return clean(el.textContent); return clean(el.getAttribute('title')) || clean(el.getAttribute('placeholder')) || clean(el.getAttribute('name')); }; @@ -128,7 +131,7 @@ 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)}); + text: clean(n.innerText).slice(0, 2000)}); break; } } diff --git a/packages/flow/tests/failopen/sites/gui_attestations.py b/packages/flow/tests/failopen/sites/gui_attestations.py new file mode 100644 index 0000000000..1b177f2c72 --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_attestations.py @@ -0,0 +1,133 @@ +"""gui.attestations.judge (C1 C2 C5): every planned box shows the planned state +with the statement it had when it was planned. + +The obligations are the plan's boxes, fixed before any tick. A box the plan +never saw is unexpected, a statement that hashes differently is refuted, an +unread state is not checked, and an empty plan never passes. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.gui.attestations import judge_attestations, statement_digest +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +RUN = "run-1" + + +def _row(handle: str, statement: str, decision: str, want: bool) -> dict[str, Any]: + return { + "handle": handle, + "decision": decision, + "digest": statement_digest(statement), + "want_checked": want, + } + + +def _seen(handle: str, statement: str, checked: Any) -> dict[str, Any]: + return {"handle": handle, "statement": statement, "checked": checked, "run_id": RUN} + + +def _good() -> dict[str, Any]: + return { + "plan": [ + _row("#a", "I confirm this is true", "tick", True), + _row("#b", "Send me offers", "leave", False), + ], + "after": [ + _seen("#a", "I confirm this is true", True), + _seen("#b", "Send me offers", False), + ], + "complete": True, + } + + +def _run(ev: dict[str, Any]) -> Any: + return judge_attestations( + ev["plan"], ev["after"], run_id=RUN, complete=ev.get("complete") + ) + + +def _bad(item: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(item) + out["checked"] = not out["checked"] if isinstance(out["checked"], bool) else False + return out + + +def _inflate(ev: dict[str, Any], n: int) -> dict[str, Any]: + plan = [_row(f"#{i}", f"s{i}", "tick", True) for i in range(n)] + after = [_seen(f"#{i}", f"s{i}", i != n - 1) for i in range(n)] + return {**ev, "plan": plan, "after": after} + + +register( + SiteSpec( + id="gui.attestations.judge", + classes="C1 C2 C5", + target="openadapt_flow.gui.attestations:judge_attestations", + run=_run, + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_good(), True), + Seed( + { + **_good(), + "after": [ + _seen("#a", "I confirm this is true", False), + _seen("#b", "Send me offers", False), + ], + }, + False, + "the attestation is not ticked", + ), + Seed( + { + **_good(), + "after": [ + _seen("#a", "I confirm this and more", True), + _seen("#b", "Send me offers", False), + ], + }, + False, + "the statement changed", + ), + Seed( + { + **_good(), + "plan": [ + _row("#a", "I confirm this is true", "stop", True), + _row("#b", "Send me offers", "leave", False), + ], + }, + False, + "the plan stopped on a box", + ), + Seed( + { + **_good(), + "after": _good()["after"] + [_seen("#c", "New terms", False)], + }, + False, + "a box the plan never saw", + ), + ], + items=key("after"), + plan=key("plan"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("after"), 0), + values=( + key("checked", "after", 0), + key("statement", "after", 0), + key("digest", "plan", 0), + key("want_checked", "plan", 0), + key("decision", "plan", 0), + ), + subject=key("run_id", "after", 0), + partial=lambda ev: [("complete", {**ev, "complete": False})], + ) +) diff --git a/packages/flow/tests/gui/test_gui_attestations.py b/packages/flow/tests/gui/test_gui_attestations.py new file mode 100644 index 0000000000..a87616e574 --- /dev/null +++ b/packages/flow/tests/gui/test_gui_attestations.py @@ -0,0 +1,428 @@ +"""Checkbox attestations on four kinds of app. + +- a web form (membership application) with a declaration and a marketing box; +- an EMR-like chart where a medication review must be attested in a dialog; +- a SaaS danger zone where the attestation is a switch; +- a spreadsheet-like grid whose "final totals" box sits in a dialog. + +An attestation is ticked only on a person's grant for the pinned statement; +an undeclared box, a changed statement, a box bound to a fact or a missing +grant stops the run before anything is ticked. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from openadapt_flow.gui.attestations import ( + AttestationGrant, + AttestationSpec, + BoxDecision, + IgnoredBox, + PackError, + apply_attestations, + check_pack, + judge_attestations, + judge_screen, + learn_attestations, + plan_checkboxes, + statement_digest, +) +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.model import ControlSpec, Recorder, match_one +from openadapt_flow.verdict import Status +from tests.gui import _apps +from tests.gui._grid import GridApp, Sheet + +TRUE = "I confirm the information I have given is true and complete" + + +def _membership( + statement: str = TRUE, extra: str = "", agree: bool = False +) -> _apps.App: + box = ( + f'

{statement}

' + if agree + else f'' + ) + + def form(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Apply", + f"""

Membership application

+ +
Declaration{box}
+{extra} +
""", + ) + + def apply(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + app.state["applied"] = {k: v[0] for k, v in f.items()} + return 200, _apps.page("Thanks", "

Application received

") + + return _apps.App("join.test", {("GET", "/apply"): form, ("POST", "/apply"): apply}) + + +DECL = AttestationSpec( + "declaration", + ControlSpec("checkbox", TRUE, ("Declaration",)), + statement_digest(TRUE), +) +MARKETING = IgnoredBox( + ControlSpec("checkbox", "Send me news and offers"), checked=False +) +GRANT = AttestationGrant("declaration", statement_digest(TRUE), granted_by="applicant") + + +def _open(page: Any, app: _apps.App) -> PageActuator: + act = PageActuator(page) + page.goto(f"{app.origin}/apply") + return act + + +# -- web form -------------------------------------------------------------------- + + +def test_web_form_declaration_is_ticked_on_a_grant_and_read_back(page) -> None: + app = _membership() + with _apps.serve(page, app): + act = _open(page, app) + screen = act.observe() + name = match_one(ControlSpec("textbox", "Full name"), screen).handle + act.set_text(name, "Cy Sample") + plan = plan_checkboxes( + act.observe(), + attestations=[DECL], + grants=[GRANT], + ignored=[MARKETING], + run_id="r1", + ) + assert [b.decision for b in plan.boxes] == [BoxDecision.TICK, BoxDecision.LEAVE] + after = apply_attestations(act, plan) + verdict = judge_screen(plan, after) + assert verdict.status is Status.HELD, verdict.settlement + act.click(match_one(ControlSpec("button", "Submit application"), after).handle) + assert app.state["applied"] == {"name": "Cy Sample", "dec": "on"} + + +@pytest.mark.parametrize( + ("kwargs", "reason"), + [ + ({"grants": []}, "no one attested"), + ( + {"grants": [AttestationGrant("declaration", "0" * 64, "applicant")]}, + "different statement", + ), + ({"ignored": []}, "does not declare"), + ], +) +def test_web_form_without_a_matching_grant_or_declaration_stops( + page, kwargs, reason +) -> None: + app = _membership() + with _apps.serve(page, app): + act = _open(page, app) + args = { + "attestations": [DECL], + "grants": [GRANT], + "ignored": [MARKETING], + **kwargs, + } + plan = plan_checkboxes(act.observe(), **args) + assert plan.stops and reason in plan.stops[0].reason + with pytest.raises(ValueError): + apply_attestations(act, plan) + assert all( + c.checked is False for c in act.observe().controls if c.role == "checkbox" + ) + + +def test_web_form_changed_wording_or_a_new_box_stops(page) -> None: + reworded = _membership(TRUE + ", and I accept the new terms") + with _apps.serve(page, reworded): + act = _open(page, reworded) + # The spec names the box by its old words, so a reworded box is a + # box the pack does not declare. + plan = plan_checkboxes( + act.observe(), attestations=[DECL], grants=[GRANT], ignored=[MARKETING] + ) + assert [b.reason for b in plan.stops] == [ + "a checkbox the pack does not declare" + ] + # A box labelled "I agree" pins the paragraph around it: new words there + # are a different statement. + agree_text = f"Declaration {TRUE} I agree" + agree = AttestationSpec( + "declaration", + ControlSpec("checkbox", "I agree", ("Declaration",)), + statement_digest(agree_text), + statement_from="container", + ) + grant = AttestationGrant("declaration", agree.statement_sha256, "applicant") + same = _membership(agree=True) + with _apps.serve(page, same): + act = _open(page, same) + plan = plan_checkboxes( + act.observe(), attestations=[agree], grants=[grant], ignored=[MARKETING] + ) + assert not plan.stops, plan.stops + assert judge_screen(plan, apply_attestations(act, plan)).status is Status.HELD + changed = _membership(TRUE + " and I accept the new fees", agree=True) + with _apps.serve(page, changed): + act = _open(page, changed) + plan = plan_checkboxes( + act.observe(), attestations=[agree], grants=[grant], ignored=[MARKETING] + ) + assert [b.reason for b in plan.stops] == [ + "the statement differs from the declared one" + ] + added = _membership( + extra='' + ) + with _apps.serve(page, added): + act = _open(page, added) + plan = plan_checkboxes( + act.observe(), attestations=[DECL], grants=[GRANT], ignored=[MARKETING] + ) + assert [b.name for b in plan.stops] == ["I agree to binding arbitration"] + + +def test_a_grant_must_be_a_grant_not_a_fact() -> None: + with pytest.raises(TypeError): + plan_checkboxes(_membership_screen(), attestations=[DECL], grants=[True]) + with pytest.raises(TypeError): + plan_checkboxes( + _membership_screen(), attestations=[DECL], grants=[{"declaration": True}] + ) + + +def _membership_screen(): + from openadapt_flow.gui.model import Container, Control, Screen + + return Screen( + controls=( + Control( + "#dec", + "checkbox", + TRUE, + checked=False, + containers=(Container("fs", "group", "Declaration"),), + ), + ) + ) + + +def test_web_form_demo_suggests_the_declaration_and_the_box_left_alone(page) -> None: + app = _membership() + with _apps.serve(page, app): + act = _open(page, app) + rec = Recorder(act) + s = act.observe() + rec.set_text( + match_one(ControlSpec("textbox", "Full name"), s).handle, "Dee Sample" + ) + rec.set_checked("#dec", True) + rec.click( + match_one(ControlSpec("button", "Submit application"), act.observe()).handle + ) + candidates, leave = learn_attestations(rec.steps) + assert [(c.name, c.control.containers) for c in candidates] == [ + (TRUE, ("Declaration",)) + ] + assert candidates[0].statement_sha256 == DECL.statement_sha256 + assert [(i.control.name, i.checked) for i in leave] == [ + ("Send me news and offers", False) + ] + + +# -- EMR-like chart: an attestation bound to a fact is refused -------------------- + + +def _chart() -> _apps.App: + def chart(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Chart", + """

Chart: Test Patient B

+ +
""", + ) + + return _apps.App( + "chart.test", + {("GET", "/chart"): chart, ("POST", "/review"): lambda a, p, m, f: (200, "{}")}, + ) + + +REVIEW = "I attest that I reviewed this medication list with the patient" +REVIEW_SPEC = AttestationSpec( + "med_review", ControlSpec("checkbox", REVIEW), statement_digest(REVIEW) +) + + +def test_emr_attestation_bound_to_a_fact_is_refused_by_pack_check_and_plan( + page, +) -> None: + with pytest.raises(PackError): + check_pack( + [REVIEW_SPEC], + [ControlSpec("textbox", "Note"), ControlSpec("checkbox", REVIEW)], + ) + check_pack([REVIEW_SPEC], [ControlSpec("textbox", "Note")]) + app = _chart() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/chart") + act.click( + match_one(ControlSpec("button", "Review medications"), act.observe()).handle + ) + screen = act.observe() + box = match_one(ControlSpec("checkbox", REVIEW, dialog=True), screen) + grant = AttestationGrant( + "med_review", REVIEW_SPEC.statement_sha256, "clinician 4" + ) + bound = plan_checkboxes( + screen, attestations=[REVIEW_SPEC], grants=[grant], bound=[box.handle] + ) + assert [b.reason for b in bound.stops] == [ + "a declared attestation is bound to a field" + ] + plan = plan_checkboxes( + screen, attestations=[REVIEW_SPEC], grants=[grant], run_id="r2" + ) + after = apply_attestations(act, plan) + assert judge_screen(plan, after).status is Status.HELD + assert plan.ticks[0].granted_by == "clinician 4" + + +# -- SaaS: a switch --------------------------------------------------------------- + + +DANGER = "I understand this permanently deletes every project in the workspace" + + +def _danger_zone(prechecked: bool = False) -> _apps.App: + state = "true" if prechecked else "false" + + def page_(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Danger zone", + f"""

Danger zone

+{DANGER} +
""", + ) + + return _apps.App("app.test", {("GET", "/danger"): page_}) + + +DANGER_SPEC = AttestationSpec( + "delete_ack", ControlSpec("switch", DANGER), statement_digest(DANGER) +) + + +def test_saas_switch_attestation_ticks_on_grant_and_refuses_a_prechecked_one( + page, +) -> None: + grant = AttestationGrant( + "delete_ack", DANGER_SPEC.statement_sha256, "workspace owner" + ) + app = _danger_zone() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/danger") + plan = plan_checkboxes( + act.observe(), attestations=[DANGER_SPEC], grants=[grant] + ) + assert [b.decision for b in plan.boxes] == [BoxDecision.TICK] + act.click(plan.ticks[0].handle) # a switch is toggled by a click + assert judge_screen(plan, act.observe()).status is Status.HELD + pre = _danger_zone(prechecked=True) + with _apps.serve(page, pre): + act = PageActuator(page) + page.goto(f"{pre.origin}/danger") + plan = plan_checkboxes( + act.observe(), attestations=[DANGER_SPEC], grants=[grant] + ) + assert [b.reason for b in plan.stops] == [ + "the box was ticked before the run touched it" + ] + + +# -- grid: a box in a dialog, no browser -------------------------------------------- + + +FINAL = "These totals are final for the quarter" + + +class _ClosingGrid(GridApp): + def tree(self) -> dict[str, Any]: + self.dialog = { + "role": "dialog", + "name": "Close quarter", + "handle": "dlg", + "children": [ + { + "role": "check box", + "name": FINAL, + "handle": "chk:final", + "checked": self.checks.get("chk:final", False), + }, + { + "role": "check box", + "name": "Email the summary to me", + "handle": "chk:email", + "checked": self.checks.get("chk:email", False), + }, + ], + } + return super().tree() + + +def test_grid_dialog_attestation_settles_against_a_fresh_read() -> None: + grid = _ClosingGrid([Sheet("Q3", ("Item", "Amount"), [["Rent", "1300"]])]) + spec = AttestationSpec( + "final", + ControlSpec("checkbox", FINAL, ("Close quarter",)), + statement_digest(FINAL), + ) + grant = AttestationGrant("final", spec.statement_sha256, "controller") + leave = IgnoredBox(ControlSpec("checkbox", "Email the summary to me")) + plan = plan_checkboxes( + grid.observe(), + attestations=[spec], + grants=[grant], + ignored=[leave], + run_id="g1", + ) + after = apply_attestations(grid, plan) + assert judge_screen(plan, after).status is Status.HELD + # Someone ticks the box the pack leaves alone after the plan: refuted. + grid.checks["chk:email"] = True + assert judge_screen(plan, grid.observe()).status is Status.REFUTED + + +def test_judge_refuses_empty_unexpected_and_unread_boxes() -> None: + row = { + "handle": "a", + "decision": "tick", + "digest": statement_digest("x"), + "want_checked": True, + } + good = [{"handle": "a", "statement": "x", "checked": True, "run_id": "r"}] + assert judge_attestations([row], good, run_id="r").status is Status.HELD + assert judge_attestations([], [], run_id="r").status is not Status.HELD + extra = good + [{"handle": "b", "statement": "y", "checked": False, "run_id": "r"}] + assert judge_attestations([row], extra, run_id="r").status is not Status.HELD + unread = [{**good[0], "checked": None}] + assert judge_attestations([row], unread, run_id="r").status is Status.NOT_CHECKED + other_run = [{**good[0], "run_id": "q"}] + assert judge_attestations([row], other_run, run_id="r").status is not Status.HELD + assert ( + judge_attestations([row], good, run_id="r", complete=False).status + is not Status.HELD + ) From 580d5323aa759b2ba2f49b8ba61e7cf3db0089f0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:03:23 -0500 Subject: [PATCH 11/19] docs(flow): record gui.attestations in CAPABILITIES, the changelog and the fail-closed list --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 6 ++++++ packages/flow/docs/FAIL_CLOSED.md | 2 ++ packages/flow/openadapt_flow/gui/__init__.py | 2 ++ 5 files changed, 12 insertions(+) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index efadedeecc..e778c753f1 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -180,6 +180,7 @@ improvising or retrying when something is off. | 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` | +| Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `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 504fccab0e..028b3ff61f 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -620,6 +620,7 @@ improvising or retrying when something is off. | 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` | +| Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `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 9e11407f7d..1c11422592 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -25,6 +25,12 @@ 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. +- Checkbox attestations (`openadapt_flow.gui.attestations`) are declared in + pack data with the digest of their statement and ticked only on an + `AttestationGrant` from the person who attests. A grant is its own type, so + no intake value or derived fact can tick one. An undeclared box, changed + wording, a missing grant or an attestation bound to a field stops the run + before any box is ticked. - One verdict kernel, `openadapt_flow.verdict`, for every check that turns evidence into held, refuted or not checked. It fixes the obligations from diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index fc9ec70c56..f7cc47c3ab 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -293,6 +293,8 @@ Done: - [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. +- [x] `gui.attestations.judge_attestations` (C1 C2 C5): new. The plan's boxes + are the obligations; a box the plan never saw is unexpected. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py index bbcddd672a..65a3e2124b 100644 --- a/packages/flow/openadapt_flow/gui/__init__.py +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -8,6 +8,8 @@ - :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. +- :mod:`openadapt_flow.gui.attestations`: a checkbox that states something + is ticked only on a person's grant, never through a fact. 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 From 4b9dea53728383b4a667476fae52af48a67b7fd8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:07:35 -0500 Subject: [PATCH 12/19] feat(flow): hub pages of section dialogs, with completion read per section from the hub gui.hub classifies an open dialog by what is in it: one that holds an editable control is a form, never a confirmation, and only a declared section's dialog may be filled. run_section opens a section, fills and saves it, and requires the dialog to close with the demonstrated writes and the card to show done on a fresh read. learn_hub derives each section's opener, dialog, save control and done tokens from a demonstration. judge_hub settles the planned sections and is a registered verdict site. --- packages/flow/openadapt_flow/gui/hub.py | 535 ++++++++++++++++++ packages/flow/tests/failopen/sites/gui_hub.py | 100 ++++ packages/flow/tests/gui/test_gui_hub.py | 381 +++++++++++++ 3 files changed, 1016 insertions(+) create mode 100644 packages/flow/openadapt_flow/gui/hub.py create mode 100644 packages/flow/tests/failopen/sites/gui_hub.py create mode 100644 packages/flow/tests/gui/test_gui_hub.py diff --git a/packages/flow/openadapt_flow/gui/hub.py b/packages/flow/openadapt_flow/gui/hub.py new file mode 100644 index 0000000000..c193d44d85 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/hub.py @@ -0,0 +1,535 @@ +"""Hub pages whose sections open in dialogs, with completion tracked per section. + +Many apps put a long record behind one page of cards or a checklist. A chart +has Allergies, Medications and Vitals. An onboarding page has Company, Billing +and Team. Each section's Edit button opens a dialog, Save closes it, and the +card shows that the section is done. Two things went wrong on such pages +before: + +- the page had no "Next" control, so a wizard walk stopped on the hub; and +- the section dialog was taken for a confirmation modal, which either stops + the run or, worse, gets "confirmed". + +This module treats the hub as its own shape: + +- :func:`classify_dialog` sorts an open dialog by what is in it. A dialog + holding any editable control is a *form* dialog, whatever its words. It is + a declared section's form only when its name matches that section, and + every other form dialog stops the run. Only a dialog with no editable + control can be a confirmation, and that is left to the caller's modal rules. +- :class:`SectionSpec` is pack data for one section: its opener on the hub, + the dialog it opens, the save control in the dialog, the card that shows + its status, and the card tokens that mean done. :func:`learn_hub` derives + them from a demonstration: the tokens the card gained when the section was + saved, minus the values typed in the dialog. +- :func:`run_section` opens one section, lets the caller fill the dialog, and + saves it. It stops if any of these fails: no other dialog may be open, the + card must not already show done, exactly the declared dialog must open, the + dialog must close on save with the demonstrated number of writes, and the + card must then show done on a fresh read of the hub. +- :func:`judge_hub` is a verdict site. Its obligations are the planned + sections, fixed before any is opened, and it settles them against a fresh + read of the hub. Completion is read from the hub, never inferred from + having clicked Save. + +:func:`expected_writes` gives the writes the planned sections should make, so +a caller with a write budget can size it to the sections instead of to one +commit. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from enum import Enum +from typing import Any, Callable, Iterable, Mapping, Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + AmbiguousControl, + ControlSpec, + DemoStep, + Dialog, + MissingControl, + Screen, + match_one, + norm, + spec_for, +) +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Settlement, + Status, + Subject, + settle, +) +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "DialogKind", + "HubVerdict", + "SectionLearned", + "SectionOutcome", + "SectionSpec", + "card_reading", + "card_tokens", + "classify_dialog", + "expected_writes", + "judge_hub", + "judge_hub_screen", + "learn_hub", + "run_section", +] + + +def card_tokens(text: str) -> tuple[str, ...]: + """A card's text as case-folded word tokens; a symbol (a check mark) is + a token of its own.""" + + return tuple(re.findall(r"\w+|[^\w\s]", norm(text))) + + +@dataclass(frozen=True) +class SectionSpec: + """Pack data for one section of a hub. + + ``card`` is the name of the hub container that holds the opener and shows + the section's status. The section is done when the card's tokens include + every ``done_tokens`` entry and none of ``pending_tokens``.""" + + section_id: str + opener: ControlSpec + dialog_name: str + save: ControlSpec + card: str + done_tokens: tuple[str, ...] + pending_tokens: tuple[str, ...] = () + save_writes: int = 1 + required: bool = True + + def __post_init__(self) -> None: + if not self.done_tokens: + raise ValueError( + "a section needs card tokens that show it is done; without " + "them completion cannot be read from the hub" + ) + if self.save_writes < 0: + raise ValueError("save_writes is a count") + if set(self.done_tokens) & set(self.pending_tokens): + raise ValueError("a token cannot mean both done and pending") + + +# -- dialogs ---------------------------------------------------------------------- + + +class DialogKind(str, Enum): + SECTION_FORM = "section_form" + UNDECLARED_FORM = "undeclared_form" + CONFIRMATION = "confirmation" + + +def classify_dialog( + screen: Screen, dialog: Dialog, sections: Sequence[SectionSpec] = () +) -> tuple[DialogKind, Optional[SectionSpec]]: + """What an open dialog is. Any editable control inside makes it a form + dialog, never a confirmation. It is a declared section's form only when + exactly one section names it.""" + + editable = [c for c in screen.in_dialog(dialog.handle) if c.editable] + if not editable: + return DialogKind.CONFIRMATION, None + named = [s for s in sections if norm(s.dialog_name) == norm(dialog.name)] + if len(named) == 1: + return DialogKind.SECTION_FORM, named[0] + return DialogKind.UNDECLARED_FORM, None + + +# -- reading a card --------------------------------------------------------------- + + +@dataclass(frozen=True) +class CardReading: + """What a fresh read of the hub shows for one section's card.""" + + found: bool + done: Optional[bool] + reason: str = "" + + +def card_reading(screen: Screen, section: SectionSpec) -> CardReading: + """Find the section's card through its opener (outside any dialog) and + read whether it shows done.""" + + opener = ControlSpec( + section.opener.role, + section.opener.name, + section.opener.containers, + section.opener.target, + dialog=False, + ) + try: + ctrl = match_one(opener, screen) + except (MissingControl, AmbiguousControl) as exc: + return CardReading(False, None, str(exc)) + cards = [c for c in ctrl.containers if norm(c.name) == norm(section.card)] + if len(cards) != 1: + return CardReading(False, None, f"{len(cards)} cards named {section.card!r}") + tokens = set(card_tokens(cards[0].text)) + if set(section.pending_tokens) & tokens: + return CardReading(True, False, "the card still shows it pending") + if not set(section.done_tokens) <= tokens: + return CardReading(True, False, "the card does not show it done") + return CardReading(True, True) + + +# -- the verdict ------------------------------------------------------------------ + + +@dataclass(frozen=True) +class HubVerdict: + settlement: Settlement + status: Status + + +@verdict_site("gui.hub.judge", classes="C1 C2") +def judge_hub( + planned: Sequence[str], + cards: Sequence[Mapping[str, Any]], + *, + run_id: str, + complete: bool = True, + open_dialogs: int = 0, +) -> HubVerdict: + """Settle the planned sections against a fresh read of the hub. + + ``planned`` is the section ids the run set out to complete, fixed before + any was opened. ``cards`` rows carry ``section_id``, ``found``, ``done`` + and ``run_id``. A section holds only when its card was found and shows + done, on a complete read with no dialog left open. A card that shows it + not done is refuted. One that was not found, or whose state is not a + bool, is not checked. A section nobody planned is unexpected.""" + + obligations = Obligations.fix( + ( + Subject(run_id=run_id, surface="gui", key=str(s), field="section") + for s in planned + ), + source="hub plan", + ) + results = [] + for row in cards: + subject = Subject( + run_id=str(row.get("run_id") or ""), + surface="gui", + key=str(row.get("section_id")), + field="section", + ) + obs = Observed(dict(row), complete=complete is True) + done = row.get("done") + if row.get("found") is not True or not isinstance(done, bool): + results.append(Result.not_checked(subject, "the card was not read")) + elif done is False: + results.append(Result.refuted(subject, obs, "the card does not show done")) + elif complete is not True: + results.append(Result.not_checked(subject, "the hub was read in part")) + elif type(open_dialogs) is not int or open_dialogs != 0: + results.append(Result.not_checked(subject, "a dialog is still open")) + else: + results.append(Result.held(subject, obs, "the card shows done")) + settlement = settle(obligations, results) + status = settlement.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) + seen_wrong = [r for r in results if r.status is Status.REFUTED] + if status is not Status.HELD and seen_wrong: + status = Status.REFUTED + return HubVerdict(settlement, status) + + +def judge_hub_screen( + screen: Screen, + sections: Sequence[SectionSpec], + planned: Iterable[str], + *, + run_id: str, +) -> HubVerdict: + """:func:`judge_hub` on a fresh read of the hub.""" + + planned = list(planned) + rows = [] + for section in sections: + if section.section_id not in planned: + continue + reading = card_reading(screen, section) + rows.append( + { + "section_id": section.section_id, + "found": reading.found, + "done": reading.done, + "run_id": run_id, + } + ) + return judge_hub( + planned, + rows, + run_id=run_id, + complete=screen.complete, + open_dialogs=len(screen.dialogs), + ) + + +def expected_writes(sections: Sequence[SectionSpec], planned: Iterable[str]) -> int: + """Writes the planned sections' saves should make, in total.""" + + wanted = set(planned) + return sum(s.save_writes for s in sections if s.section_id in wanted) + + +# -- running one section ---------------------------------------------------------- + + +@dataclass(frozen=True) +class SectionOutcome: + section_id: str + result: Result + opened: bool = False + saved: bool = False + hub: Optional[Screen] = None + + @property + def held(self) -> bool: + return self.result.status is Status.HELD + + +def run_section( + actuator: Actuator, + section: SectionSpec, + fill: Callable[[Screen, Dialog], None], + *, + sections: Sequence[SectionSpec] = (), + run_id: str = "", +) -> SectionOutcome: + """Open ``section``, let ``fill`` enter its values, save it, and confirm + on the hub that it is done. + + ``fill`` gets the screen with the dialog open and the dialog. It must + act only inside that dialog.""" + + subject = Subject( + run_id=run_id, surface="gui", key=section.section_id, field="section" + ) + sid = section.section_id + + def stop(reason: str, **kw: Any) -> SectionOutcome: + return SectionOutcome(sid, Result.not_checked(subject, reason), **kw) + + hub = actuator.observe() + if hub.dialogs: + return stop("a dialog is already open on the hub") + before = card_reading(hub, section) + if not before.found: + return stop(f"the section's card is not on the hub: {before.reason}") + if before.done: + return stop("the card shows done before the run opened the section") + try: + opener = match_one( + ControlSpec( + section.opener.role, + section.opener.name, + section.opener.containers, + section.opener.target, + dialog=False, + ), + hub, + ) + except (MissingControl, AmbiguousControl) as exc: + return stop(str(exc)) + w0 = actuator.write_count() + if w0 is None: + return stop("this backend cannot count writes; a section save cannot be shown") + actuator.click(opener.handle) + opened = actuator.observe() + if len(opened.dialogs) != 1: + return stop(f"{len(opened.dialogs)} dialogs opened", opened=True) + dialog = opened.dialogs[0] + kind, owner = classify_dialog(opened, dialog, sections or (section,)) + if kind is not DialogKind.SECTION_FORM or owner is None or owner.section_id != sid: + return stop( + f"the dialog that opened is a {kind.value} dialog, not {sid!r}", opened=True + ) + if actuator.write_count() != w0: + return stop("opening the section wrote", opened=True) + fill(opened, dialog) + filled = actuator.observe() + if [d.handle for d in filled.dialogs] != [dialog.handle]: + return stop("the dialog changed while it was filled", opened=True) + try: + save = match_one( + ControlSpec( + section.save.role, + section.save.name, + section.save.containers, + section.save.target, + dialog=True, + ), + filled, + ) + except (MissingControl, AmbiguousControl) as exc: + return stop(str(exc), opened=True) + if save.dialog != dialog.handle: + return stop("the save control is outside the section's dialog", opened=True) + w1 = actuator.write_count() + actuator.click(save.handle) + w2 = actuator.write_count() + after = actuator.observe() + obs = Observed(after, complete=after.complete) + if after.dialogs: + errors = [c.error for c in after.controls if c.error] or list(after.errors) + reason = ( + f"the dialog did not close: {errors[0]}" + if errors + else "the dialog did not close" + ) + return SectionOutcome( + sid, Result.refuted(subject, obs, reason), True, False, after + ) + if w1 is None or w2 is None or w2 - w1 != section.save_writes: + got = "unknown" if w1 is None or w2 is None else w2 - w1 + return SectionOutcome( + sid, + Result.refuted( + subject, + obs, + f"saving wrote {got}; the demo wrote {section.save_writes}", + ), + True, + True, + after, + ) + verdict = judge_hub_screen(after, (section,), [sid], run_id=run_id) + if verdict.status is Status.HELD: + return SectionOutcome( + sid, Result.held(subject, obs, "the card shows done"), True, True, after + ) + reading = card_reading(after, section) + if verdict.status is Status.REFUTED: + return SectionOutcome( + sid, Result.refuted(subject, obs, reading.reason), True, True, after + ) + return SectionOutcome( + sid, + Result.not_checked(subject, reading.reason or "not read"), + True, + True, + after, + ) + + +# -- from a demonstration ---------------------------------------------------------- + + +@dataclass(frozen=True) +class SectionLearned: + """One section found in a demonstration. ``spec`` is None when the card + showed no new token on save (``reason`` says why); the pack author must + then say how the hub shows the section done.""" + + opener_index: int + save_index: int + spec: Optional[SectionSpec] + reason: str = "" + + +def learn_hub(demo: Sequence[DemoStep]) -> tuple[SectionLearned, ...]: + """Find each open, fill, save cycle: a click that opened one form dialog, + then a click inside it that closed it. The card is the opener's innermost + named container. Its done tokens are those it gained on save, less any + token of a value typed in the dialog; its pending tokens are those it lost.""" + + out = [] + i = 0 + while i < len(demo): + step = demo[i] + new = [ + d + for d in step.after.dialogs + if d.handle not in {x.handle for x in step.before.dialogs} + ] + if step.action != "click" or step.target.dialog or len(new) != 1: + i += 1 + continue + dialog = new[0] + typed: set[str] = set() + j = i + 1 + closed_by: Optional[int] = None + while j < len(demo) and demo[j].target.dialog == dialog.handle: + if demo[j].value: + typed |= set(card_tokens(demo[j].value)) + if demo[j].action == "click" and dialog.handle not in { + d.handle for d in demo[j].after.dialogs + }: + closed_by = j + break + j += 1 + if closed_by is None: + # The dialog was left some other way (or never closed): not a + # section cycle the demo showed whole. + i = j + continue + out.append(_learned(step, demo[closed_by], dialog, typed, i, closed_by)) + i = closed_by + 1 + return tuple(out) + + +def _learned( + open_step: DemoStep, + save_step: DemoStep, + dialog: Dialog, + typed: set[str], + i: int, + j: int, +) -> SectionLearned: + opener = open_step.target + named = [c for c in opener.containers if c.name and c.kind != "dialog"] + if not named: + return SectionLearned(i, j, None, "the opener sits in no named card") + card = named[-1] + after_ctrl = save_step.after.control(opener.handle) + after_card = None + if after_ctrl is not None: + after_card = next( + (c for c in after_ctrl.containers if c.handle == card.handle), None + ) + if after_card is None: + return SectionLearned(i, j, None, "the card was not on the hub after saving") + before_t, after_t = set(card_tokens(card.text)), set(card_tokens(after_card.text)) + done = tuple(sorted(after_t - before_t - typed)) + pending = tuple(sorted(before_t - after_t - typed)) + open_spec = spec_for(opener, open_step.before) + save_spec = spec_for(save_step.target, save_step.before) + if not done: + return SectionLearned( + i, j, None, "the card gained no token when the section was saved" + ) + if open_spec is None or save_spec is None: + return SectionLearned( + i, j, None, "the opener or the save control is not unique" + ) + if save_step.writes is None: + return SectionLearned( + i, j, None, "the backend could not count the save's writes" + ) + return SectionLearned( + i, + j, + SectionSpec( + section_id=norm(card.name).replace(" ", "_"), + opener=open_spec, + dialog_name=dialog.name, + save=save_spec, + card=card.name, + done_tokens=done, + pending_tokens=pending, + save_writes=save_step.writes, + ), + ) diff --git a/packages/flow/tests/failopen/sites/gui_hub.py b/packages/flow/tests/failopen/sites/gui_hub.py new file mode 100644 index 0000000000..5a7e1951ab --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_hub.py @@ -0,0 +1,100 @@ +"""gui.hub.judge (C1 C2): every planned section's card shows done on a fresh +read of the hub, with no dialog left open. + +The obligations are the sections the run planned before opening any. A card +that shows not done is refuted; one that was not found or not read is not +checked; a section nobody planned is unexpected; an empty plan never passes. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.gui.hub import judge_hub +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +RUN = "run-1" + + +def _card(sid: str, done: Any = True, found: Any = True) -> dict[str, Any]: + return {"section_id": sid, "found": found, "done": done, "run_id": RUN} + + +def _good() -> dict[str, Any]: + return { + "planned": ["allergies", "medications"], + "cards": [_card("allergies"), _card("medications")], + "complete": True, + "open_dialogs": 0, + } + + +def _run(ev: dict[str, Any]) -> Any: + return judge_hub( + ev["planned"], + ev["cards"], + run_id=RUN, + complete=ev.get("complete"), + open_dialogs=ev.get("open_dialogs"), + ) + + +def _bad(item: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(item) + out["done"] = False + return out + + +def _inflate(ev: dict[str, Any], n: int) -> dict[str, Any]: + planned = [f"s{i}" for i in range(n)] + cards = [_card(f"s{i}", done=i != n - 1) for i in range(n)] + return {**ev, "planned": planned, "cards": cards} + + +register( + SiteSpec( + id="gui.hub.judge", + classes="C1 C2", + target="openadapt_flow.gui.hub:judge_hub", + run=_run, + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_good(), True), + Seed( + { + **_good(), + "cards": [_card("allergies"), _card("medications", done=False)], + }, + False, + "one card not done", + ), + Seed( + {**_good(), "cards": [_card("allergies")]}, + False, + "a planned section with no card", + ), + Seed({**_good(), "open_dialogs": 1}, False, "a dialog left open"), + Seed( + {**_good(), "cards": _good()["cards"] + [_card("vitals")]}, + False, + "a section nobody planned", + ), + ], + items=key("cards"), + plan=key("planned"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("cards"), 0), + values=( + key("done", "cards", 0), + key("found", "cards", 0), + key("section_id", "cards", 0), + key("open_dialogs"), + ), + subject=key("run_id", "cards", 0), + partial=lambda ev: [("complete", {**ev, "complete": False})], + ) +) diff --git a/packages/flow/tests/gui/test_gui_hub.py b/packages/flow/tests/gui/test_gui_hub.py new file mode 100644 index 0000000000..56c6878059 --- /dev/null +++ b/packages/flow/tests/gui/test_gui_hub.py @@ -0,0 +1,381 @@ +"""Hub pages of section dialogs on three kinds of app. + +- an EMR-like chart hub (Allergies, Medications) whose cards open dialogs; +- a SaaS onboarding checklist, where a dialog that says "Confirm" but holds a + field is a form, not a confirmation; +- a desktop preferences window read as an accessibility tree, no browser. + +Sections are learned from one demonstration and replayed with other values. +Completion is read from the hub after each save, never assumed. +""" + +from __future__ import annotations + +from typing import Any, Optional + +import pytest + +from openadapt_flow.gui.adapters import screen_from_tree +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.hub import ( + DialogKind, + SectionSpec, + classify_dialog, + expected_writes, + judge_hub, + judge_hub_screen, + learn_hub, + run_section, +) +from openadapt_flow.gui.model import ControlSpec, Recorder, Screen, match_one +from openadapt_flow.verdict import Status +from tests.gui import _apps + +# -- an EMR-like chart hub --------------------------------------------------------- + +CHART_JS = """ +function openS(id){document.getElementById('dlg-'+id).hidden=false;} +function saveS(id, field){ + const v=document.getElementById(field).value; + if(!v){document.getElementById('err-'+id).textContent='Enter a value'; + document.getElementById(field).setAttribute('aria-invalid','true');return;} + fetch('/save/'+id,{method:'POST',body:JSON.stringify({v:v})}).then(r=>r.json()).then(j=>{ + if(j.ok){document.getElementById('st-'+id).textContent=j.status; + document.getElementById('dlg-'+id).hidden=true;}}); +}""" + + +def _card( + sid: str, title: str, field: str, status: str, dialog_name: Optional[str] = None +) -> str: + return f"""

{title}

+

{status}

+""" + + +def chart_hub( + *, + ignore_saves: bool = False, + allergies_status: str = "Not reviewed", + allergy_dialog: Optional[str] = None, +) -> _apps.App: + def hub(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Chart", + "

Chart: Test Patient C

" + + _card("al", "Allergies", "Allergy", allergies_status, allergy_dialog) + + _card("md", "Medications", "Medication", "Not reviewed") + + "" + + f"
", + ) + + def save(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + sid = path.rsplit("/", 1)[1] + if ignore_saves: + return 200, '{"ok": true, "status": "Not reviewed"}' + app.state[sid] = f["v"][0] + return 200, '{"ok": true, "status": "Reviewed \\u2713 ' + f["v"][0] + '"}' + + return _apps.App( + "chart.test", + { + ("GET", "/chart"): hub, + ("POST", "/save/al"): save, + ("POST", "/save/md"): save, + ("POST", "/sign"): lambda a, p, m, f: (200, "{}"), + }, + ) + + +def _fill_with(value: str): + def fill(screen: Screen, dialog: Any) -> None: + (field,) = [c for c in screen.in_dialog(dialog.handle) if c.editable] + ACT[0].set_text(field.handle, value) + + return fill + + +ACT: list[Any] = [] + + +def _record_chart(page: Any, app: _apps.App) -> list: + act = PageActuator(page) + page.goto(f"{app.origin}/chart") + rec = Recorder(act) + for title, field, value in ( + ("Allergies", "Allergy", "Penicillin"), + ("Medications", "Medication", "Drug D 5 mg"), + ): + rec.click( + match_one( + ControlSpec("button", f"Edit {title.lower()}"), act.observe() + ).handle + ) + s = act.observe() + rec.set_text( + match_one(ControlSpec("textbox", field, dialog=True), s).handle, value + ) + rec.click( + match_one(ControlSpec("button", "Save", dialog=True), act.observe()).handle + ) + return rec.steps + + +def _learned_chart(page: Any) -> list[SectionSpec]: + with _apps.serve(page, chart_hub()) as app: + learned = learn_hub(_record_chart(page, app)) + assert all(s.spec is not None for s in learned), [s.reason for s in learned] + return [s.spec for s in learned] # type: ignore[misc] + + +def test_emr_hub_sections_are_learned_from_the_card_tokens(page) -> None: + specs = _learned_chart(page) + assert [(s.section_id, s.card, s.dialog_name) for s in specs] == [ + ("allergies", "Allergies", "Allergies"), + ("medications", "Medications", "Medications"), + ] + # "Reviewed" was on the card before and after; the typed value is not a + # done token. What the card gained is the check mark; it lost "not". + assert specs[0].done_tokens == ("✓",) + assert specs[0].pending_tokens == ("not",) + assert specs[0].save_writes == 1 + assert expected_writes(specs, ["allergies", "medications"]) == 2 + + +def test_emr_hub_replays_each_section_and_reads_completion_from_the_hub(page) -> None: + specs = _learned_chart(page) + app = chart_hub() + with _apps.serve(page, app): + act = PageActuator(page) + ACT[:] = [act] + page.goto(f"{app.origin}/chart") + before = judge_hub_screen( + act.observe(), specs, ["allergies", "medications"], run_id="r1" + ) + assert before.status is Status.REFUTED + for spec, value in zip(specs, ("Latex", "Drug E 2 mg")): + out = run_section(act, spec, _fill_with(value), sections=specs, run_id="r1") + assert out.held, out.result.reason + verdict = judge_hub_screen( + act.observe(), specs, ["allergies", "medications"], run_id="r1" + ) + assert verdict.status is Status.HELD + assert app.state == {"al": "Latex", "md": "Drug E 2 mg"} + + +@pytest.mark.parametrize( + ("variant", "value", "status", "reason"), + [ + ({"ignore_saves": True}, "Latex", Status.REFUTED, "still shows it pending"), + ({}, "", Status.REFUTED, "did not close: Enter a value"), + ( + {"allergies_status": "Reviewed ✓ Sulfa"}, + "Latex", + Status.NOT_CHECKED, + "before the run opened", + ), + ( + {"allergy_dialog": "Allergy history import"}, + "Latex", + Status.NOT_CHECKED, + "undeclared_form", + ), + ], +) +def test_emr_hub_section_that_does_not_complete_stops( + page, variant, value, status, reason +) -> None: + specs = _learned_chart(page) + app = chart_hub(**variant) + with _apps.serve(page, app): + act = PageActuator(page) + ACT[:] = [act] + page.goto(f"{app.origin}/chart") + out = run_section(act, specs[0], _fill_with(value), sections=specs, run_id="r2") + assert out.result.status is status and reason in out.result.reason + + +# -- SaaS onboarding checklist: form dialogs are never confirmations ----------------- + + +def onboarding() -> _apps.App: + def hub(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Get started", + """

Get started

    +
  • Company profile

    To do +Set up
+ + + +
""", + ) + + def co(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + app.state["company"] = f["cn"][0] + return 200, "{}" + + return _apps.App("app.test", {("GET", "/start"): hub, ("POST", "/co"): co}) + + +def test_saas_dialog_with_a_field_is_a_form_even_when_it_says_confirm(page) -> None: + section = SectionSpec( + "company", + ControlSpec("button", "Set up", ("Company profile",)), + "Company profile", + ControlSpec("button", "Confirm", ("Company profile",)), + card="Company profile", + done_tokens=("done",), + pending_tokens=("to",), + ) + app = onboarding() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/start") + for dlg, kind in ( + ("d2", DialogKind.UNDECLARED_FORM), + ("d3", DialogKind.CONFIRMATION), + ): + page.evaluate(f"{dlg}.hidden=false") + screen = act.observe() + (dialog,) = screen.dialogs + assert classify_dialog(screen, dialog, [section])[0] is kind + page.evaluate(f"{dlg}.hidden=true") + ACT[:] = [act] + out = run_section(act, section, _fill_with("Acme Test Co"), run_id="r3") + assert out.held, out.result.reason + assert app.state["company"] == "Acme Test Co" + + +# -- desktop preferences window, read as an accessibility tree ----------------------- + + +class Prefs: + """A native preferences window: each group shows a status and opens a + dialog whose OK button saves.""" + + def __init__(self, *, ok_saves: bool = True) -> None: + self.status = {"Account": "Not set", "Proxy": "Not set"} + self.values: dict[str, str] = {} + self.open: Optional[str] = None + self.draft = "" + self.writes = 0 + self.ok_saves = ok_saves + + def tree(self) -> dict[str, Any]: + groups = [ + { + "role": "group", + "name": g, + "handle": f"grp:{g}", + "text": f"{g} {self.status[g]}", + "children": [ + {"role": "push button", "name": "Change", "handle": f"chg:{g}"} + ], + } + for g in self.status + ] + if self.open: + groups.append( + { + "role": "dialog", + "name": f"{self.open} settings", + "handle": "dlg", + "children": [ + { + "role": "edit", + "name": "Value", + "value": self.draft, + "handle": "dlg:val", + }, + {"role": "push button", "name": "OK", "handle": "dlg:ok"}, + ], + } + ) + return {"role": "window", "name": "Preferences", "children": groups} + + def observe(self) -> Screen: + return screen_from_tree(self.tree(), location="prefs") + + def click(self, handle: str) -> None: + if handle.startswith("chg:"): + self.open, self.draft = handle[4:], "" + elif handle == "dlg:ok" and self.open: + if self.ok_saves: + self.values[self.open] = self.draft + self.status[self.open] = "Configured" + self.writes += 1 + self.open = None + + def set_text(self, handle: str, value: str) -> None: + self.draft = value + + def set_checked(self, handle: str, checked: bool) -> None: + raise KeyError(handle) + + def write_count(self) -> Optional[int]: + return self.writes + + +def _record_prefs() -> list[SectionSpec]: + app = Prefs() + rec = Recorder(app) + for group, value in (("Account", "tester"), ("Proxy", "proxy.example.test:3128")): + rec.click(f"chg:{group}") + rec.set_text("dlg:val", value) + rec.click("dlg:ok") + learned = learn_hub(rec.steps) + assert all(s.spec for s in learned), [s.reason for s in learned] + return [s.spec for s in learned] # type: ignore[misc] + + +def test_desktop_prefs_hub_learns_and_replays_without_a_browser() -> None: + specs = _record_prefs() + assert [(s.card, s.done_tokens, s.pending_tokens) for s in specs] == [ + ("Account", ("configured",), ("not", "set")), + ("Proxy", ("configured",), ("not", "set")), + ] + app = Prefs() + + def fill(value: str): + return lambda screen, dialog: app.set_text("dlg:val", value) + + for spec, value in zip(specs, ("other", "proxy2.example.test:8080")): + assert run_section(app, spec, fill(value), sections=specs, run_id="d1").held + assert ( + judge_hub_screen(app.observe(), specs, ["account", "proxy"], run_id="d1").status + is Status.HELD + ) + + +def test_desktop_prefs_ok_that_saves_nothing_is_refuted() -> None: + specs = _record_prefs() + app = Prefs(ok_saves=False) + out = run_section( + app, specs[0], lambda s, d: app.set_text("dlg:val", "x"), sections=specs + ) + assert out.result.status is Status.REFUTED and "saving wrote 0" in out.result.reason + + +def test_judge_hub_never_passes_empty_unread_or_unplanned() -> None: + row = {"section_id": "a", "found": True, "done": True, "run_id": "r"} + assert judge_hub(["a"], [row], run_id="r").status is Status.HELD + assert judge_hub([], [], run_id="r").status is not Status.HELD + assert ( + judge_hub(["a"], [row, {**row, "section_id": "b"}], run_id="r").status + is not Status.HELD + ) + assert ( + judge_hub(["a"], [{**row, "found": False}], run_id="r").status + is Status.NOT_CHECKED + ) + assert judge_hub(["a"], [row], run_id="r", open_dialogs=1).status is not Status.HELD + assert judge_hub(["a", "b"], [row], run_id="r").status is not Status.HELD From a0646e16bf0607e9dddeb3b0e88e973d1429933d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:08:05 -0500 Subject: [PATCH 13/19] docs(flow): record gui.hub in CAPABILITIES, the changelog and the fail-closed list --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 4 ++++ packages/flow/docs/FAIL_CLOSED.md | 2 ++ packages/flow/openadapt_flow/gui/__init__.py | 2 ++ 5 files changed, 10 insertions(+) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index e778c753f1..b06c89583b 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -181,6 +181,7 @@ improvising or retrying when something is off. | 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` | | Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `packages/flow/tests/gui` | +| Hub pages whose sections open in dialogs: a dialog holding any editable control is a form, never a confirmation; each section's completion is read from its card on the hub after save, with the demonstrated writes, never assumed from the click | On main ([#2502](https://github.com/OpenAdaptAI/OpenAdapt/pull/2502)) | Synthetic: an EMR-like chart hub, a SaaS onboarding checklist (headless Chromium) and a desktop preferences window read as an accessibility tree | `openadapt_flow.gui.hub`, `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 028b3ff61f..ca47ba8c04 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -621,6 +621,7 @@ improvising or retrying when something is off. | 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` | | Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `packages/flow/tests/gui` | +| Hub pages whose sections open in dialogs: a dialog holding any editable control is a form, never a confirmation; each section's completion is read from its card on the hub after save, with the demonstrated writes, never assumed from the click | On main ([#2502](https://github.com/OpenAdaptAI/OpenAdapt/pull/2502)) | Synthetic: an EMR-like chart hub, a SaaS onboarding checklist (headless Chromium) and a desktop preferences window read as an accessibility tree | `openadapt_flow.gui.hub`, `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 1c11422592..7f4c25e4fe 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -31,6 +31,10 @@ no intake value or derived fact can tick one. An undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before any box is ticked. +- Hub pages of section dialogs (`openadapt_flow.gui.hub`). A dialog holding + an editable control is a form, never a confirmation. Each section is opened, + filled and saved, and its completion is read from its card on the hub after + the save, with the demonstrated number of writes. - One verdict kernel, `openadapt_flow.verdict`, for every check that turns evidence into held, refuted or not checked. It fixes the obligations from diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index f7cc47c3ab..220d4c2f5d 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -295,6 +295,8 @@ Done: the demonstrated writes; an unlisted step role is not checked. - [x] `gui.attestations.judge_attestations` (C1 C2 C5): new. The plan's boxes are the obligations; a box the plan never saw is unexpected. +- [x] `gui.hub.judge_hub` (C1 C2): new. The planned sections are the + obligations; completion is read from the hub, never from the save click. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py index 65a3e2124b..64bcd04108 100644 --- a/packages/flow/openadapt_flow/gui/__init__.py +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -10,6 +10,8 @@ and the step that commits is the one the demonstration showed writing. - :mod:`openadapt_flow.gui.attestations`: a checkbox that states something is ticked only on a person's grant, never through a fact. +- :mod:`openadapt_flow.gui.hub`: a hub page whose sections open in dialogs, + each section's completion read back from the hub. 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 From 4b144a1c7c5e3d61d466aa26d682aec1873895c6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:46:51 -0500 Subject: [PATCH 14/19] feat(flow): repeating structures learned from the demo, added to match the intake and checked per instance gui.repeating learns an add-another group from a demonstration (the add control, the instance's container kind and its fields), adds instances until the count matches the intake, fills them in document order and reads each one back by the container it was written into. It stops before writing on a prefilled instance, more instances than items, an add that did not add exactly one blank instance, or an add that wrote. judge_instances is a registered verdict site; location_rows exports the checks in the effect-location shape. --- packages/flow/openadapt_flow/gui/repeating.py | 592 ++++++++++++++++++ .../tests/failopen/sites/gui_repeating.py | 145 +++++ packages/flow/tests/gui/test_gui_repeating.py | 398 ++++++++++++ 3 files changed, 1135 insertions(+) create mode 100644 packages/flow/openadapt_flow/gui/repeating.py create mode 100644 packages/flow/tests/failopen/sites/gui_repeating.py create mode 100644 packages/flow/tests/gui/test_gui_repeating.py diff --git a/packages/flow/openadapt_flow/gui/repeating.py b/packages/flow/openadapt_flow/gui/repeating.py new file mode 100644 index 0000000000..39938b105c --- /dev/null +++ b/packages/flow/openadapt_flow/gui/repeating.py @@ -0,0 +1,592 @@ +"""Repeating structures: "add another traveller", "add a row", "add a line item". + +A form that asks for a list shows one instance of a block of fields (a +traveller, a medication row, an invoice line) and a control that adds +another. A run whose intake has three items must add instances until there +are three, fill each one with its own item, and check each one. Packs used to +work around this with a stop or a popup that cannot exist. This module +handles it once: + +- :func:`learn_repeats` finds the shape in a demonstration. It looks for a + click after which a new block of editable controls appeared inside a new + container of one kind (a fieldset, a row, a list item). When the block + repeats the fields of an instance already on the screen, that is the group + (a list that starts empty is learned from its second add). + It yields a :class:`RepeatSpec`: the add control, the instance's container + kind and its field slots. :func:`map_slots` proposes which item key feeds + each slot, from the values the demonstration typed. +- :func:`find_instances` reads the instances on a screen: each container of + the declared kind that holds exactly one control per slot, in document + order. A slot control outside any instance, or an instance with a missing + or doubled slot, makes the read unusable. +- :func:`fill_instances` fixes the obligations from the intake first (every + item, every slot). It then adds instances until the count matches, fills + them in document order and reads them back. It stops before writing when: + - an instance already holds data the run did not enter; + - the screen already has more instances than the intake (the run never + deletes one); + - the add control is missing or ambiguous, or one click did not add exactly + one blank instance; + - adding wrote anything; + - an item lacks a slot's key. +- :func:`judge_instances` is a verdict site. It settles item-by-slot + obligations against a fresh read, keyed by the instance each item was + written into (its container handle, bound when it was filled, never a + position guess). A wrong value is refuted, an instance nobody planned is + unexpected and refuted, and a missing instance is missing. + +:func:`location_rows` exports the per-instance checks as plain rows shaped +like the effect-location record (``openadapt.effect-location/v1``), so the +shared verifier layer can take them over without this module importing it. +""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + AmbiguousControl, + Container, + Control, + ControlSpec, + DemoStep, + MissingControl, + Screen, + match_one, + norm, + spec_for, +) +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Settlement, + Status, + Subject, + settle, +) +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "Instance", + "InstanceRead", + "RepeatSpec", + "RepeatVerdict", + "Slot", + "FillOutcome", + "fill_instances", + "find_instances", + "judge_instances", + "learn_repeats", + "location_rows", + "map_slots", + "planned_rows", + "seen_rows", +] + +#: Container kinds an instance can be. +INSTANCE_KINDS = frozenset({"group", "region", "row", "item"}) + + +@dataclass(frozen=True) +class Slot: + """One field of an instance, and the item key that feeds it ("" until + the pack author or :func:`map_slots` sets it).""" + + role: str + name: str + item_key: str = "" + + +@dataclass(frozen=True) +class RepeatSpec: + """Pack data for one repeating group. + + ``within`` names containers the whole group sits in, to tell two groups + with the same fields apart. ``add_writes`` is how many writes one add made + in the demonstration (usually 0).""" + + group_id: str + add: ControlSpec + instance_kind: str + slots: tuple[Slot, ...] + within: tuple[str, ...] = () + add_writes: int = 0 + max_instances: int = 50 + + def __post_init__(self) -> None: + if self.instance_kind not in INSTANCE_KINDS: + raise ValueError(f"unknown instance kind {self.instance_kind!r}") + if not self.slots: + raise ValueError("a repeating group has at least one field") + keys = [(s.role, norm(s.name)) for s in self.slots] + if len(keys) != len(set(keys)): + raise ValueError("two slots have the same role and name") + + +# -- reading instances ---------------------------------------------------------- + + +@dataclass(frozen=True) +class Instance: + handle: str + name: str + #: The control for each slot, in slot order. + controls: tuple[Control, ...] + + def values(self) -> tuple[str, ...]: + return tuple(_shown(c) for c in self.controls) + + def blank(self) -> bool: + return all(not v or v == "false" for v in self.values()) + + +@dataclass(frozen=True) +class InstanceRead: + instances: tuple[Instance, ...] + problem: str = "" + + @property + def usable(self) -> bool: + return not self.problem + + +def _shown(ctrl: Control) -> str: + if ctrl.role in ("checkbox", "switch", "radio"): + return "true" if ctrl.checked else "false" + return ctrl.value.strip() + + +def _slot_of(spec: RepeatSpec, ctrl: Control) -> Optional[int]: + for n, slot in enumerate(spec.slots): + if ctrl.role == slot.role and norm(ctrl.name) == norm(slot.name): + return n + return None + + +def _in_scope(spec: RepeatSpec, ctrl: Control) -> bool: + names = ctrl.container_names() + at = 0 + for name in names: + if at < len(spec.within) and name == norm(spec.within[at]): + at += 1 + return at == len(spec.within) + + +def _instance_box(spec: RepeatSpec, ctrl: Control) -> Optional[Container]: + boxes = [c for c in ctrl.containers if c.kind == spec.instance_kind] + return boxes[-1] if boxes else None + + +def find_instances(screen: Screen, spec: RepeatSpec) -> InstanceRead: + """The group's instances on ``screen``, in document order.""" + + order: list[str] = [] + by_box: dict[str, dict[int, list[Control]]] = {} + names: dict[str, str] = {} + for ctrl in screen.controls: + slot = _slot_of(spec, ctrl) + if slot is None or not _in_scope(spec, ctrl) or ctrl.dialog: + continue + box = _instance_box(spec, ctrl) + if box is None: + return InstanceRead((), f"{ctrl.name!r} sits in no {spec.instance_kind}") + if box.handle not in by_box: + order.append(box.handle) + by_box[box.handle] = {} + names[box.handle] = box.name + by_box[box.handle].setdefault(slot, []).append(ctrl) + out = [] + for handle in order: + slots = by_box[handle] + if sorted(slots) != list(range(len(spec.slots))) or any( + len(v) != 1 for v in slots.values() + ): + return InstanceRead( + (), + f"instance {names[handle] or handle!r} does not hold each field once", + ) + out.append( + Instance( + handle, + names[handle], + tuple(slots[n][0] for n in range(len(spec.slots))), + ) + ) + if not screen.complete: + return InstanceRead(tuple(out), "the screen was read in part") + return InstanceRead(tuple(out)) + + +# -- the verdict ------------------------------------------------------------------ + + +@dataclass(frozen=True) +class RepeatVerdict: + settlement: Settlement + status: Status + + +@verdict_site("gui.repeating.judge", classes="C1 C2 C5") +def judge_instances( + planned: Sequence[Mapping[str, Any]], + bound: Mapping[str, str], + seen: Sequence[Mapping[str, Any]], + *, + run_id: str, + complete: bool = True, +) -> RepeatVerdict: + """Settle item-by-slot obligations against a fresh read. + + ``planned`` rows carry ``item`` (the item's index as text), ``slot`` and + ``expected``, one per item and slot, fixed from the intake before any + instance was added. ``bound`` maps each item to the container handle it + was written into. ``seen`` rows carry ``handle``, ``slot``, ``value`` and + ``run_id``, one per slot of every instance on the screen. A value must + equal the expected text exactly. An instance no item was bound to is + refuted and unexpected; a value that is not text is not checked.""" + + obligations = Obligations.fix( + ( + Subject( + run_id=run_id, + surface="gui", + key=str(p.get("item")), + field=str(p.get("slot")), + ) + for p in planned + ), + source="intake items", + ) + expected = { + (str(p.get("item")), str(p.get("slot"))): p.get("expected") for p in planned + } + item_of = {str(h): str(i) for i, h in bound.items()} + if len(item_of) != len(bound): + item_of = {} # two items bound to one instance: nothing can settle + results = [] + for row in seen: + handle, slot = str(row.get("handle")), str(row.get("slot")) + item = item_of.get(handle) + subject = Subject( + run_id=str(row.get("run_id") or ""), + surface="gui", + key=item if item is not None else f"unplanned:{handle}", + field=slot, + ) + obs = Observed(dict(row), complete=complete is True) + value = row.get("value") + want = expected.get((item, slot)) if item is not None else None + if item is None: + results.append( + Result.refuted(subject, obs, "an instance no item was written into") + ) + elif not isinstance(value, str) or not isinstance(want, str): + results.append( + Result.not_checked(subject, "the value was not read as text") + ) + elif value != want: + results.append( + Result.refuted(subject, obs, f"shows {value!r}, the item has {want!r}") + ) + elif complete is not True: + results.append(Result.not_checked(subject, "the screen was read in part")) + else: + results.append(Result.held(subject, obs, "as entered")) + settlement = settle(obligations, results) + status = settlement.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) + seen_wrong = [r for r in results if r.status is Status.REFUTED] + if status is not Status.HELD and seen_wrong: + status = Status.REFUTED + return RepeatVerdict(settlement, status) + + +def _item_text(item: Mapping[str, Any], slot: Slot) -> Optional[str]: + if slot.item_key not in item: + return None + value = item[slot.item_key] + if slot.role in ("checkbox", "switch"): + if not isinstance(value, bool): + return None + return "true" if value else "false" + if value is None or isinstance(value, bool): + return None + return str(value).strip() + + +def planned_rows( + spec: RepeatSpec, items: Sequence[Mapping[str, Any]] +) -> list[dict[str, Any]]: + return [ + {"item": str(i), "slot": slot.name, "expected": _item_text(item, slot)} + for i, item in enumerate(items) + for slot in spec.slots + ] + + +def seen_rows( + read: InstanceRead, spec: RepeatSpec, run_id: str +) -> list[dict[str, Any]]: + return [ + {"handle": inst.handle, "slot": slot.name, "value": value, "run_id": run_id} + for inst in read.instances + for slot, value in zip(spec.slots, inst.values()) + ] + + +# -- filling ---------------------------------------------------------------------- + + +@dataclass(frozen=True) +class FillOutcome: + group_id: str + status: Status + reason: str + #: Item index (as text) to the container handle it was written into. + bound: Mapping[str, str] + added: int = 0 + wrote: bool = False + verdict: Optional[RepeatVerdict] = None + + @property + def held(self) -> bool: + return self.status is Status.HELD + + +def fill_instances( + actuator: Actuator, + spec: RepeatSpec, + items: Sequence[Mapping[str, Any]], + *, + run_id: str = "", +) -> FillOutcome: + """Add, fill and check one instance per item (see the module doc).""" + + gid = spec.group_id + + def stop(reason: str, **kw: Any) -> FillOutcome: + return FillOutcome(gid, Status.NOT_CHECKED, reason, kw.pop("bound", {}), **kw) + + planned = planned_rows(spec, items) + missing = [p for p in planned if p["expected"] is None] + if missing: + return stop( + f"item {missing[0]['item']} has no usable value for {missing[0]['slot']!r}" + ) + if len(items) > spec.max_instances: + return stop(f"{len(items)} items is more than the group's {spec.max_instances}") + read = find_instances(actuator.observe(), spec) + if not read.usable: + return stop(read.problem) + if any(not inst.blank() for inst in read.instances): + return stop("an instance already holds data the run did not enter") + if len(read.instances) > len(items): + return stop( + f"the screen shows {len(read.instances)} instances for {len(items)} items; " + "the run never deletes one" + ) + added = 0 + while len(read.instances) < len(items): + try: + add = match_one(spec.add, actuator.observe()) + except (MissingControl, AmbiguousControl) as exc: + return stop(str(exc), added=added) + w0 = actuator.write_count() + actuator.click(add.handle) + w1 = actuator.write_count() + added += 1 + if w0 is None or w1 is None: + return stop( + "this backend cannot count writes, so an add cannot be shown safe", + added=added, + ) + if w1 - w0 != spec.add_writes: + return stop( + f"adding an instance wrote {w1 - w0} times; the demo wrote {spec.add_writes}", + added=added, + wrote=True, + ) + after = find_instances(actuator.observe(), spec) + if not after.usable: + return stop(after.problem, added=added) + old = {i.handle for i in read.instances} + new = [i for i in after.instances if i.handle not in old] + if len(after.instances) != len(read.instances) + 1 or len(new) != 1: + return stop( + f"one add went from {len(read.instances)} to {len(after.instances)} instances", + added=added, + ) + if not new[0].blank(): + return stop("the added instance is not blank", added=added) + read = after + bound = {str(i): inst.handle for i, inst in enumerate(read.instances)} + for i, inst in enumerate(read.instances): + for slot, ctrl in zip(spec.slots, inst.controls): + value = _item_text(items[i], slot) + assert value is not None # checked above + if slot.role in ("checkbox", "switch"): + actuator.set_checked(ctrl.handle, value == "true") + else: + actuator.set_text(ctrl.handle, value) + final = find_instances(actuator.observe(), spec) + if not final.usable: + return FillOutcome(gid, Status.NOT_CHECKED, final.problem, bound, added, True) + verdict = judge_instances( + planned, bound, seen_rows(final, spec, run_id), run_id=run_id, complete=True + ) + reason = ( + "every instance shows its item" + if verdict.status is Status.HELD + else ("an instance does not show its item") + ) + return FillOutcome(gid, verdict.status, reason, bound, added, True, verdict) + + +def location_rows( + spec: RepeatSpec, items: Sequence[Mapping[str, Any]], bound: Mapping[str, str] +) -> list[dict[str, Any]]: + """The per-instance checks as rows shaped like effect locations: one per + item and slot, found by the instance's container and the slot's name, + expected once, read on the same screen.""" + + return [ + { + "id": f"{spec.group_id}:{i}:{slot.name}", + "keys": [f"{spec.group_id}[{i}].{slot.item_key}"], + "start": "same_screen", + "locator": {"kind": "region", "value": bound[str(i)], "column": slot.name}, + "expected": { + f"{spec.group_id}[{i}].{slot.item_key}": _item_text(item, slot) + }, + "expected_count": 1, + } + for i, item in enumerate(items) + if str(i) in bound + for slot in spec.slots + ] + + +# -- from a demonstration ---------------------------------------------------------- + + +def _common_box(ctrls: Sequence[Control]) -> Optional[Container]: + """The innermost container every control shares.""" + + if not ctrls: + return None + shared = list(ctrls[0].containers) + for ctrl in ctrls[1:]: + handles = [c.handle for c in ctrl.containers] + shared = [c for c in shared if c.handle in handles] + return shared[-1] if shared else None + + +def learn_repeats(demo: Sequence[DemoStep]) -> tuple[RepeatSpec, ...]: + """Each click that added a block of editable controls in a new container, + where the block's fields (role and name) match the fields of a container of + the same kind already on the screen. A list that starts empty is learned + from its second add, when the first added block is the sibling.""" + + out: list[RepeatSpec] = [] + for index, step in enumerate(demo): + if step.action != "click" or not step.target.activatable: + continue + before = {c.handle for c in step.before.controls} + new = [c for c in step.after.controls if c.editable and c.handle not in before] + if not new: + continue + box = _common_box(new) + if box is None or box.kind not in INSTANCE_KINDS: + continue + if box.handle in {b.handle for c in step.before.controls for b in c.containers}: + continue # the controls appeared inside an existing container + fields = Counter((c.role, norm(c.name)) for c in new) + if any(n != 1 for n in fields.values()): + continue + siblings: dict[str, Counter[tuple[str, str]]] = {} + for ctrl in step.before.controls: + if not ctrl.editable: + continue + kin = [b for b in ctrl.containers if b.kind == box.kind] + if kin: + siblings.setdefault(kin[-1].handle, Counter())[ + (ctrl.role, norm(ctrl.name)) + ] += 1 + if not any(sig == fields for sig in siblings.values()): + continue + add = spec_for(step.target, step.before) + if add is None or step.writes is None: + continue + slots = tuple(Slot(c.role, c.name) for c in new) + out.append( + RepeatSpec( + group_id=f"group-{index}", + add=add, + instance_kind=box.kind, + slots=slots, + add_writes=step.writes, + ) + ) + seen: set[tuple[Any, ...]] = set() + unique = [] + for spec in out: + key = (spec.add, spec.instance_kind, spec.slots) + if key not in seen: + seen.add(key) + unique.append(spec) + return tuple(unique) + + +def map_slots( + spec: RepeatSpec, + demo: Sequence[DemoStep], + items: Sequence[Mapping[str, Any]], +) -> tuple[RepeatSpec, dict[str, str]]: + """Propose the item key for each slot from the demonstration's typed + values: a slot maps to key ``k`` when, for every instance the demo filled, + the value typed there equals ``items[i][k]`` and no other key fits. Slots + that do not map are returned with a reason. A proposal, for the author.""" + + final = demo[-1].after if demo else Screen() + read = find_instances(final, spec) + problems: dict[str, str] = {} + if not read.usable or len(read.instances) != len(items): + return spec, { + s.name: "the demo's instances do not line up with its items" + for s in spec.slots + } + typed: dict[str, str] = {} + for step in demo: + if step.action == "type": + typed[step.target.handle] = step.value.strip() + slots = [] + for n, slot in enumerate(spec.slots): + keys: Optional[set[str]] = None + for i, inst in enumerate(read.instances): + value = typed.get(inst.controls[n].handle) + fit = { + k + for k, v in items[i].items() + if value is not None and str(v).strip() == value + } + keys = fit if keys is None else keys & fit + if keys and len(keys) == 1: + slots.append(Slot(slot.role, slot.name, next(iter(keys)))) + else: + slots.append(slot) + problems[slot.name] = "no single item key matches what the demo typed" + return ( + RepeatSpec( + spec.group_id, + spec.add, + spec.instance_kind, + tuple(slots), + spec.within, + spec.add_writes, + spec.max_instances, + ), + problems, + ) diff --git a/packages/flow/tests/failopen/sites/gui_repeating.py b/packages/flow/tests/failopen/sites/gui_repeating.py new file mode 100644 index 0000000000..540ea37645 --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_repeating.py @@ -0,0 +1,145 @@ +"""gui.repeating.judge (C1 C2 C5): every intake item shows in the instance it +was written into, slot by slot. + +The obligations are item-by-slot, fixed from the intake before any instance +was added. A value must equal the item's text exactly. An instance no item +was written into is refuted and unexpected; a missing instance is missing; an +empty intake never passes. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.gui.repeating import judge_instances +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +RUN = "run-1" + + +def _good() -> dict[str, Any]: + return { + "planned": [ + {"item": "0", "slot": "Full name", "expected": "Ann Example"}, + {"item": "0", "slot": "Date of birth", "expected": "1990-01-02"}, + {"item": "1", "slot": "Full name", "expected": "Ben Example"}, + {"item": "1", "slot": "Date of birth", "expected": "1988-03-04"}, + ], + "bound": {"0": "#p1", "1": "#p2"}, + "seen": [ + { + "handle": "#p1", + "slot": "Full name", + "value": "Ann Example", + "run_id": RUN, + }, + { + "handle": "#p1", + "slot": "Date of birth", + "value": "1990-01-02", + "run_id": RUN, + }, + { + "handle": "#p2", + "slot": "Full name", + "value": "Ben Example", + "run_id": RUN, + }, + { + "handle": "#p2", + "slot": "Date of birth", + "value": "1988-03-04", + "run_id": RUN, + }, + ], + "complete": True, + } + + +def _run(ev: dict[str, Any]) -> Any: + return judge_instances( + ev["planned"], ev["bound"], ev["seen"], run_id=RUN, complete=ev.get("complete") + ) + + +def _bad(item: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(item) + out["value"] = str(out.get("value")) + " (other)" + return out + + +def _inflate(ev: dict[str, Any], n: int) -> dict[str, Any]: + planned = [{"item": str(i), "slot": "v", "expected": f"x{i}"} for i in range(n)] + bound = {str(i): f"#r{i}" for i in range(n)} + seen = [ + { + "handle": f"#r{i}", + "slot": "v", + "value": f"x{i}" if i != n - 1 else "no", + "run_id": RUN, + } + for i in range(n) + ] + return {**ev, "planned": planned, "bound": bound, "seen": seen} + + +def _swapped() -> dict[str, Any]: + ev = _good() + ev["bound"] = {"0": "#p2", "1": "#p1"} + return ev + + +register( + SiteSpec( + id="gui.repeating.judge", + classes="C1 C2 C5", + target="openadapt_flow.gui.repeating:judge_instances", + run=_run, + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_good(), True), + Seed(_swapped(), False, "items in each other's instances"), + Seed( + {**_good(), "seen": _good()["seen"][:2]}, False, "an item never added" + ), + Seed( + { + **_good(), + "seen": _good()["seen"] + + [ + { + "handle": "#p3", + "slot": "Full name", + "value": "", + "run_id": RUN, + } + ], + }, + False, + "an instance nobody planned", + ), + Seed( + {**_good(), "bound": {"0": "#p1", "1": "#p1"}}, + False, + "two items, one instance", + ), + ], + items=key("seen"), + plan=key("planned"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("seen"), 0), + values=( + key("value", "seen", 0), + key("handle", "seen", 0), + key("slot", "seen", 0), + key("expected", "planned", 0), + key("0", "bound"), + ), + subject=key("run_id", "seen", 0), + partial=lambda ev: [("complete", {**ev, "complete": False})], + ) +) diff --git a/packages/flow/tests/gui/test_gui_repeating.py b/packages/flow/tests/gui/test_gui_repeating.py new file mode 100644 index 0000000000..75b1a04891 --- /dev/null +++ b/packages/flow/tests/gui/test_gui_repeating.py @@ -0,0 +1,398 @@ +"""Repeating structures on four kinds of app. + +- a web form (group booking) with "Add another attendee"; +- an EMR-like medication table that starts empty, with unlabeled rows; +- a spreadsheet-like grid with no browser ("Insert row"); +- a SaaS invoice whose "Add line item" control is a link. + +Each group is learned from one demonstration, then filled for an intake with +a different number of items. Every instance is read back against its own item. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.model import ControlSpec, Recorder, match_all, match_one +from openadapt_flow.gui.repeating import ( + RepeatSpec, + Slot, + fill_instances, + find_instances, + judge_instances, + learn_repeats, + location_rows, + map_slots, +) +from openadapt_flow.verdict import Status +from tests.gui import _apps +from tests.gui._grid import GridApp, Sheet + +# -- web form: group booking ------------------------------------------------------- + + +def booking( + *, + start: int = 1, + prefill: str = "", + add: str = "one", + add_posts: bool = False, + upper: bool = False, + auto_blank: bool = False, +) -> _apps.App: + adds = {"one": "addOne();", "none": "", "two": "addOne();addOne();"}[add] + post = "fetch('/draft',{method:'POST',body:'{}'});" if add_posts else "" + blur = "this.value=this.value.toUpperCase();" if upper else "" + auto = "autoAdd(this);" if auto_blank else "" + + def form(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Book", + f"""

Group booking

+
+ +
+
""", + ) + + def book(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + app.state["booking"] = {k: v[0] for k, v in f.items()} + return 200, _apps.page("Booked", "

Booked

") + + return _apps.App( + "book.test", + { + ("GET", "/book"): form, + ("POST", "/book"): book, + ("POST", "/draft"): lambda a, p, m, f: (200, "{}"), + }, + ) + + +DEMO_PEOPLE = [ + {"name": "Ann Example", "dob": "1990-01-02"}, + {"name": "Ben Example", "dob": "1988-03-04"}, +] +PEOPLE = [ + {"name": "Cal Sample", "dob": "1975-05-06"}, + {"name": "Dot Sample", "dob": "1979-07-08"}, + {"name": "Eve Sample", "dob": "2001-09-10"}, +] + + +def _record_booking(page: Any) -> tuple[RepeatSpec, list]: + app = booking() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + rec = Recorder(act) + + def fill(n: int, person: dict) -> None: + s = act.observe() + names = match_all(ControlSpec("textbox", "Full name"), s) + dobs = match_all(ControlSpec("textbox", "Date of birth"), s) + rec.set_text(names[n].handle, person["name"]) + rec.set_text(dobs[n].handle, person["dob"]) + + fill(0, DEMO_PEOPLE[0]) + rec.click( + match_one( + ControlSpec("button", "Add another attendee"), act.observe() + ).handle + ) + fill(1, DEMO_PEOPLE[1]) + (spec,) = learn_repeats(rec.steps) + mapped, problems = map_slots(spec, rec.steps, DEMO_PEOPLE) + assert not problems, problems + return mapped, rec.steps + + +def test_web_form_group_is_learned_with_its_fields_and_item_keys(page) -> None: + spec, _ = _record_booking(page) + assert spec.add == ControlSpec("button", "Add another attendee", dialog=False) + assert spec.instance_kind == "group" + assert spec.slots == ( + Slot("textbox", "Full name", "name"), + Slot("textbox", "Date of birth", "dob"), + ) + + +def test_web_form_adds_fills_and_checks_one_instance_per_item(page) -> None: + spec, _ = _record_booking(page) + app = booking() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + out = fill_instances(act, spec, PEOPLE, run_id="r1") + assert out.held, out.reason + assert out.added == 2 + act.click(match_one(ControlSpec("button", "Book"), act.observe()).handle) + assert app.state["booking"] == { + "name1": "Cal Sample", + "dob1": "1975-05-06", + "name2": "Dot Sample", + "dob2": "1979-07-08", + "name3": "Eve Sample", + "dob3": "2001-09-10", + } + + +@pytest.mark.parametrize( + ("variant", "items", "reason", "status"), + [ + ({"add": "none"}, PEOPLE, "from 1 to 1 instances", Status.NOT_CHECKED), + ({"add": "two"}, PEOPLE, "from 1 to 3 instances", Status.NOT_CHECKED), + ({"prefill": "Zed Other"}, PEOPLE, "already holds data", Status.NOT_CHECKED), + ({"add_posts": True}, PEOPLE, "wrote 1 times", Status.NOT_CHECKED), + ({"start": 3}, PEOPLE[:2], "never deletes", Status.NOT_CHECKED), + ({"upper": True}, PEOPLE, "does not show its item", Status.REFUTED), + ({"auto_blank": True}, PEOPLE, "does not show its item", Status.REFUTED), + ], +) +def test_web_form_group_that_does_not_line_up_stops( + page, variant, items, reason, status +) -> None: + spec, _ = _record_booking(page) + app = booking(**variant) + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + out = fill_instances(act, spec, items, run_id="r2") + assert out.status is status and reason in out.reason, out.reason + if status is Status.NOT_CHECKED: + assert not out.wrote or "wrote" in out.reason + + +def test_an_item_missing_a_key_stops_before_anything_is_added(page) -> None: + spec, _ = _record_booking(page) + app = booking() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + out = fill_instances(act, spec, [PEOPLE[0], {"name": "No Dob"}]) + assert ( + out.status is Status.NOT_CHECKED and out.added == 0 and "dob" not in out.bound + ) + + +# -- EMR-like medication table: starts empty, rows have no labels -------------------- + + +def meds(*, sort_after: bool = False) -> _apps.App: + sorter = ( + "document.getElementById('tb').addEventListener('change',()=>{" + "const rows=[...document.querySelectorAll('#tb tr')];" + "if(rows.every(r=>r.querySelector('input').value)){" + "const vals=rows.map(r=>[...r.querySelectorAll('input')].map(i=>i.value)).sort();" + "rows.forEach((r,k)=>r.querySelectorAll('input').forEach((i,j)=>i.value=vals[k][j]));}});" + if sort_after + else "" + ) + + def chart(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Medications", + f"""

Chart: Test Patient D

+ +
DrugDose
+ +
""", + ) + + return _apps.App("chart.test", {("GET", "/meds"): chart}) + + +DEMO_MEDS = [{"drug": "Drug A", "dose": "10 mg"}, {"drug": "Drug B", "dose": "5 mg"}] +MEDS = [ + {"drug": "Drug Z", "dose": "1 mg"}, + {"drug": "Drug Y", "dose": "2 mg"}, + {"drug": "Drug X", "dose": "3 mg"}, +] + + +def _record_meds(page: Any) -> RepeatSpec: + app = meds() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/meds") + rec = Recorder(act) + for n, med in enumerate(DEMO_MEDS): + rec.click( + match_one(ControlSpec("button", "Add medication"), act.observe()).handle + ) + s = act.observe() + rec.set_text( + match_all(ControlSpec("textbox", "Drug"), s)[n].handle, med["drug"] + ) + rec.set_text( + match_all(ControlSpec("textbox", "Dose"), s)[n].handle, med["dose"] + ) + (spec,) = learn_repeats(rec.steps) + mapped, problems = map_slots(spec, rec.steps, DEMO_MEDS) + assert not problems + return mapped + + +def test_emr_table_that_starts_empty_is_learned_from_the_second_add(page) -> None: + spec = _record_meds(page) + assert spec.instance_kind == "row" + assert [(s.name, s.item_key) for s in spec.slots] == [ + ("Drug", "drug"), + ("Dose", "dose"), + ] + + +def test_emr_rows_are_checked_by_the_row_each_item_was_written_into(page) -> None: + spec = _record_meds(page) + app = meds() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/meds") + out = fill_instances(act, spec, MEDS, run_id="r3") + assert out.held, out.reason + assert len(set(out.bound.values())) == 3 + # The app sorts the rows once all are filled: each row now shows another + # item's values, so the check by row refutes even though every value is + # somewhere on the screen. + app = meds(sort_after=True) + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/meds") + out = fill_instances(act, spec, MEDS, run_id="r4") + assert out.status is Status.REFUTED + + +# -- spreadsheet-like grid ----------------------------------------------------------- + + +def _ledger(rows: list[list[str]] | None = None) -> GridApp: + return GridApp( + [Sheet("Expenses", ("Item", "Amount"), rows if rows is not None else [])] + ) + + +def _record_grid() -> RepeatSpec: + grid = _ledger() + rec = Recorder(grid) + demo = [{"item": "Rent", "amount": "1200"}, {"item": "Power", "amount": "90"}] + for r, row in enumerate(demo): + rec.click("tool:insert") + rec.set_text(f"cell:Expenses:{r}:0", row["item"]) + rec.set_text(f"cell:Expenses:{r}:1", row["amount"]) + (spec,) = learn_repeats(rec.steps) + mapped, problems = map_slots(spec, rec.steps, demo) + assert not problems + return mapped + + +def test_grid_rows_are_learned_and_filled_without_a_browser() -> None: + spec = _record_grid() + assert spec.add.name == "Insert row" and spec.instance_kind == "row" + grid = _ledger() + items = [ + {"item": "Rent", "amount": "1250"}, + {"item": "Water", "amount": "40"}, + {"item": "Net", "amount": "60"}, + ] + out = fill_instances(grid, spec, items, run_id="g1") + assert out.held, out.reason + assert grid.sheets[0].rows == [["Rent", "1250"], ["Water", "40"], ["Net", "60"]] + assert location_rows(spec, items, out.bound)[0] == { + "id": f"{spec.group_id}:0:Item", + "keys": [f"{spec.group_id}[0].item"], + "start": "same_screen", + "locator": {"kind": "region", "value": out.bound["0"], "column": "Item"}, + "expected": {f"{spec.group_id}[0].item": "Rent"}, + "expected_count": 1, + } + + +def test_grid_rows_already_holding_data_stop_and_nothing_is_added() -> None: + spec = _record_grid() + grid = _ledger([["Old", "5"]]) + out = fill_instances( + grid, spec, [{"item": "Rent", "amount": "1"}, {"item": "Tax", "amount": "2"}] + ) + assert out.status is Status.NOT_CHECKED and out.added == 0 + assert grid.sheets[0].rows == [["Old", "5"]] + + +# -- SaaS invoice: the add control is a link ------------------------------------------ + + +def invoice() -> _apps.App: + def page_(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Invoice", + """

New invoice

    +Add line item +
    """, + ) + + return _apps.App("app.test", {("GET", "/invoice"): page_}) + + +def test_saas_invoice_fills_lines_added_by_a_link(page) -> None: + spec = RepeatSpec( + "lines", + ControlSpec("link", "Add line item"), + "item", + (Slot("textbox", "Description", "desc"), Slot("textbox", "Amount", "amount")), + ) + app = invoice() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/invoice") + assert [i.name for i in find_instances(act.observe(), spec).instances] == [ + "Line 1" + ] + items = [ + {"desc": "Setup", "amount": "100.00"}, + {"desc": "Support", "amount": "40.00"}, + ] + out = fill_instances(act, spec, items, run_id="s1") + assert out.held, out.reason + + +# -- the verdict ------------------------------------------------------------------------ + + +def test_judge_instances_refuses_missing_extra_and_rebound_rows() -> None: + planned = [{"item": "0", "slot": "Name", "expected": "Ann"}] + seen = [{"handle": "#a", "slot": "Name", "value": "Ann", "run_id": "r"}] + assert judge_instances(planned, {"0": "#a"}, seen, run_id="r").status is Status.HELD + assert judge_instances([], {}, [], run_id="r").status is not Status.HELD + extra = seen + [{"handle": "#b", "slot": "Name", "value": "", "run_id": "r"}] + assert ( + judge_instances(planned, {"0": "#a"}, extra, run_id="r").status + is Status.REFUTED + ) + assert ( + judge_instances(planned, {"0": "#b"}, seen, run_id="r").status is Status.REFUTED + ) + assert ( + judge_instances(planned, {"0": "#a"}, [], run_id="r").status + is Status.NOT_CHECKED + ) + near = [{**seen[0], "value": "Ann "}] + assert ( + judge_instances(planned, {"0": "#a"}, near, run_id="r").status is Status.REFUTED + ) From f72b015dcde4af136e13b97731a1c5b4cccbdfcf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:47:55 -0500 Subject: [PATCH 15/19] 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 c992c1fb7e50909b7d42c1179e81e1cbc28ea532 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:49:42 -0500 Subject: [PATCH 16/19] fix(flow): run_section reports the hub verdict's status instead of minting its own held result From Gemini's review of #2502. Only judge_hub, a registered verdict site, can say a section held; run_section now carries its status and verdict. --- packages/flow/openadapt_flow/gui/hub.py | 51 ++++++++++--------------- packages/flow/tests/gui/test_gui_hub.py | 8 ++-- 2 files changed, 24 insertions(+), 35 deletions(-) diff --git a/packages/flow/openadapt_flow/gui/hub.py b/packages/flow/openadapt_flow/gui/hub.py index c193d44d85..c557958db9 100644 --- a/packages/flow/openadapt_flow/gui/hub.py +++ b/packages/flow/openadapt_flow/gui/hub.py @@ -290,15 +290,20 @@ def expected_writes(sections: Sequence[SectionSpec], planned: Iterable[str]) -> @dataclass(frozen=True) class SectionOutcome: + """How one section went. ``status`` is HELD only when :func:`judge_hub` + held for the section on a fresh read of the hub (``verdict``).""" + section_id: str - result: Result + status: Status + reason: str opened: bool = False saved: bool = False hub: Optional[Screen] = None + verdict: Optional[HubVerdict] = None @property def held(self) -> bool: - return self.result.status is Status.HELD + return self.status is Status.HELD def run_section( @@ -315,13 +320,10 @@ def run_section( ``fill`` gets the screen with the dialog open and the dialog. It must act only inside that dialog.""" - subject = Subject( - run_id=run_id, surface="gui", key=section.section_id, field="section" - ) sid = section.section_id def stop(reason: str, **kw: Any) -> SectionOutcome: - return SectionOutcome(sid, Result.not_checked(subject, reason), **kw) + return SectionOutcome(sid, Status.NOT_CHECKED, reason, **kw) hub = actuator.observe() if hub.dialogs: @@ -382,7 +384,6 @@ def stop(reason: str, **kw: Any) -> SectionOutcome: actuator.click(save.handle) w2 = actuator.write_count() after = actuator.observe() - obs = Observed(after, complete=after.complete) if after.dialogs: errors = [c.error for c in after.controls if c.error] or list(after.errors) reason = ( @@ -390,39 +391,27 @@ def stop(reason: str, **kw: Any) -> SectionOutcome: if errors else "the dialog did not close" ) - return SectionOutcome( - sid, Result.refuted(subject, obs, reason), True, False, after - ) - if w1 is None or w2 is None or w2 - w1 != section.save_writes: - got = "unknown" if w1 is None or w2 is None else w2 - w1 + return SectionOutcome(sid, Status.REFUTED, reason, True, False, after) + if w1 is None or w2 is None: return SectionOutcome( sid, - Result.refuted( - subject, - obs, - f"saving wrote {got}; the demo wrote {section.save_writes}", - ), + Status.NOT_CHECKED, + "the save's writes were not counted", True, True, after, ) + if w2 - w1 != section.save_writes: + reason = f"saving wrote {w2 - w1}; the demo wrote {section.save_writes}" + return SectionOutcome(sid, Status.REFUTED, reason, True, True, after) verdict = judge_hub_screen(after, (section,), [sid], run_id=run_id) - if verdict.status is Status.HELD: - return SectionOutcome( - sid, Result.held(subject, obs, "the card shows done"), True, True, after - ) reading = card_reading(after, section) - if verdict.status is Status.REFUTED: - return SectionOutcome( - sid, Result.refuted(subject, obs, reading.reason), True, True, after - ) - return SectionOutcome( - sid, - Result.not_checked(subject, reading.reason or "not read"), - True, - True, - after, + reason = ( + "the card shows done" + if verdict.status is Status.HELD + else (reading.reason or "the card was not read") ) + return SectionOutcome(sid, verdict.status, reason, True, True, after, verdict) # -- from a demonstration ---------------------------------------------------------- diff --git a/packages/flow/tests/gui/test_gui_hub.py b/packages/flow/tests/gui/test_gui_hub.py index 56c6878059..3fca8cbc8e 100644 --- a/packages/flow/tests/gui/test_gui_hub.py +++ b/packages/flow/tests/gui/test_gui_hub.py @@ -158,7 +158,7 @@ def test_emr_hub_replays_each_section_and_reads_completion_from_the_hub(page) -> assert before.status is Status.REFUTED for spec, value in zip(specs, ("Latex", "Drug E 2 mg")): out = run_section(act, spec, _fill_with(value), sections=specs, run_id="r1") - assert out.held, out.result.reason + assert out.held, out.reason verdict = judge_hub_screen( act.observe(), specs, ["allergies", "medications"], run_id="r1" ) @@ -195,7 +195,7 @@ def test_emr_hub_section_that_does_not_complete_stops( ACT[:] = [act] page.goto(f"{app.origin}/chart") out = run_section(act, specs[0], _fill_with(value), sections=specs, run_id="r2") - assert out.result.status is status and reason in out.result.reason + assert out.status is status and reason in out.reason # -- SaaS onboarding checklist: form dialogs are never confirmations ----------------- @@ -251,7 +251,7 @@ def test_saas_dialog_with_a_field_is_a_form_even_when_it_says_confirm(page) -> N page.evaluate(f"{dlg}.hidden=true") ACT[:] = [act] out = run_section(act, section, _fill_with("Acme Test Co"), run_id="r3") - assert out.held, out.result.reason + assert out.held, out.reason assert app.state["company"] == "Acme Test Co" @@ -362,7 +362,7 @@ def test_desktop_prefs_ok_that_saves_nothing_is_refuted() -> None: out = run_section( app, specs[0], lambda s, d: app.set_text("dlg:val", "x"), sections=specs ) - assert out.result.status is Status.REFUTED and "saving wrote 0" in out.result.reason + assert out.status is Status.REFUTED and "saving wrote 0" in out.reason def test_judge_hub_never_passes_empty_unread_or_unplanned() -> None: From 1b628b0344946e51acf38a5ff8e606c56f3e72cb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:50:28 -0500 Subject: [PATCH 17/19] docs(flow): record gui.repeating in CAPABILITIES, the changelog and the fail-closed list --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 5 +++++ packages/flow/docs/FAIL_CLOSED.md | 3 +++ packages/flow/openadapt_flow/gui/__init__.py | 2 ++ 5 files changed, 12 insertions(+) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index b06c89583b..ddddb31762 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -182,6 +182,7 @@ improvising or retrying when something is off. | 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` | | Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `packages/flow/tests/gui` | | Hub pages whose sections open in dialogs: a dialog holding any editable control is a form, never a confirmation; each section's completion is read from its card on the hub after save, with the demonstrated writes, never assumed from the click | On main ([#2502](https://github.com/OpenAdaptAI/OpenAdapt/pull/2502)) | Synthetic: an EMR-like chart hub, a SaaS onboarding checklist (headless Chromium) and a desktop preferences window read as an accessibility tree | `openadapt_flow.gui.hub`, `packages/flow/tests/gui` | +| Repeating structures ("add another traveller", a table row, a line item) learned from one demonstration: instances are added to match the intake, filled in order and each read back by the container it was written into; a prefilled instance, more instances than items, or an add that did not add exactly one blank instance stops the run before writing | On main ([#2512](https://github.com/OpenAdaptAI/OpenAdapt/pull/2512)) | Synthetic: a web form, an EMR-like medication table, a SaaS invoice (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.repeating`, `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 ca47ba8c04..c5c57b9428 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -622,6 +622,7 @@ improvising or retrying when something is off. | 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` | | Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `packages/flow/tests/gui` | | Hub pages whose sections open in dialogs: a dialog holding any editable control is a form, never a confirmation; each section's completion is read from its card on the hub after save, with the demonstrated writes, never assumed from the click | On main ([#2502](https://github.com/OpenAdaptAI/OpenAdapt/pull/2502)) | Synthetic: an EMR-like chart hub, a SaaS onboarding checklist (headless Chromium) and a desktop preferences window read as an accessibility tree | `openadapt_flow.gui.hub`, `packages/flow/tests/gui` | +| Repeating structures ("add another traveller", a table row, a line item) learned from one demonstration: instances are added to match the intake, filled in order and each read back by the container it was written into; a prefilled instance, more instances than items, or an add that did not add exactly one blank instance stops the run before writing | On main ([#2512](https://github.com/OpenAdaptAI/OpenAdapt/pull/2512)) | Synthetic: a web form, an EMR-like medication table, a SaaS invoice (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.repeating`, `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 7f4c25e4fe..706e6af28d 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -35,6 +35,11 @@ an editable control is a form, never a confirmation. Each section is opened, filled and saved, and its completion is read from its card on the hub after the save, with the demonstrated number of writes. +- Repeating structures (`openadapt_flow.gui.repeating`). An "add another" + group is learned from a demonstration. A run adds instances until the count + matches the intake, fills them in order and reads each one back by the + container it was written into. It never deletes an instance and stops on a + prefilled one. - One verdict kernel, `openadapt_flow.verdict`, for every check that turns evidence into held, refuted or not checked. It fixes the obligations from diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 220d4c2f5d..b46925501b 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -297,6 +297,9 @@ Done: are the obligations; a box the plan never saw is unexpected. - [x] `gui.hub.judge_hub` (C1 C2): new. The planned sections are the obligations; completion is read from the hub, never from the save click. +- [x] `gui.repeating.judge_instances` (C1 C2 C5): new. Item-by-slot + obligations from the intake, checked in the instance each item was written + into; an instance nobody planned is refuted. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py index 64bcd04108..c0621df80f 100644 --- a/packages/flow/openadapt_flow/gui/__init__.py +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -12,6 +12,8 @@ is ticked only on a person's grant, never through a fact. - :mod:`openadapt_flow.gui.hub`: a hub page whose sections open in dialogs, each section's completion read back from the hub. +- :mod:`openadapt_flow.gui.repeating`: "add another" groups, added to match + the intake and checked instance by instance. 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 From 77e71039702339c6ea82876cfa00d36d6c65a7b1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:55:46 -0500 Subject: [PATCH 18/19] fix(flow): an attestation spec that matches more than one box stops on every one One grant covers one box. A loose spec naming two identical boxes used to plan a tick for both on one grant; now each is a stop and nothing is ticked. From Gemini's non-blocking note on #2501. --- .../flow/openadapt_flow/gui/attestations.py | 20 +++++++++++++++- .../flow/tests/gui/test_gui_attestations.py | 24 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/gui/attestations.py b/packages/flow/openadapt_flow/gui/attestations.py index 0042c6c19e..d66183d805 100644 --- a/packages/flow/openadapt_flow/gui/attestations.py +++ b/packages/flow/openadapt_flow/gui/attestations.py @@ -25,7 +25,8 @@ shows the state the pack declared. - ``stop``: anything else. An undeclared checkbox, a changed statement, a missing or mismatched grant, an attestation bound to a field, a box ticked - before the run touched it, or two specs matching one box. The run stops + before the run touched it, two specs matching one box, or one spec + matching several boxes (one grant covers one box). The run stops before acting on any box. :func:`judge_attestations` is a verdict site. Its obligations are the plan's @@ -256,6 +257,14 @@ def plan_checkboxes( by_id = _grants_by_id(grants) bound_set = set(bound) boxes: list[BoxPlan] = [] + # One grant covers one box: a spec that names several boxes on the + # screen (two identical "I agree" boxes) stops on every one of them. + matches = { + a.attestation_id: sum( + 1 for c in screen.controls if c.role in BOX_ROLES and a.control.matches(c) + ) + for a in attestations + } for ctrl in screen.controls: if ctrl.role not in BOX_ROLES: continue @@ -283,6 +292,15 @@ def plan_checkboxes( if len(specs) > 1: boxes.append(_stop(ctrl, "two declared attestations match this box")) continue + if specs and matches[specs[0].attestation_id] > 1: + boxes.append( + _stop( + ctrl, + "the attestation's spec matches more than one box", + specs[0].attestation_id, + ) + ) + continue if not specs: leave = [i for i in ignored if i.control.matches(ctrl)] if len(leave) == 1 and ctrl.checked is leave[0].checked: diff --git a/packages/flow/tests/gui/test_gui_attestations.py b/packages/flow/tests/gui/test_gui_attestations.py index a87616e574..c6bdf37b6d 100644 --- a/packages/flow/tests/gui/test_gui_attestations.py +++ b/packages/flow/tests/gui/test_gui_attestations.py @@ -426,3 +426,27 @@ def test_judge_refuses_empty_unexpected_and_unread_boxes() -> None: judge_attestations([row], good, run_id="r", complete=False).status is not Status.HELD ) + + +def test_one_spec_matching_two_identical_boxes_stops_on_both(page) -> None: + twin = _membership( + extra=f''.replace( + "