diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54a4ff4707..cc26db334f 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 - name: No generated page was edited by hand # CAPABILITIES.md and llms-full.txt are generated from sources (row # files under capabilities/, README.md, ...). A change edits the diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index afa54b0169..9d5cf2f252 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -670,6 +670,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/04-the-core-a-checked-entry-every-time/0315-fail-closed-by-construction-one-verdict-kernel.md b/capabilities/04-the-core-a-checked-entry-every-time/0315-fail-closed-by-construction-one-verdict-kernel.md new file mode 100644 index 0000000000..589dcd292a --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0315-fail-closed-by-construction-one-verdict-kernel.md @@ -0,0 +1 @@ +| 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` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 4fa9618bc4..cf239e23c3 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -64,6 +64,23 @@ ### 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. + `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. - A sign-in that asks for a second factor (a code by text message or email, an authenticator code, or a push approval) no longer has to stop the program. A `second_factor` step (`one_time` is `code` or `approval`) waits @@ -112,6 +129,18 @@ ### 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. +- `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. - The form transaction layer (`form_tx`, an unreleased prototype until this release) reads back every field it typed, selected or kept. Each one gets a `passed`, `failed` or `not_checked` verdict; a field it cannot read back diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md new file mode 100644 index 0000000000..236df580f5 --- /dev/null +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -0,0 +1,316 @@ +# 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. One result can't settle two obligations: if two claim it, both + 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". +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. 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 + +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 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 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. + +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, 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). + +## 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. A spec with no pass seed, or one that no mutation +applies to, fails too: + +| 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` 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 | +| S8 `''` and NULL in the governed check (#2258) | main at `576f87b41` | `00a55cc16` | P0, M10 | +| 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. + +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. + +- `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, 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/`, 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. 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. + +## 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 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 + `''`, 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. + +## 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 + 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 + 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 ad5f4a0210..8796f3a89e 100644 --- a/packages/flow/openadapt_flow/hard_invariants.py +++ b/packages/flow/openadapt_flow/hard_invariants.py @@ -8,20 +8,55 @@ 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"] InvariantStatus = Literal["held", "refuted", "not_checked"] 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 { @@ -38,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 { @@ -62,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], @@ -71,19 +118,25 @@ 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") def judge_hard_invariants( *, outside_scope_changes: Optional[int], @@ -123,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 3b85d83183..6a855994d9 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 + + #: Signed per-write receipts a run folder may hold, each one line. _EVIDENCE_GLOBS = ( ("tx_receipt", "tx-receipt.cose"), @@ -338,14 +412,13 @@ def build_statement( raise ReceiptRecordError( "too_many_writes", "the complete write list exceeds the receipt limit" ) - 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 3f10ca3026..86ade2f524 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -33,13 +33,22 @@ 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"] @@ -219,6 +228,7 @@ def _resolve_self( return out +@verdict_site("versions.judge", classes="C1 C5") def judge_versions( spec: FrameVersions, stored: Mapping[str, Any], @@ -254,131 +264,190 @@ 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: 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 = [ + 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 8f624d6a50..06327fb679 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__ = [ @@ -140,6 +141,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 new file mode 100644 index 0000000000..1d398de88b --- /dev/null +++ b/packages/flow/openadapt_flow/verdict.py @@ -0,0 +1,545 @@ +"""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. +- :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 + 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 contextvars import ContextVar +from dataclasses import dataclass, 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. + + 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 + + +@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``; mapping one to ``Observed`` raises ``TypeError``). + 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): + 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)): + 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 ---------------------------------------------------------------------- + +#: 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 _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) +class Result: + """One check of one subject. Build it with the class methods.""" + + subject: Subject + status: Status + reason: str + + 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 not _MINTING.get(): + 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. 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") + return _mint_held(subject, reason or "held") + + @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 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, + 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 _mint_held(subject, text) + 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 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: + 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) + + +@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 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) + buckets: dict[str, list[Subject]] = { + k: [] for k in ("held", "refuted", "not_checked", "missing", "mismatched") + } + conflicting: list[Subject] = [] + used: set[int] = set() + matches: dict[int, list[Result]] = {} + # 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.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 shared: + # Two results that disagree, or one result two obligations claim. + conflicting.append(item) + else: + buckets[got[0].status.value].append(item) + # 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, + 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..b180b54c5a --- /dev/null +++ b/packages/flow/openadapt_flow/verdict_sites.py @@ -0,0 +1,39 @@ +"""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] = {} +#: ``{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: + 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 + + return mark diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index cabfb87834..4463eb2498 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 ( @@ -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,37 +2957,106 @@ def _label(verdict: Verdict) -> EffectVerdictLabel: return labels[verdict] -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" +_AGGREGATE_LABELS: dict[Status, EffectVerdictLabel] = { + Status.HELD: "CONFIRMED", + Status.REFUTED: "REFUTED", + Status.NOT_CHECKED: "INDETERMINATE", +} + + +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="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.""" -def _observed(verdicts: Sequence[EffectVerdict]) -> str: + 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.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 "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") 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) ): @@ -3198,6 +3269,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) @@ -3256,8 +3331,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() @@ -3285,8 +3360,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/public-artifacts.json b/packages/flow/public-artifacts.json index a592e524a5..45f8dcf4a4 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1534,9 +1534,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..354ca8caf4 --- /dev/null +++ b/packages/flow/scripts/check_verdict_folds.py @@ -0,0 +1,608 @@ +"""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 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): + +- ``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", + "swallow_wide", + "slice_count", + "else_success", + "says_unchanged", + "empty_change_set", +) + + +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) + config["_unchanged"] = frozenset(config["literals"]["unchanged"]) + config["_change_names"] = re.compile(config["change_set"]["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: + if site in out: + raise ValueError( + f"{path}: verdict site {site!r} on both {out[site]} and {name}" + ) + out[site] = name + visit(child, name + ".") + else: + # Inside an ``if``, ``try`` or ``with``: same scope, same prefix. + visit(child, prefix) + + 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"} +) +_NOT_CHECKED_STRINGS = frozenset( + {"not_checked", "NOT_CHECKED", "INDETERMINATE", "unchecked", "unknown", "UNKNOWN"} +) + + +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 _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 + # 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) + ): + return True + return False + + +_RECORDING = frozenset({"append", "add", "extend", "put", "setdefault", "insert"}) + + +_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.""" + + # 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, unchanged = config["_fold_names"], config["_unchanged"] + change_names = config["_change_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 _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)): + 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.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) 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])) + ): + counts["bool_fold"] += 1 + 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=[]) + exits = [ + n + for n in ast.walk(body) + 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)): + 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 + 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) + ) + 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 _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] + + 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 False + + +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 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 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 = [] + 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 + + +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, 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 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_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]: + """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 = {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(): + 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: + 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) + 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" + ) + 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) + 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)") + 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..0eef239d88 --- /dev/null +++ b/packages/flow/scripts/verdict_folds.toml @@ -0,0 +1,53 @@ +# 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"] +# 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 new file mode 100644 index 0000000000..a5e13b9ff9 --- /dev/null +++ b/packages/flow/scripts/verdict_folds_baseline.json @@ -0,0 +1,1760 @@ +{ + "packages/flow/openadapt_flow/__main__.py": { + "cmp_literal": 14, + "swallow": 8, + "swallow_wide": 9, + "says_unchanged": 2 + }, + "packages/flow/openadapt_flow/_browser_readiness.py": { + "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 + }, + "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/a2a_server.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/agent/authoring.py": { + "cmp_literal": 3, + "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, + "swallow_wide": 5 + }, + "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, + "says_unchanged": 4 + }, + "packages/flow/openadapt_flow/agent/contract_call.py": { + "swallow_wide": 1 + }, + "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, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/agent/repair.py": { + "swallow": 4, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/agent/runner.py": { + "says_success": 1, + "cmp_literal": 12, + "swallow": 3, + "swallow_wide": 1, + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/agent/runs.py": { + "swallow": 2, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/agent/sandbox.py": { + "says_success": 2, + "cmp_literal": 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_wide": 2 + }, + "packages/flow/openadapt_flow/agent/service.py": { + "cmp_literal": 1, + "swallow": 4, + "swallow_wide": 4 + }, + "packages/flow/openadapt_flow/agent/teach.py": { + "cmp_literal": 8, + "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/approval_fields.py": { + "bool_fold": 1, + "swallow": 3, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/agent_guard/capture.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/agent_guard/cdp.py": { + "swallow": 11 + }, + "packages/flow/openadapt_flow/agent_guard/commit_guard.py": { + "cmp_literal": 2, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/agent_guard/ledger_row.py": { + "says_success": 2, + "cmp_literal": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/agent_guard/readback.py": { + "says_success": 1, + "cmp_literal": 1, + "swallow": 2 + }, + "packages/flow/openadapt_flow/agent_guard/session.py": { + "cmp_literal": 1, + "swallow": 4, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/agent_guard/shadow_hold.py": { + "says_success": 3, + "cmp_literal": 3 + }, + "packages/flow/openadapt_flow/api_footprint.py": { + "empty_change_set": 1 + }, + "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, + "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 + }, + "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/at_rest.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/attest_bridge.py": { + "swallow": 2, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/authoring.py": { + "swallow": 2, + "swallow_wide": 7 + }, + "packages/flow/openadapt_flow/authorization_summary.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/backends/_owned.py": { + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/backends/_page_quiescence.py": { + "swallow": 4, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/backends/_server_responses.py": { + "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_wide": 4 + }, + "packages/flow/openadapt_flow/backends/macos_backend.py": { + "swallow": 16, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/backends/one_time_field.py": { + "swallow": 6 + }, + "packages/flow/openadapt_flow/backends/parallels_vm.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/backends/playwright_backend.py": { + "cmp_literal": 1, + "swallow": 71, + "swallow_wide": 19 + }, + "packages/flow/openadapt_flow/backends/rdp_backend.py": { + "swallow": 11, + "swallow_wide": 5 + }, + "packages/flow/openadapt_flow/backends/redirect_guard.py": { + "swallow": 1, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/backends/remote_display.py": { + "bool_fold": 1, + "swallow": 31, + "swallow_wide": 4 + }, + "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, + "swallow_wide": 6 + }, + "packages/flow/openadapt_flow/backends/windows_backend.py": { + "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_wide": 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_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 + }, + "packages/flow/openadapt_flow/cli_deferred.py": { + "says_success": 1, + "cmp_literal": 4 + }, + "packages/flow/openadapt_flow/cli_handoff.py": { + "swallow": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/cli_handoff_list.py": { + "swallow": 1 + }, + "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_redact_report.py": { + "empty_change_set": 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, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/cloud_seal.py": { + "cmp_literal": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/compile_agent/code_action.py": { + "swallow": 9, + "swallow_wide": 4, + "slice_count": 1, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/compile_agent/driven.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/compile_agent/harness.py": { + "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 + }, + "packages/flow/openadapt_flow/compile_agent/pipeline.py": { + "cmp_literal": 7, + "swallow": 2, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/compile_agent/repair_bridge.py": { + "cmp_literal": 4, + "swallow": 2 + }, + "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/annotate.py": { + "swallow_wide": 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/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, + "swallow": 2, + "swallow_wide": 1, + "slice_count": 1, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/compiler/compose_authoring.py": { + "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_wide": 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, + "swallow_wide": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/compiler/probing.py": { + "cmp_literal": 4, + "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_unchanged": 1 + }, + "packages/flow/openadapt_flow/connector/daemon.py": { + "cmp_literal": 4, + "swallow": 2, + "swallow_wide": 6 + }, + "packages/flow/openadapt_flow/connector/egress.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/connector/executor.py": { + "cmp_literal": 18, + "swallow": 6, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/connector/windows_service.py": { + "swallow": 6, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/connector/windows_tokens.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/console/app.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/console/attention.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/console/data.py": { + "cmp_literal": 5, + "swallow": 5, + "swallow_wide": 1, + "empty_change_set": 2 + }, + "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/countersign/vault.py": { + "swallow": 1 + }, + "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/emit/mcp_governed.py": { + "cmp_literal": 2, + "swallow": 2 + }, + "packages/flow/openadapt_flow/emit/mcp_tool.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/exceptions/cli.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/exceptions/mcp_server.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/exceptions/registry.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/exceptions/watch.py": { + "swallow": 8, + "swallow_wide": 4 + }, + "packages/flow/openadapt_flow/execute/dispatch.py": { + "cmp_literal": 2 + }, + "packages/flow/openadapt_flow/execute/service.py": { + "swallow": 2, + "swallow_wide": 3 + }, + "packages/flow/openadapt_flow/execution_profiles.py": { + "says_success": 1, + "cmp_literal": 17, + "bool_fold": 17, + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/extension_network.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/failure_signals.py": { + "says_success": 1, + "cmp_literal": 6, + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/fault_gate.py": { + "cmp_literal": 2, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/fhir_setup.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/fleet/canary.py": { + "cmp_literal": 2, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/fleet/hub.py": { + "says_success": 4 + }, + "packages/flow/openadapt_flow/fleet/policy.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/fleet/status.py": { + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/flight/cli.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/flight/computer.py": { + "says_success": 1, + "swallow": 4, + "swallow_wide": 8 + }, + "packages/flow/openadapt_flow/flight/gate.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/flight/proxy.py": { + "says_success": 1, + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/flight/scrub.py": { + "bool_fold": 1, + "slice_count": 4 + }, + "packages/flow/openadapt_flow/flight/timeline.py": { + "says_success": 1, + "swallow": 2 + }, + "packages/flow/openadapt_flow/form_tx/judge.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/form_tx/playwright_surface.py": { + "swallow": 16 + }, + "packages/flow/openadapt_flow/form_tx/receipt.py": { + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/form_tx/reconciler.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/form_tx/session_lease.py": { + "cmp_literal": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/form_tx/types.py": { + "bool_fold": 1, + "says_success": 1 + }, + "packages/flow/openadapt_flow/generate/compositional.py": { + "cmp_literal": 3, + "swallow": 1, + "says_unchanged": 2 + }, + "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": { + "swallow_wide": 1, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/generate/zero_touch.py": { + "cmp_literal": 4, + "swallow": 2, + "swallow_wide": 3, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/guard.py": { + "says_success": 1, + "cmp_literal": 3, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/halt_cleanup.py": { + "bool_fold": 1, + "swallow": 5, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/handoff.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/handoffs/followup.py": { + "slice_count": 1, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/handoffs/line.py": { + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/handoffs/payer.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/handoffs/readers.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/hard_invariants.py": { + "says_success": 2, + "cmp_literal": 1, + "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": { + "says_success": 12, + "cmp_literal": 6, + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/hosted.py": { + "cmp_literal": 5, + "swallow": 8, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/intake/param_gate.py": { + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/integrations/agents/__init__.py": { + "swallow": 1, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/integrations/agents/skills.py": { + "cmp_literal": 6, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/interactive_recorder.py": { + "swallow": 20, + "swallow_wide": 15 + }, + "packages/flow/openadapt_flow/interchange/conformance.py": { + "cmp_literal": 3 + }, + "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, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/jit/adapters.py": { + "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_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 + }, + "packages/flow/openadapt_flow/learn.py": { + "cmp_literal": 4 + }, + "packages/flow/openadapt_flow/learn_probe.py": { + "cmp_literal": 1, + "bool_fold": 1 + }, + "packages/flow/openadapt_flow/learning/branch_teach.py": { + "bool_fold": 3 + }, + "packages/flow/openadapt_flow/learning/gate.py": { + "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_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 + }, + "packages/flow/openadapt_flow/mockmed/fault_server.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/models/runtime.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/multi_surface_record.py": { + "swallow": 3 + }, + "packages/flow/openadapt_flow/network_capture.py": { + "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, + "swallow_wide": 2 + }, + "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": 5 + }, + "packages/flow/openadapt_flow/production_qualification.py": { + "empty_change_set": 1 + }, + "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, + "empty_change_set": 1 + }, + "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 + }, + "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, + "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, + "swallow_wide": 1, + "slice_count": 1, + "empty_change_set": 3 + }, + "packages/flow/openadapt_flow/qualify/faults.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/qualify/result.py": { + "says_success": 3, + "cmp_literal": 15, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/readback_ladder.py": { + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/readiness/cdp_wire.py": { + "cmp_literal": 1, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/readiness/compare.py": { + "says_success": 2, + "swallow": 1 + }, + "packages/flow/openadapt_flow/readiness/devtools_relay.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/readiness/export.py": { + "says_success": 1 + }, + "packages/flow/openadapt_flow/readiness/runner.py": { + "says_success": 6, + "cmp_literal": 3, + "swallow": 2, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/receipt.py": { + "says_success": 1, + "cmp_literal": 9, + "bool_fold": 8, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/receipt_record.py": { + "says_success": 1, + "cmp_literal": 5, + "bool_fold": 3, + "swallow": 3, + "swallow_wide": 1 + }, + "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, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/record_sor.py": { + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/recorder.py": { + "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, + "swallow": 1 + }, + "packages/flow/openadapt_flow/repair/campaign.py": { + "cmp_literal": 2, + "bool_fold": 1, + "swallow": 1, + "swallow_wide": 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/element_identity.py": { + "swallow_wide": 3 + }, + "packages/flow/openadapt_flow/repair/hold.py": { + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/repair/lifecycle.py": { + "cmp_literal": 5, + "says_unchanged": 4 + }, + "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, + "swallow_wide": 11, + "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/request_binding.py": { + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/rest_setup.py": { + "swallow": 1, + "swallow_wide": 2, + "empty_change_set": 2 + }, + "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, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/rl_env/environment.py": { + "swallow": 10, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/rl_env/parallel.py": { + "cmp_literal": 2, + "swallow_wide": 1 + }, + "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, + "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 + }, + "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, + "swallow_wide": 3, + "says_unchanged": 2, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/rollback_qualify.py": { + "swallow": 2, + "swallow_wide": 1 + }, + "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/run_ledger/cli.py": { + "says_success": 1, + "bool_fold": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/run_ledger/collect.py": { + "says_success": 5, + "cmp_literal": 5 + }, + "packages/flow/openadapt_flow/run_ledger/outcome.py": { + "says_success": 6, + "cmp_literal": 2, + "says_unchanged": 5 + }, + "packages/flow/openadapt_flow/run_ledger/readers.py": { + "says_success": 4, + "cmp_literal": 5, + "bool_fold": 1, + "swallow": 1 + }, + "packages/flow/openadapt_flow/run_ledger/store.py": { + "cmp_literal": 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, + "swallow_wide": 2 + }, + "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, + "swallow_wide": 4 + }, + "packages/flow/openadapt_flow/runtime/actuators/session_headers.py": { + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/actuators/web_form.py": { + "swallow": 4, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/admitted_composition.py": { + "says_success": 3, + "cmp_literal": 10, + "bool_fold": 2, + "swallow": 3, + "says_unchanged": 1 + }, + "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, + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/runtime/durable/attended.py": { + "cmp_literal": 11, + "bool_fold": 1, + "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 + }, + "packages/flow/openadapt_flow/runtime/durable/authority.py": { + "cmp_literal": 6, + "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": { + "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, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/effects/_common.py": { + "bool_fold": 1, + "slice_count": 1, + "empty_change_set": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/adapter.py": { + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/api_recheck.py": { + "says_success": 4, + "cmp_literal": 5, + "swallow": 1, + "swallow_wide": 1 + }, + "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, + "swallow": 2 + }, + "packages/flow/openadapt_flow/runtime/effects/desktop_readback.py": { + "cmp_literal": 1, + "swallow_wide": 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, + "empty_change_set": 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, + "swallow_wide": 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, + "swallow_wide": 1 + }, + "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, + "swallow_wide": 1, + "empty_change_set": 1 + }, + "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, + "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_wide": 6 + }, + "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/healing/pipeline.py": { + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/runtime/hover_evidence.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/runtime/identity.py": { + "swallow_wide": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/runtime/identity_census.py": { + "swallow": 1, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/identity_looks.py": { + "swallow": 5 + }, + "packages/flow/openadapt_flow/runtime/identity_vlm.py": { + "swallow": 2 + }, + "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_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/process_v1.py": { + "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": 4 + }, + "packages/flow/openadapt_flow/runtime/replay/settling.py": { + "swallow": 5, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/replayer.py": { + "cmp_literal": 26, + "bool_fold": 12, + "swallow": 57, + "swallow_wide": 46, + "slice_count": 1, + "empty_change_set": 3 + }, + "packages/flow/openadapt_flow/runtime/resolver.py": { + "cmp_literal": 1, + "swallow": 3, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/runtime/second_factor_step.py": { + "says_success": 1, + "swallow": 1, + "swallow_wide": 3 + }, + "packages/flow/openadapt_flow/runtime/surfaces.py": { + "swallow": 9, + "swallow_wide": 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, + "swallow_wide": 8, + "says_unchanged": 1 + }, + "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/sealed_set.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/second_factor.py": { + "swallow": 2, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/second_factor_terminal.py": { + "swallow": 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, + "swallow_wide": 7, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/shadow_db.py": { + "cmp_literal": 1, + "bool_fold": 1, + "swallow": 2, + "swallow_wide": 3 + }, + "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, + "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, + "swallow_wide": 2 + }, + "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, + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/transforms.py": { + "says_unchanged": 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, + "empty_change_set": 1 + }, + "packages/flow/openadapt_flow/tx/lens.py": { + "says_success": 1, + "swallow_wide": 1, + "else_success": 1 + }, + "packages/flow/openadapt_flow/tx/wire_tap.py": { + "bool_fold": 2, + "swallow": 3, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/txplan/adapters.py": { + "bool_fold": 1, + "swallow": 2, + "swallow_wide": 1 + }, + "packages/flow/openadapt_flow/txplan/audit.py": { + "slice_count": 1 + }, + "packages/flow/openadapt_flow/txplan/cli.py": { + "says_success": 1, + "cmp_literal": 1 + }, + "packages/flow/openadapt_flow/txplan/engine.py": { + "says_success": 9, + "cmp_literal": 6, + "bool_fold": 2, + "swallow_wide": 1, + "says_unchanged": 1, + "empty_change_set": 4 + }, + "packages/flow/openadapt_flow/txplan/proxy.py": { + "cmp_literal": 1, + "swallow": 1, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/txplan/scoped.py": { + "says_success": 1, + "cmp_literal": 3, + "else_success": 1 + }, + "packages/flow/openadapt_flow/undo_proposal.py": { + "cmp_literal": 5, + "bool_fold": 1, + "swallow": 4, + "swallow_wide": 3, + "slice_count": 1 + }, + "packages/flow/openadapt_flow/validation/behavioral_generalization.py": { + "says_success": 1, + "cmp_literal": 3, + "bool_fold": 2, + "swallow_wide": 4 + }, + "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/variants.py": { + "says_unchanged": 1 + }, + "packages/flow/openadapt_flow/verifier.py": { + "says_success": 4, + "cmp_literal": 39, + "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_wide": 2 + }, + "packages/flow/openadapt_flow/verify_run.py": { + "says_success": 4, + "cmp_literal": 36, + "bool_fold": 2, + "swallow": 5, + "swallow_wide": 4, + "empty_change_set": 1 + }, + "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 + }, + "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, + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/wrap/__init__.py": { + "swallow_wide": 2 + }, + "packages/flow/openadapt_flow/wrap/approval_gate.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/wrap/candidate.py": { + "swallow": 1 + }, + "packages/flow/openadapt_flow/wrap/cli.py": { + "says_success": 1, + "swallow": 2 + }, + "packages/flow/openadapt_flow/wrap/dispatch_cli.py": { + "says_success": 3 + }, + "packages/flow/openadapt_flow/wrap/fallback.py": { + "says_success": 2, + "cmp_literal": 5, + "swallow": 2, + "swallow_wide": 2, + "empty_change_set": 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 + }, + "openadapt/cli.py": { + "cmp_literal": 1, + "swallow": 10, + "swallow_wide": 7, + "slice_count": 2 + }, + "openadapt/quickstart/engine.py": { + "cmp_literal": 7, + "swallow": 3 + }, + "openadapt/quickstart/notices.py": { + "swallow": 1 + }, + "openadapt/quickstart/openemr.py": { + "cmp_literal": 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": { + "swallow": 5 + }, + "openadapt/seal_publish.py": { + "swallow": 1 + }, + "openadapt/seal_view/__init__.py": { + "swallow": 2 + }, + "scripts/ci/attestation.py": { + "bool_fold": 2 + }, + "scripts/ci/check_windows_governed_safety.py": { + "says_success": 2, + "cmp_literal": 1 + }, + "scripts/ci/flow_shard_measurement.py": { + "cmp_literal": 1, + "bool_fold": 1, + "swallow_wide": 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, + "swallow_wide": 1, + "empty_change_set": 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..7b964c1cea --- /dev/null +++ b/packages/flow/tests/failopen/harness.py @@ -0,0 +1,401 @@ +"""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). +- 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 +mutation. +""" + +from __future__ import annotations + +import copy +from collections.abc import Callable, Sequence +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", "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 +#: 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) +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 + #: 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 + #: 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" + #: 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) + #: 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) +class Failure: + site: str + mutator: str + 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.key}" + + +REGISTRY: dict[str, 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 + + +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 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.""" + + from tests.failopen import mutators + + failures: list[Failure] = [] + 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 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"{at} {seed.note}: pass={got}".replace(" ", " "), + ) + ) + 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 + ran += 1 + if m.check is not None: + problem = m.check() + if problem: + 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( + 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"{at}: {m.label}: still passes") + ) + 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") + ) + if not ran and only is None: + failures.append(Failure(spec.id, "spec", "P0", "no mutation applies")) + 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..d28fac6974 --- /dev/null +++ b/packages/flow/tests/failopen/mutators.py @@ -0,0 +1,275 @@ +"""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, 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 +from pathlib import Path +from typing import Any, Optional + +from tests.failopen.harness import ABSENT, Seed, SiteSpec + +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 = "" + #: 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]]: + """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 = (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" + ) + 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, []) + 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( + "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: + # 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 + [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])]), # 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", + adverse=True, + ) + if spec.subject is not None: + yield Mutation( + "M8", + "a result from another run", + spec.subject.set(ev, "other-run"), + "not_pass", + ) + for which, lens in enumerate(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 {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) + 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.partial is not None: + for label, partial in spec.partial(ev): + # 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" + ) + 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"{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"{case.label}: 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_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_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_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_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_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/_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/_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 new file mode 100644 index 0000000000..a96d02ec57 --- /dev/null +++ b/packages/flow/tests/failopen/selftest/specs.py @@ -0,0 +1,483 @@ +"""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_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 + +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"}, + # 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] + + [{"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, 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": []} + + 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, *(("a_code_no_list_names",) if unlisted else ())) + 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"}) +# 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) ------------------ + + +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, base_scored: int = 20) -> dict[str, Any]: + """Twenty runs planned: two scenarios, ten repetitions.""" + base = { + "schema": "openadapt.agent-test.baseline/v1", + "app": "app", + "app_pack_digest": "a", + "scenarios_digest": "s", + "images": ["img"], + "agent": "agent", + "repetitions": 10, + "scored": base_scored, + "rates": _summary(base_scored)["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(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(18), + ) + + +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) ------------------------ + +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, + _v_s8_governed_pre.check, + _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") + + +pair( + "wire_tap_triple_slash", + _relay, + _v_wire_tap_pre.relay_redirect_location, + _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_folds._unplanned(verify_run._aggregate), + ), + ( + "S9_observed_empty", + verify_run_folds.observed_spec, + _v_s9_verify_run_pre._observed, + verify_run_folds._unplanned(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..beab0b242a --- /dev/null +++ b/packages/flow/tests/failopen/sites/connector_status.py @@ -0,0 +1,92 @@ +"""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)" + ), + known=[ + "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 new file mode 100644 index 0000000000..4da988d6e3 --- /dev/null +++ b/packages/flow/tests/failopen/sites/governed_safety.py @@ -0,0 +1,86 @@ +"""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", + "site", + ) +) 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..3793964b85 --- /dev/null +++ b/packages/flow/tests/failopen/sites/hard_invariants.py @@ -0,0 +1,56 @@ +"""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] = { + "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", + level=lambda out: Status(out.status), + 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(), + 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..a51245ded8 --- /dev/null +++ b/packages/flow/tests/failopen/sites/receipt_lines.py @@ -0,0 +1,145 @@ +"""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: 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"), + 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 new file mode 100644 index 0000000000..06cbb90b9f --- /dev/null +++ b/packages/flow/tests/failopen/sites/verify_run_folds.py @@ -0,0 +1,193 @@ +"""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 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: 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 = { + "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] + + +def aggregate_spec(fn: Callable[..., Any], id: str, kind: str = "site") -> SiteSpec: + return SiteSpec( + id=id, + classes="C2", + target="openadapt_flow.verify_run:_aggregate", + 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), + 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", + 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), + 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"], + }, + ) + + +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 new file mode 100644 index 0000000000..a0889b82b2 --- /dev/null +++ b/packages/flow/tests/failopen/sites/versions_judge.py @@ -0,0 +1,69 @@ +"""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 openadapt_flow.verdict import Status +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", + level=lambda out: Status(out.status), + 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..966663e7bc --- /dev/null +++ b/packages/flow/tests/failopen/sites/wire_tap_relay.py @@ -0,0 +1,58 @@ +"""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`` 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 + +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", "site") + ) + + +_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..d518969137 --- /dev/null +++ b/packages/flow/tests/failopen/test_kernel.py @@ -0,0 +1,328 @@ +"""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_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_copied_or_restored() -> None: + import dataclasses + + a = Subject(key="1", run_id="r1") + held = _result(a, "held") + with pytest.raises(TypeError): + 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_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 + + with pytest.raises(TypeError): + observe(probe, benign={TimeoutError: Observed(0)}) + + +@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..97eca77fb5 --- /dev/null +++ b/packages/flow/tests/failopen/test_kernel_mutants.py @@ -0,0 +1,142 @@ +"""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": ( + " matches[n] = [r for r in same_key if not binding_mismatches(item, r.subject)]\n", + " matches[n] = list(same_key)\n", + ), + "one writer wins": ( + " 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 shared:\n", + " elif len({r.status for r in got}) > 1:\n", + ), + "truncate at limit": ( + " 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", + " 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", + ), +} + + +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" + ) + 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) + 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 + + 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_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_registry_complete.py b/packages/flow/tests/failopen/test_registry_complete.py new file mode 100644 index 0000000000..0e0145754d --- /dev/null +++ b/packages/flow/tests/failopen/test_registry_complete.py @@ -0,0 +1,115 @@ +"""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(":") + 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 + 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: + 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).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_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..f707b7c8eb --- /dev/null +++ b/packages/flow/tests/failopen/test_sites.py @@ -0,0 +1,44 @@ +"""Every registered verdict site holds under every generic mutation. + +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 + +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")} + + +@pytest.mark.parametrize("spec_id", sorted(SPECS)) +def test_site_holds(spec_id: str) -> None: + 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_and_failures() -> None: + for spec in SPECS.values(): + if spec.kind == "owned": + 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 new file mode 100644 index 0000000000..0776318921 --- /dev/null +++ b/packages/flow/tests/failopen/test_verify_run_migration.py @@ -0,0 +1,111 @@ +"""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 + + +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. +VERDICTS = st.sampled_from([Verdict.CONFIRMED, Verdict.REFUTED, Verdict.INDETERMINATE]) +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(_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(_plan(items), 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" + + +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" + + +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_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 new file mode 100644 index 0000000000..78238ccd50 --- /dev/null +++ b/packages/flow/tests/test_verdict_folds_check.py @@ -0,0 +1,223 @@ +"""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', + "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", +} + + +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_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) + 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) + + +@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", + "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( + 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()", + "0 == len(changes)", + "[] == deleted", + ], +) +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 + + +@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") + 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( + "@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( + "\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({"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) == { + "a.py": {"swallow": 2} + } + + +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 + + 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 diff --git a/scripts/ci/check_windows_governed_safety.py b/scripts/ci/check_windows_governed_safety.py index c71fed852e..69c3448c12 100644 --- a/scripts/ci/check_windows_governed_safety.py +++ b/scripts/ci/check_windows_governed_safety.py @@ -37,6 +37,17 @@ from pathlib import Path from typing import Any +try: + from openadapt_flow.verdict import verdict_site +except ImportError: # standalone CI script without openadapt_flow installed + + def verdict_site(site: str, *, classes: str = "") -> Any: + def _wrap(fn: Any) -> Any: + fn.__verdict_site__ = site + return fn + + return _wrap + 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, @@ -87,6 +98,7 @@ def _diff_from_seed( return problems +@verdict_site("governed_safety.check", classes="C5") def check(evidence: Any) -> list[str]: """Return the safety violations in ``evidence``; empty means safe."""