diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0393-three-verdict-tiers-entity-scoped-frames-and.md b/capabilities/04-the-core-a-checked-entry-every-time/0393-three-verdict-tiers-entity-scoped-frames-and.md new file mode 100644 index 0000000000..f217631b54 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0393-three-verdict-tiers-entity-scoped-frames-and.md @@ -0,0 +1 @@ +| Three verdict tiers, entity-scoped frames and shadow mode by default: with `frame.database.entity_tables` (derived by `learn entities` from the setup: main tables, the tables a contract reads through, and the acting user's table), a row added or changed outside the entity tables (a scheduler, a queue, a recomputed total, a notification) is a logged side effect on a CONFIRMED result, by names only, and a candidate for the learner; a removed row, any entity-table row the write doesn't declare, another user's row and an unexcused column of the actor's row still refute. Settling ignores motion outside the scope; a generated read's own check columns are not compared on undeclared rows. The verifier waits for declared records with backoff (8 s budget, database reads only) before judging. A scope is admitted only when planted wrong-row, wrong-value, duplicate, sibling-edit, late-revert and lost-update faults and the actor-table attacks are all caught under it. A new contract is in shadow (`WriteResult.blocks` false, verdict recorded in full) until N clean checks in a row (20 to 50, default 30), then a person can turn gating on. Not yet: another user's unattributed edit of an entity-table record still stops the write; a harm confined to a non-entity table is logged, not stopped | (this PR) | Adversarial tests on SQLite (each safety-bar fault under a scope, settling under a moving queue, admission refusals); real-app replay pending | `openadapt-flow gate`, `openadapt-flow learn entities`, [VERDICT_TIERS.md](packages/flow/docs/VERDICT_TIERS.md) | diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index d6215a7b1d..e2666e5ac0 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -68,6 +68,7 @@ "fleet": "services fleet", "flight": "run --flight", "for-each": "run --for-each", + "gate": "verify gate", "guard": "run --guard", "hooks": "setup hooks", "induce": "compile --induce", diff --git a/packages/flow/docs/VERDICT_TIERS.md b/packages/flow/docs/VERDICT_TIERS.md new file mode 100644 index 0000000000..4e8146b111 --- /dev/null +++ b/packages/flow/docs/VERDICT_TIERS.md @@ -0,0 +1,125 @@ +# Verdict tiers, entity-scoped frames and shadow mode + +A whole-database frame stops a correct write whenever any row moves. On a +live app many rows move with no harm: a scheduler's heartbeat, a task queue, +prices or totals the app recomputes after a save, a notification for each +watcher of a record. This page describes how the verifier separates those +from real harm without letting any planted fault through. + +## Three tiers + +Every check of a write ends in one of these tiers. `WriteResult.tier` names +it, and `to_dict()` returns it with `side_effects`, `enforcement` and +`blocks`. + +| Tier | Outcome | What it covers | +| --- | --- | --- | +| `hard` | `REFUTED` | The target is missing, a value is wrong after normalization, a duplicate, a changed or removed row in a business-entity table that the write doesn't declare (including another user's row and an unexcused column of the acting user's row), a late revert, a lost update, any removed row, and anything no row comparison explains. | +| `logged` | `CONFIRMED` | The write holds, and rows moved only outside the entity tables (added or changed, never removed). Each is listed in the frame evidence as `side_effects`: table, change, row count and column names, never keys or values. The same rows go to `openadapt-flow learn` as candidate excuses. | +| `doubt` | `UNCERTAIN` | Timing or knowledge doubt that the verifier's own waiting didn't clear. | +| `clean` | `CONFIRMED` | Nothing else moved. | + +A logged pass is still `CONFIRMED`. A harm that slips through the logged +tier is therefore counted as a silent pass by any grader that reads the +outcome. The tier never hides a pass. + +### Retry before reporting a doubt + +Before a write is judged, the verifier waits for its declared records to +become visible: 0.5 s, then 1, 2 and 4 s, within 8 s in all +(`OPENADAPT_VERIFY_RETRY_S` sets the budget; 0 turns it off). The wait +reads only through database verifiers, so the wait itself can't move a +bookkeeping row. It never decides anything: the full judge runs afterwards +either way. A record that is present stops the wait at once. + +The database frame's own settling (`settle_s`, `settle_attempts`) ignores +motion in tables outside the entity tables, so a scheduler that never stops +doesn't keep a write unsettled. Those tables are still diffed against the +baseline in the read that is judged. + +## Entity-scoped frames + +`frame.database.entity_tables` lists the business-entity tables. When it is +set, the hard checks cover those tables and rows elsewhere are logged. The +tables the frame already names (`views`, `judged_by`, `new_row_fields`, +side records, learned excuses, owner tables, the app profile's rules) +always count as entity tables. When it is unset, every table is judged as +before. + +The list is derived from the setup, never written by hand +(`openadapt-flow learn entities`): + +- each kind's main table; +- every table a contract's own read selects from, which covers the child + tables a write adds and the tables a field's location reads through; +- the acting user's table: the one table that every column bound to an + actor parameter references by foreign key. When it can't be derived, no + scope is proposed, because another user's row must stay a stop. + +On a frame that diffs the whole database, a surface's own check columns +(`pin__*`, `empty__*`, which a generated read computes as 1 or 0) are not +compared on undeclared rows. One can flip with the clock and no write. The +stored columns they are computed from are compared themselves. + +## The safety bar + +A relaxation (an entity scope, or a learned mask) is admitted only if the +planted faults are all still caught under it +(`openadapt_flow.runtime.effects.admission`): + +- wrong row, wrong value, duplicate, sibling business-record edit, late + revert and lost update; +- for a relaxation that touches the acting user's table, another user's row + and another column of the actor's own row. + +Every class must have at least one case, every case must be caught, and +every case caught before the relaxation must be run again under it. +`fault_gate` names count for the same classes (`wrong_record` is a wrong +row, `unrelated_edit` a sibling edit). + +``` +openadapt-flow learn entities propose --manifest manifest.yaml --read read.yaml --out scope.json +openadapt-flow learn entities stage scope.json --out candidate/ +# run the planted faults against candidate/ and write faults.json +openadapt-flow learn entities apply scope.json --faults faults.json --by "A. Reviewer" +``` + +`faults.json` is `openadapt.relaxation-faults/v1`: the proposal's +`proposal_sha256` and one `{case, class, caught}` per case. `apply` refuses +results run under another proposal, and writes every contract or none. + +## Shadow mode by default + +A contract is new to an app until it has been seen to judge real writes +correctly. Until then (`enforcement: shadow`) its verdicts are computed and +recorded in full, but `WriteResult.blocks` is false, so a caller that stops +on a verdict doesn't stop. Each check is appended to the contract's gate log +(`OPENADAPT_GATE_DIR`, by default `/gates`, else +`~/.openadapt/gates`; names and outcomes only). + +After N checks in a row with no stop of a correct write, gating is offered, +and a person turns it on: + +``` +openadapt-flow gate status contract.yaml +openadapt-flow gate label contract.yaml caught # a real harm: keeps the run +openadapt-flow gate label contract.yaml false_stop # breaks it, and is counted +openadapt-flow gate enable contract.yaml --by "A. Reviewer" # refused until offered +``` + +N is `OPENADAPT_GATE_CLEAN_RUNS`, kept between 20 and 50 (default 30). A +stop that nobody has labelled breaks the run, since it may be a false stop. +`OPENADAPT_ENFORCEMENT=gating` gates every contract (the behaviour before +shadow mode), and `shadow` keeps every contract in shadow. Shadow mode +changes only `blocks`. The ledger still holds a refuted attempt, so a retry +is never sent silently. + +## Limits + +- An edit by another user to a record in an entity table, with no audit + log or modified-by field to attribute it, still stops the write. Nothing + in the store tells it apart from the agent editing a sibling record. +- A harm confined to a table outside the entity tables (an agent that + changes a notification or a queue row) is logged, not stopped. The scope + is admitted only when the planted faults, which target business records, + are all caught. It is not a check on side tables. diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/gate.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/gate.md new file mode 100644 index 0000000000..34d31c4394 --- /dev/null +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/gate.md @@ -0,0 +1 @@ +Show a contract's shadow-mode run of clean checks, label a stop as a real catch or a false stop, and turn gating on once it is offered (`docs/VERDICT_TIERS.md`). diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md index f7880c8387..221277dff2 100644 --- a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md @@ -1 +1 @@ -Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts. +Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), scope the frame to the setup's business entities (`learn entities`, admitted only if the planted faults are still caught), and write them into the contracts. diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 6f6531ac33..45ad7a1a4b 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13171,8 +13171,6 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: from openadapt_flow.cli_fleet import register_fleet_parser from openadapt_flow.cli_receipt import register as _register_receipt from openadapt_flow.cli_reconcile import register as _register_reconcile - from openadapt_flow.cli_rollback import register as _register_rollback - from openadapt_flow.cli_shadow import register as _register_shadow from openadapt_flow.compile_agent.cli import add_parser as _add_compile_agent_parser from openadapt_flow.flight.cli import add_parser as _add_flight_parser from openadapt_flow.hooks.cli import add_parser as _add_hooks_parser @@ -13181,8 +13179,9 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: from openadapt_flow.txplan.cli import add_parser as _add_plan_parser from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser - _register_rollback(sub) - _register_shadow(sub) + __import__("openadapt_flow.cli_rollback", fromlist=["_"]).register(sub) + __import__("openadapt_flow.cli_shadow", fromlist=["_"]).register(sub) + __import__("openadapt_flow.cli_gate", fromlist=["_"]).register(sub) __import__("openadapt_flow.readiness.cli", fromlist=["cli"]).register(sub) _register_receipt(sub) _register_learn(sub) @@ -13633,6 +13632,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]: "openadapt_flow.cli_no_outbound:_cmd_list", "openadapt_flow.cli_no_outbound:_cmd_remove", "openadapt_flow.cli_local_seal:_guarded", + "openadapt_flow.cli_gate:cmd_gate", "openadapt_flow.cli_receipt:cmd_anchor", "openadapt_flow.cli_receipt:cmd_keys_export", "openadapt_flow.cli_receipt:cmd_verify", diff --git a/packages/flow/openadapt_flow/cli_gate.py b/packages/flow/openadapt_flow/cli_gate.py new file mode 100644 index 0000000000..acfdd136ad --- /dev/null +++ b/packages/flow/openadapt_flow/cli_gate.py @@ -0,0 +1,81 @@ +"""CLI: ``openadapt-flow gate`` -- shadow mode and gating, per contract. + + openadapt-flow gate status contract.yaml + openadapt-flow gate label contract.yaml caught|false_stop + openadapt-flow gate enable contract.yaml --by "A. Reviewer" + openadapt-flow gate disable contract.yaml --by "A. Reviewer" + +See ``openadapt_flow.enforcement`` and ``docs/VERDICT_TIERS.md``. +""" + +from __future__ import annotations + +import argparse +import json +import sys + + +def register(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "gate", + help="Show a contract's shadow run of clean checks, label a stop, or " + "turn gating on once it is offered", + allow_abbrev=False, + ) + gsub = p.add_subparsers(dest="gate_command", required=True) + s = gsub.add_parser( + "status", + help="mode, clean checks in a row, whether gating is offered", + allow_abbrev=False, + ) + s.add_argument("contract") + s.add_argument("--json", action="store_true") + s.set_defaults(func=cmd_gate) + s = gsub.add_parser( + "label", + help="label one stop: caught (a real harm) or false_stop", + allow_abbrev=False, + ) + s.add_argument("contract") + s.add_argument("write_id") + s.add_argument("verdict", choices=("caught", "false_stop")) + s.set_defaults(func=cmd_gate) + for name, text in ( + ("enable", "turn gating on (only once it is offered)"), + ("disable", "go back to shadow"), + ): + s = gsub.add_parser(name, help=text, allow_abbrev=False) + s.add_argument("contract") + s.add_argument("--by", required=True, help="who decided") + s.set_defaults(func=cmd_gate) + + +def cmd_gate(args: argparse.Namespace) -> int: + from openadapt_flow import enforcement + + digest = enforcement.contract_digest(args.contract) + if args.gate_command == "label": + enforcement.label(digest, args.write_id, args.verdict) + st = enforcement.status(digest) + elif args.gate_command == "enable": + try: + st = enforcement.enable(digest, args.by) + except enforcement.GateRefused as exc: + print(f"gate: {exc}", file=sys.stderr) + return 2 + elif args.gate_command == "disable": + st = enforcement.disable(digest, args.by) + else: + st = enforcement.status(digest) + if getattr(args, "json", False): + print(json.dumps(st.to_dict(), indent=2)) + return 0 + print(f"mode: {st.mode}") + print(f"clean checks in a row: {st.clean_in_a_row} of {st.needed}") + print(f"checks recorded: {st.checks}; stops labelled false: {st.false_stops}") + if st.offered: + print( + "gating is offered: run `openadapt-flow gate enable " + f"{args.contract} --by ` to let this contract block" + ) + return 0 diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 35b959b74d..7095a2fea8 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -66,6 +66,7 @@ "fleet": "services fleet", "flight": "run --flight", "for-each": "run --for-each", + "gate": "verify gate", "guard": "run --guard", "hooks": "setup hooks", "induce": "compile --induce", diff --git a/packages/flow/openadapt_flow/enforcement.py b/packages/flow/openadapt_flow/enforcement.py new file mode 100644 index 0000000000..20cf594066 --- /dev/null +++ b/packages/flow/openadapt_flow/enforcement.py @@ -0,0 +1,225 @@ +"""Shadow mode by default: a new contract observes before it may block. + +A contract is new to an app until it has been seen to judge real writes +correctly. Until then its verdicts are computed and recorded in full, but a +caller that stops on a verdict (``WriteResult.blocks``) doesn't stop: the +contract is in ``shadow``. Each verdict is appended to the contract's gate +log. After ``N`` checks in a row with no stop of a correct write, gating is +*offered*; a person turns it on (``openadapt-flow gate enable``) and from +then on a verdict that isn't CONFIRMED blocks (``gating``). + +What counts as clean: a CONFIRMED check, or a stop a person labelled a true +catch (``openadapt-flow gate label caught``). Any other stop +breaks the run, since until someone looks it may be a false stop. A stop a +person labels ``false_stop`` breaks it too, and says so in ``status``. + +``N`` is ``OPENADAPT_GATE_CLEAN_RUNS`` (20 to 50, default 30). Setting +``OPENADAPT_ENFORCEMENT=gating`` gates every contract (the behaviour before +shadow mode); ``shadow`` keeps every contract in shadow. The log lives under +``OPENADAPT_GATE_DIR`` (default ``/gates``, else +``~/.openadapt/gates``), one JSON line per +check, names and outcomes only, never values. A log that can't be written +never changes a verdict; it only leaves the contract in shadow. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional + +SCHEMA = "openadapt.gate/v1" +MIN_CLEAN_RUNS = 20 +MAX_CLEAN_RUNS = 50 +DEFAULT_CLEAN_RUNS = 30 +MODES = ("shadow", "gating") + + +def clean_runs_needed() -> int: + """``N``: clean checks in a row before gating is offered (20 to 50).""" + + raw = os.environ.get("OPENADAPT_GATE_CLEAN_RUNS", "") + try: + n = int(raw) if raw.strip() else DEFAULT_CLEAN_RUNS + except ValueError: + n = DEFAULT_CLEAN_RUNS + return min(MAX_CLEAN_RUNS, max(MIN_CLEAN_RUNS, n)) + + +def gate_dir() -> Path: + raw = os.environ.get("OPENADAPT_GATE_DIR") + if raw: + return Path(raw) + ledger = os.environ.get("OPENADAPT_LEDGER_DIR") + if ledger: + return Path(ledger) / "gates" + return Path.home() / ".openadapt" / "gates" + + +def _file(digest: str) -> Path: + name = hashlib.sha256(str(digest).encode("utf-8")).hexdigest()[:32] + return gate_dir() / f"{name}.jsonl" + + +def _append(digest: str, entry: dict[str, Any]) -> None: + path = _file(digest) + # Private, like the ledger it may sit in: names and outcomes only, but + # still nobody else's to read. + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(path.parent, 0o700) + line = json.dumps({"schema": SCHEMA, "contract": digest, **entry}, sort_keys=True) + # One short line per append: O_APPEND keeps concurrent writers whole. + from openadapt_flow.private_file import open_binary + + fd = open_binary(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + try: + os.write(fd, (line + "\n").encode("utf-8")) + finally: + os.close(fd) + + +def _entries(digest: str) -> list[dict[str, Any]]: + path = _file(digest) + if not path.exists(): + return [] + out = [] + for line in path.read_text(encoding="utf-8").splitlines(): + try: + item = json.loads(line) + except ValueError: + continue + if isinstance(item, dict) and item.get("contract") == digest: + out.append(item) + return out + + +@dataclass +class GateStatus: + contract: str + mode: str + clean_in_a_row: int + needed: int + checks: int + false_stops: int + offered: bool + + def to_dict(self) -> dict[str, Any]: + return { + "contract": self.contract, + "mode": self.mode, + "clean_in_a_row": self.clean_in_a_row, + "needed": self.needed, + "checks": self.checks, + "false_stops_labelled": self.false_stops, + "gating_offered": self.offered, + } + + +def status(digest: str) -> GateStatus: + """The contract's mode and its run of clean checks, from its log.""" + + entries = _entries(digest) + labels = { + str(e.get("write_id")): str(e.get("label")) + for e in entries + if e.get("event") == "label" + } + checks = [e for e in entries if e.get("event") == "check"] + run = 0 + from openadapt_flow.verifier import Outcome + + for e in checks: + clean = e.get("outcome") == Outcome.CONFIRMED.value or ( + labels.get(str(e.get("write_id"))) == "caught" + ) + run = run + 1 if clean else 0 + needed = clean_runs_needed() + forced = os.environ.get("OPENADAPT_ENFORCEMENT", "").strip().lower() + enabled = None + for e in entries: + if e.get("event") == "enable": + enabled = True + elif e.get("event") == "disable": + enabled = False + if forced in MODES: + mode = forced + else: + mode = "gating" if enabled else "shadow" + return GateStatus( + contract=digest, + mode=mode, + clean_in_a_row=run, + needed=needed, + checks=len(checks), + false_stops=sum(1 for v in labels.values() if v == "false_stop"), + offered=mode == "shadow" and run >= needed, + ) + + +def observe(digest: str, result: Any) -> str: + """Record one check and return the contract's mode for it. Never raises: + a log that can't be read or written leaves the contract where it was + (``shadow`` unless gating was on, or forced by the environment).""" + + try: + _append( + digest, + { + "event": "check", + "at": time.time(), + "write_id": str(getattr(result, "write_id", "") or ""), + "outcome": str(getattr(getattr(result, "outcome", ""), "value", "")), + "tier": str(getattr(result, "tier", "")), + }, + ) + except (OSError, TypeError, ValueError): # the log never changes a verdict + pass + try: + return status(digest).mode + except (OSError, TypeError, ValueError): + forced = os.environ.get("OPENADAPT_ENFORCEMENT", "").strip().lower() + return forced if forced in MODES else "shadow" + + +def label(digest: str, write_id: str, verdict: str) -> None: + """A person's label for one stop: ``caught`` (a real harm) or + ``false_stop`` (a correct write stopped).""" + + if verdict not in ("caught", "false_stop"): + raise ValueError("label is 'caught' or 'false_stop'") + _append( + digest, + {"event": "label", "at": time.time(), "write_id": write_id, "label": verdict}, + ) + + +class GateRefused(ValueError): + pass + + +def enable(digest: str, by: str) -> GateStatus: + """Turn gating on, only once it is offered (``N`` clean checks in a row).""" + + st = status(digest) + if not st.offered and st.mode != "gating": + raise GateRefused( + f"gating is not offered yet: {st.clean_in_a_row} of {st.needed} clean " + "checks in a row" + ) + _append(digest, {"event": "enable", "at": time.time(), "by": by}) + return status(digest) + + +def disable(digest: str, by: str) -> GateStatus: + _append(digest, {"event": "disable", "at": time.time(), "by": by}) + return status(digest) + + +def contract_digest(path: Optional[str]) -> str: + from openadapt_flow.verifier import Contract + + return Contract.load(str(path)).digest diff --git a/packages/flow/openadapt_flow/learn.py b/packages/flow/openadapt_flow/learn.py index eb11a04cf6..ede8282dee 100644 --- a/packages/flow/openadapt_flow/learn.py +++ b/packages/flow/openadapt_flow/learn.py @@ -131,6 +131,18 @@ def episode_record(episode: Any, result: Any) -> dict[str, Any]: moves = frame.get("moves") if isinstance(moves, list): out["moves"] = [dict(m) for m in moves if isinstance(m, Mapping)] + side = frame.get("side_effect_moves") + from openadapt_flow.verifier import Outcome + + if ( + out["outcome"] == Outcome.CONFIRMED.value + and isinstance(side, list) + and side + ): + # Logged side effects (rows outside the entity tables): the + # write passed, and these are the learner's candidates. + out["moves"] = [dict(m) for m in side if isinstance(m, Mapping)] + out["logged"] = True out["has_database"] = isinstance(frame.get("database"), Mapping) return out @@ -339,8 +351,13 @@ def _why_ignored(ep: Mapping[str, Any]) -> Optional[str]: if ep.get("frame") != "refuted": return "nothing moved in the read-only window" return _why_rows_ignored(ep) + from openadapt_flow.verifier import Outcome + outcome = ep.get("outcome") - if outcome == "CONFIRMED": + if outcome == Outcome.CONFIRMED.value: + if ep.get("logged") and ep.get("delta") == "held": + # Passed with logged side effects: they are candidate excuses. + return _why_rows_ignored(ep) return "confirmed: nothing moved that needs an excuse" if ep.get("delta") != "held": return "the declared effects didn't hold" @@ -951,6 +968,10 @@ def build_parser(p: argparse.ArgumentParser) -> argparse.ArgumentParser: from openadapt_flow import learn_probe learn_probe.register_parser(steps) + + from openadapt_flow import learn_entities + + learn_entities.register(steps) return p diff --git a/packages/flow/openadapt_flow/learn_entities.py b/packages/flow/openadapt_flow/learn_entities.py new file mode 100644 index 0000000000..3e55c94e14 --- /dev/null +++ b/packages/flow/openadapt_flow/learn_entities.py @@ -0,0 +1,283 @@ +"""``openadapt-flow learn entities``: scope a setup's frames to its entities. + +A whole-database frame stops a correct write when any row anywhere moves: +a scheduler's heartbeat, a task queue, prices the app recomputes, a +notification for each watcher. ``frame.database.entity_tables`` scopes the +hard check to the business-entity tables; rows elsewhere are logged as side +effects and offered to the learner (``docs/VERDICT_TIERS.md``). + +The entity tables are derived from the setup, never named by hand: + +- each kind's main table (the manifest's ``main_table``); +- every table a contract's own read selects from, which covers the child + tables a write adds and the tables a field's location reads through (a + project's customer); +- the tables the frame already names (``views``, ``judged_by``, + ``new_row_fields``); +- the acting user's table: the one table every column bound to an actor + parameter references (``learn_probe.users_for_actor_params``). Without it + no scope is proposed, since another user's row must stay a stop. + +Three steps, so the scope is admitted only on evidence (``admission``): + + openadapt-flow learn entities propose --manifest m.yaml --read read.yaml --out scope.json + openadapt-flow learn entities stage scope.json --out candidate/ # a scoped copy + # run the planted faults against candidate/ -> faults.json + openadapt-flow learn entities apply scope.json --faults faults.json --by "A. Reviewer" + +``apply`` refuses unless every class of the safety bar, and the actor-table +attacks, ran against the staged scope and were all caught. +""" + +from __future__ import annotations + +import argparse +import json +import re +import shutil +import sys +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +import yaml + +SCHEMA = "openadapt.entity-scope/v1" + +_FROM = re.compile( + r"\b(?:FROM|JOIN)\s+((?:[`\"]?[A-Za-z_][\w$]*[`\"]?\.)?[`\"]?[A-Za-z_][\w$]*[`\"]?)", + re.IGNORECASE, +) + + +class EntityScopeError(ValueError): + pass + + +def tables_in_sql(sql: str) -> set[str]: + """Table names a read selects from (``FROM`` / ``JOIN``), unquoted.""" + + out = set() + for m in _FROM.finditer(sql or ""): + name = m.group(1).replace("`", "").replace('"', "") + out.add(name) + return out + + +def _sql_of(doc: Any) -> list[str]: + found: list[str] = [] + + def walk(v: Any) -> None: + if isinstance(v, Mapping): + q = v.get("sql_query") + if isinstance(q, str): + found.append(q) + for x in v.values(): + walk(x) + elif isinstance(v, list): + for x in v: + walk(x) + + walk(doc) + return found + + +def _contracts(manifest: Path) -> list[Path]: + from openadapt_flow.learn import contracts_from_manifest + + return sorted({p for ps in contracts_from_manifest(manifest).values() for p in ps}) + + +def derive(manifest: Path, schema: Any) -> dict[str, Any]: + """The proposal: entity tables and the contracts they apply to.""" + + from openadapt_flow.app_profiles import table_name + from openadapt_flow.learn_probe import users_for_actor_params + + data = yaml.safe_load(Path(manifest).read_text(encoding="utf-8")) or {} + tables: set[str] = set() + for body in (data.get("kinds") or {}).values(): + main = (body or {}).get("main_table") + if main: + tables.add(str(main)) + files = _contracts(manifest) + for path in files: + doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + for q in _sql_of(doc.get("verifier") or {}): + tables |= tables_in_sql(q) + db = ((doc.get("frame") or {}).get("database")) or {} + for key in ("views", "judged_by", "new_row_fields"): + tables |= {str(t) for t in (db.get(key) or {})} + users = users_for_actor_params(Path(manifest), schema) + if users is None: + raise EntityScopeError( + "the acting user's table can't be derived from the manifest's actor " + "parameters, so no scope is proposed: another user's row must stay a stop" + ) + tables.add(str(users.table)) + known = set(getattr(schema, "tables", {}) or {}) + if known: + tables = {t for t in tables if t in known or table_name(t) in known} + payload = { + "schema": SCHEMA, + "manifest": str(Path(manifest).resolve()), + "entity_tables": sorted(tables), + "actor_table": str(users.table), + "contracts": [str(p) for p in files], + } + from openadapt_flow.runtime.effects.admission import digest + + payload["proposal_sha256"] = digest( + {k: payload[k] for k in ("entity_tables", "actor_table")} + ) + return payload + + +def _scoped(doc: Mapping[str, Any], tables: Sequence[str]) -> dict[str, Any]: + frame = doc.get("frame") if isinstance(doc, Mapping) else None + if not isinstance(frame, Mapping) or not frame.get("database"): + raise EntityScopeError("an entity scope needs frame.database") + new = dict(doc) + new["frame"] = { + **frame, + "database": {**frame["database"], "entity_tables": list(tables)}, + } + return new + + +def _rewrite(files: Sequence[Path], tables: Sequence[str]) -> list[tuple[Path, str]]: + from openadapt_flow.verifier import Contract, VerifierError + + out = [] + for path in files: + doc = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {} + new = _scoped(doc, tables) + try: + Contract.from_dict(new, name=Path(path).stem) + except VerifierError as exc: + raise EntityScopeError(f"{path}: {exc}") from exc + out.append( + (Path(path), yaml.safe_dump(new, sort_keys=False, allow_unicode=True)) + ) + return out + + +def stage(proposal: Mapping[str, Any], out: Path) -> Path: + """A copy of the manifest's folder with the scope written in, for the + planted faults to run against. Returns the copied manifest.""" + + manifest = Path(str(proposal["manifest"])) + src = manifest.parent + out = Path(out) + if out.exists(): + raise EntityScopeError(f"{out} exists") + shutil.copytree(src, out) + files = [ + out / Path(p).resolve().relative_to(src.resolve()) + for p in proposal["contracts"] + ] + for path, text in _rewrite(files, proposal["entity_tables"]): + path.write_text(text, encoding="utf-8") + return out / manifest.name + + +def apply(proposal: Mapping[str, Any], faults: Path, by: str) -> Any: + """Write the scope into the setup's contracts, only when the planted + faults run against the staged scope were all caught.""" + + from openadapt_flow.learn import _write_all + from openadapt_flow.runtime.effects.admission import ( + ACTOR_ATTACKS, + SAFETY_BAR, + AdmissionRefused, + admit, + load_results, + ) + + if not by.strip(): + raise EntityScopeError("applying a scope names the person (--by)") + ran_under, results = load_results(Path(faults)) + if ran_under != proposal.get("proposal_sha256"): + raise AdmissionRefused( + "the fault results were not run under this proposal " + f"({ran_under or 'no digest'} != {proposal.get('proposal_sha256')})" + ) + decision = admit("entity_tables", results, required=(*SAFETY_BAR, *ACTOR_ATTACKS)) + if not decision.admitted: + raise AdmissionRefused("; ".join(decision.reasons)) + _write_all( + _rewrite([Path(p) for p in proposal["contracts"]], proposal["entity_tables"]) + ) + return decision + + +# -- CLI ----------------------------------------------------------------------------- + + +def register(steps: argparse._SubParsersAction) -> None: + e = steps.add_parser( + "entities", + help="scope the whole-database frame to the setup's business entities", + allow_abbrev=False, + ) + esub = e.add_subparsers(dest="entities_step", required=True) + p = esub.add_parser( + "propose", help="derive the entity tables from the setup", allow_abbrev=False + ) + p.add_argument("--manifest", required=True) + p.add_argument("--read", default=None, help="read.yaml (the read-only account)") + p.add_argument("--schema", default=None, help="schema.json from `generate schema`") + p.add_argument("--out", default="entity_scope.json") + p.set_defaults(func=cmd_entities) + s = esub.add_parser( + "stage", help="a scoped copy of the setup, for the faults", allow_abbrev=False + ) + s.add_argument("proposal") + s.add_argument("--out", required=True) + s.set_defaults(func=cmd_entities) + a = esub.add_parser( + "apply", + help="write the scope in, if the faults were all caught", + allow_abbrev=False, + ) + a.add_argument("proposal") + a.add_argument( + "--faults", required=True, help="openadapt.relaxation-faults/v1 JSON" + ) + a.add_argument("--by", required=True) + a.set_defaults(func=cmd_entities) + + +def cmd_entities(args: argparse.Namespace) -> int: + from openadapt_flow.runtime.effects.admission import AdmissionRefused + + try: + if args.entities_step == "propose": + from openadapt_flow.learn import _schema + + schema = _schema(args) + proposal = derive(Path(args.manifest), schema) + Path(args.out).write_text(json.dumps(proposal, indent=2), encoding="utf-8") + print( + f"{len(proposal['entity_tables'])} entity table(s) for " + f"{len(proposal['contracts'])} contract(s); written to {args.out}" + ) + return 0 + proposal = json.loads(Path(args.proposal).read_text(encoding="utf-8")) + if proposal.get("schema") != SCHEMA: + raise EntityScopeError(f"{args.proposal} is not a {SCHEMA} proposal") + if args.entities_step == "stage": + print(stage(proposal, Path(args.out))) + return 0 + decision = apply(proposal, Path(args.faults), args.by) + print(f"admitted: {json.dumps(decision.per_class, sort_keys=True)}") + return 0 + except (EntityScopeError, AdmissionRefused, OSError, ValueError) as exc: + print(f"learn entities: {exc}", file=sys.stderr) + return 2 + + +def main(argv: Optional[Sequence[str]] = None) -> int: # pragma: no cover + ap = argparse.ArgumentParser(prog="learn-entities", allow_abbrev=False) + register(ap.add_subparsers(dest="step", required=True)) + args = ap.parse_args(argv) + return int(args.func(args)) diff --git a/packages/flow/openadapt_flow/runtime/effects/admission.py b/packages/flow/openadapt_flow/runtime/effects/admission.py new file mode 100644 index 0000000000..22a8d941cb --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/effects/admission.py @@ -0,0 +1,139 @@ +"""The safety bar: a relaxation is admitted only if planted faults still fail. + +A learned mask (a ``frame.learned`` excuse) or a tier relaxation (a +``frame.database.entity_tables`` scope, under which rows outside the entity +tables are logged instead of stopping a write) makes the verifier accept +more. Each is admitted only with evidence that the planted faults are still +caught under it: the same fault cases, judged by the relaxed contracts. + +The bar (``SAFETY_BAR``): a wrong row, a wrong value, a duplicate, an edit +to a sibling business record, a late revert of the target and a lost update. +A relaxation of the acting user's own table must also still stop another +user's row and another column of the actor's row (``ACTOR_ATTACKS``). + +Admitted means: every required class has at least one case, every case is +caught, and every case caught before the relaxation is caught after it (a +case that flips to passing is named). Anything else is refused, and the +refusal says which class or case. The results are the caller's, from +``openadapt-flow qualify`` or a fault replay; this module only decides. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +SCHEMA = "openadapt.relaxation-faults/v1" + +SAFETY_BAR: tuple[str, ...] = ( + "wrong_row", + "wrong_value", + "duplicate", + "sibling_edit", + "late_revert", + "lost_update", +) +#: Faults aimed at the acting user's table: another user's row moved, and a +#: column of the actor's own row that no excuse names. +ACTOR_ATTACKS: tuple[str, ...] = ("other_user_row", "actor_other_column") + +#: ``fault_gate`` class names that are the same fault as a bar class. +ALIASES: dict[str, str] = { + "wrong_record": "wrong_row", + "unrelated_edit": "sibling_edit", + "other_record": "sibling_edit", + "revert": "late_revert", + "late_write": "late_revert", + "concurrent_save": "lost_update", +} + + +class AdmissionRefused(ValueError): + pass + + +@dataclass(frozen=True) +class FaultResult: + case: str + fault_class: str + caught: bool + + @property + def bar_class(self) -> str: + return ALIASES.get(self.fault_class, self.fault_class) + + +@dataclass +class Admission: + admitted: bool + relaxation: str + reasons: list[str] = field(default_factory=list) + per_class: dict[str, dict[str, int]] = field(default_factory=dict) + + def to_dict(self) -> dict[str, Any]: + return { + "admitted": self.admitted, + "relaxation": self.relaxation, + "reasons": list(self.reasons), + "per_class": self.per_class, + } + + +def admit( + relaxation: str, + after: Sequence[FaultResult], + before: Sequence[FaultResult] = (), + *, + required: Sequence[str] = SAFETY_BAR, +) -> Admission: + """Decide one relaxation from its fault results (see the module doc).""" + + reasons: list[str] = [] + per: dict[str, dict[str, int]] = {} + for r in after: + c = per.setdefault(r.bar_class, {"cases": 0, "caught": 0}) + c["cases"] += 1 + c["caught"] += int(bool(r.caught)) + for cls in required: + if per.get(cls, {}).get("cases", 0) == 0: + reasons.append(f"no planted {cls} case was run under the relaxation") + for r in after: + if not r.caught: + reasons.append( + f"planted {r.bar_class} case {r.case} passed under the relaxation" + ) + now = {r.case: r.caught for r in after} + for r in before: + # A case caught before that passes now is named above. + if r.caught and r.case not in now: + reasons.append( + f"case {r.case}, caught before, was not run under the relaxation" + ) + return Admission(not reasons, relaxation, reasons, per) + + +def load_results(path: Path) -> tuple[str, list[FaultResult]]: + """(proposal digest the faults ran under, results) from a results file: + ``{"schema": SCHEMA, "proposal_sha256": ..., "cases": [{case, class, + caught}]}``.""" + + data = json.loads(Path(path).read_text(encoding="utf-8")) + if not isinstance(data, Mapping) or data.get("schema") != SCHEMA: + raise AdmissionRefused(f"{path} is not a {SCHEMA} results file") + out = [] + for item in data.get("cases") or []: + if not isinstance(item, Mapping): + continue + out.append( + FaultResult(str(item["case"]), str(item["class"]), bool(item["caught"])) + ) + return str(data.get("proposal_sha256") or ""), out + + +def digest(payload: Any) -> str: + canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")) + return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest() diff --git a/packages/flow/openadapt_flow/runtime/effects/db_snapshot.py b/packages/flow/openadapt_flow/runtime/effects/db_snapshot.py index 104951cd07..dcc86c297e 100644 --- a/packages/flow/openadapt_flow/runtime/effects/db_snapshot.py +++ b/packages/flow/openadapt_flow/runtime/effects/db_snapshot.py @@ -68,7 +68,7 @@ class (:class:`SqliteValue`), which the row MAC keeps. :func:`canonical` import re import secrets import struct -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Collection, Mapping, Sequence from contextlib import suppress from dataclasses import dataclass, field, replace from decimal import Context, Decimal, InvalidOperation @@ -2120,11 +2120,20 @@ def diff( return out -def settled_state(a: Snapshot, b: Snapshot) -> bool: +def settled_state( + a: Snapshot, b: Snapshot, entity_scope: Optional[Collection[str]] = None +) -> bool: """Do two reads taken after the save show the same database, apart from rows added to append-only tables (the app's logs, which the frame excuses)? An append-only table's existing rows must not change, and - every other table must be the same, as in :func:`same_state`.""" + every other table must be the same, as in :func:`same_state`. + + ``entity_scope`` (``frame.database.entity_tables``): a table outside it + may keep moving (a scheduler, a queue). Whatever it holds in the read + that is judged is logged, never a stop, so its motion doesn't keep the + database from settling. Its rows are still diffed against the baseline.""" + + from openadapt_flow.app_profiles import table_name if (a.objects, a.code_visible) != (b.objects, b.code_visible): return False @@ -2132,6 +2141,8 @@ def settled_state(a: Snapshot, b: Snapshot) -> bool: return False for name, x in a.tables.items(): y = b.tables[name] + if entity_scope is not None and table_name(name) not in entity_scope: + continue if (x.mode, x.schema, x.row_hash_format) != ( y.mode, y.schema, diff --git a/packages/flow/openadapt_flow/runtime/effects/frame.py b/packages/flow/openadapt_flow/runtime/effects/frame.py index 60d0f9f912..01e56bacfb 100644 --- a/packages/flow/openadapt_flow/runtime/effects/frame.py +++ b/packages/flow/openadapt_flow/runtime/effects/frame.py @@ -381,6 +381,39 @@ class FrameDatabase(BaseModel): #: right wait depends on the app's own jobs, so the contract's author #: picks it. recheck_after_s: Optional[float] = Field(default=None, gt=0) + #: The business-entity tables (``docs/VERDICT_TIERS.md``): the main + #: tables the setup's kinds write, their child tables, the tables a + #: field's location reads through, and the acting user's table. Set: a + #: row added or changed in any *other* table (a scheduler heartbeat, a + #: task queue, a cache the app recomputes, a notification fan-out) is a + #: logged side effect, not a stop. It is listed in the verdict, by table, + #: change and columns, and offered to the learner. A removed row, a row + #: of an entity table, a change to a declared row and anything no row + #: comparison explains still refute. The tables the frame itself names + #: (``views``, ``judged_by``, ``new_row_fields``, side records, learned + #: excuses, owner tables) always count as entity tables. Unset: every + #: table is judged as before. + entity_tables: Optional[list[str]] = None + + def entity_scope(self, spec: Optional["FrameSpec"] = None) -> Optional[set[str]]: + """The entity tables (as :func:`table_name` names them), or None + when ``entity_tables`` is unset (every table judged).""" + + if self.entity_tables is None: + return None + names = set(self.entity_tables) + names |= set(self.views) | set(self.judged_by) | set(self.new_row_fields) + if spec is not None: + names |= {s.surface for s in spec.side_records} + names |= {s.of_surface for s in spec.side_records} + if spec.learned is not None: + names |= {e.table for e in spec.learned.excuses} + if spec.attribution is not None: + names |= set(spec.attribution.owners) + profile = self.loaded_profile() + if profile is not None: + names |= {r.table for r in profile.rules} + return {table_name(n) for n in names if n} @model_serializer(mode="wrap") def _compact(self, handler: Any) -> dict[str, Any]: @@ -396,6 +429,8 @@ def _compact(self, handler: Any) -> dict[str, Any]: data.pop("read_row_budget", None) if not data.get("judged_by"): data.pop("judged_by", None) + if data.get("entity_tables") is None: + data.pop("entity_tables", None) return data @model_validator(mode="after") @@ -735,6 +770,12 @@ class FrameVerdict: #: In memory only: rows whose source, physical key and unambiguous audit #: identity the database snapshot witnessed for a surface. added_row_witnesses: dict[str, list[AddedRowWitness]] = field(default_factory=dict) + #: ``frame.database.entity_tables`` only: rows that moved outside the + #: entity tables. They don't refute; they are logged (names only) and + #: offered to the learner as candidate excuses. + side_effects: list[FrameChange] = field(default_factory=list) + #: The side effects in ``moves`` form, for ``openadapt-flow learn``. + side_effect_moves: Optional[list[dict[str, Any]]] = None @property def held(self) -> bool: @@ -770,6 +811,14 @@ def evidence(self, spec: FrameSpec) -> dict[str, Any]: else {} ), **({"moves": self.moves} if self.moves else {}), + **( + { + "side_effects": side_effect_summary(self.side_effects), + "side_effect_moves": self.side_effect_moves or [], + } + if self.side_effects + else {} + ), **( { "learned": { @@ -785,6 +834,31 @@ def evidence(self, spec: FrameSpec) -> dict[str, Any]: } +#: Column prefixes of a generated contract's own check columns +#: (``generate.verify_contract``): ``pin__x`` and ``empty__x`` are 1 or 0, +#: computed by the read from stored columns (and, for a copied or clock pin, +#: from another row or the clock). They are checks, not stored values: one +#: can flip on an untouched row as the clock moves. With ``frame.database`` +#: the stored columns they are computed from are compared themselves, so an +#: undeclared row's check columns are not compared. +DERIVED_CHECK_PREFIXES: tuple[str, ...] = ("pin__", "empty__") + + +def side_effect_summary(changes: Sequence[FrameChange]) -> list[dict[str, Any]]: + """Logged side effects by table and change: counts and column names, + never keys or values.""" + + groups: dict[tuple[str, str], dict[str, Any]] = {} + for c in changes: + g = groups.setdefault( + (c.surface, c.change), + {"table": c.surface, "change": c.change, "rows": 0, "columns": set()}, + ) + g["rows"] += 1 + g["columns"].update(c.fields) + return [{**g, "columns": sorted(g["columns"])} for _k, g in sorted(groups.items())] + + def _not_checked(reason: str, attribution: str = "none") -> FrameVerdict: return FrameVerdict(status="not_checked", reason=reason, attribution=attribution) @@ -1054,6 +1128,14 @@ def ignore_for(name: str) -> set[str]: return set(cols) | {KEY} return surface_ignore + def derived(name: str, fields: Sequence[str]) -> list[str]: + """``fields`` without the contract's own check columns, on a surface + (not a database table) of a frame that diffs the whole database.""" + + if database is None or name in hashers: + return list(fields) + return [f for f in fields if not str(f).startswith(DERIVED_CHECK_PREFIXES)] + def identity_of(name: str) -> Optional[str]: if identities is not None and name in identities: return identities[name] @@ -1079,7 +1161,7 @@ def changed( ignore = ignore_for(name) hasher = hashers.get(name) if hasher is None: - return _changed_fields(before, after, ignore) + return derived(name, _changed_fields(before, after, ignore)) fields = sorted( k for k in before @@ -2173,6 +2255,23 @@ def names_moved(entry_ref: Any) -> bool: ) ) + side_effects: list[FrameChange] = [] + scope = database.entity_scope(spec) if database is not None else None + if scope is not None: + hard: list[FrameChange] = [] + for c in collateral: + if ( + c.surface in hashers + and (c.surface, str(c.key)) in rows_seen + and c.change in ("added", "changed") + and not (c.on_target or c.other_on_target or c.audit_only) + and table_name(c.surface) not in scope + ): + side_effects.append(c) + else: + hard.append(c) + collateral = hard + verdict = FrameVerdict( status="refuted" if collateral else "held", reason="", @@ -2188,6 +2287,10 @@ def names_moved(entry_ref: Any) -> bool: else None, learned_used=learned_used, unverified_columns=unverified_columns, + side_effects=side_effects, + side_effect_moves=_moves(side_effects, rows_seen, hashers, actor, added_columns) + if side_effects + else None, ) verdict.reason = _reason(verdict) if ( @@ -2313,6 +2416,15 @@ def _reason(verdict: FrameVerdict) -> str: f"nothing outside the declared delta changed across " f"{verdict.records_compared} record(s)" ) + if verdict.side_effects: + tables = sorted({c.surface for c in verdict.side_effects}) + sample_tables = [t for idx, t in enumerate(tables) if idx < _SAMPLE_LIMIT] + parts.append( + f"{len(verdict.side_effects)} row(s) moved outside the entity tables " + f"({', '.join(sample_tables)}" + f"{'' if len(tables) <= _SAMPLE_LIMIT else ', ...'}): logged as side " + "effects, not counted against this save" + ) if verdict.concurrent: parts.append( f"{len(verdict.concurrent)} change(s) attributed to another actor " diff --git a/packages/flow/openadapt_flow/verifier.py b/packages/flow/openadapt_flow/verifier.py index 2cc821c404..cef663e970 100644 --- a/packages/flow/openadapt_flow/verifier.py +++ b/packages/flow/openadapt_flow/verifier.py @@ -677,11 +677,47 @@ class WriteResult: #: (``docs/WRITE_RECEIPTS.md``). Issuing never changes the outcome. write_receipt: str = "off" write_receipt_path: Optional[str] = None + #: ``shadow`` or ``gating`` (``docs/VERDICT_TIERS.md``): whether a caller + #: that stops on a verdict should stop on this one. A contract observes + #: (``shadow``) until it has a run of clean checks and a person turns + #: gating on (``openadapt-flow gate``). The outcome is computed and + #: recorded the same either way. + enforcement: str = "gating" @property def verified(self) -> bool: return self.outcome is Outcome.CONFIRMED + @property + def side_effects(self) -> list[dict[str, Any]]: + """Rows that moved outside the contract's entity tables, by table, + change and columns (``frame.database.entity_tables``): logged, never + a stop. Empty when the frame lists none.""" + + frame = self.evidence.get("frame") if isinstance(self.evidence, dict) else None + if not isinstance(frame, Mapping): + return [] + return [dict(x) for x in frame.get("side_effects") or []] + + @property + def tier(self) -> str: + """``hard`` (REFUTED: blocks), ``doubt`` (UNCERTAIN after the + verifier's own retries), ``logged`` (CONFIRMED with side effects) or + ``clean`` (CONFIRMED, nothing else moved).""" + + if self.outcome is Outcome.REFUTED: + return "hard" + if self.outcome is Outcome.UNCERTAIN: + return "doubt" + return "logged" if self.side_effects else "clean" + + @property + def blocks(self) -> bool: + """Should a caller that stops on a verdict stop here? Only a result + that isn't CONFIRMED, under a contract whose gating is on.""" + + return not self.verified and self.enforcement == "gating" + @property def provisional(self) -> bool: """CONFIRMED, but a recheck is due (``recheck_due_at``): a write that @@ -751,6 +787,10 @@ def to_dict(self) -> dict[str, Any]: "final": self.final, "write_receipt": self.write_receipt, "write_receipt_path": self.write_receipt_path, + "tier": self.tier, + "side_effects": self.side_effects, + "enforcement": self.enforcement, + "blocks": self.blocks, } @@ -1795,6 +1835,11 @@ def verify_write( "the write attempt or its verification purpose changed", key=pending.write_key, ) + if write_attempted: + # RETRY tier: a write that isn't visible yet is waited for, with + # backoff, before it is judged, so a slow commit isn't reported + # as a doubt. The judge runs in full afterwards either way. + await_effects(pending.contract, pending.params) result = _judge( pending, write_attempted=write_attempted, @@ -1829,15 +1874,121 @@ def verify_write( ) finally: pending.release() - if pending.ledger is not None: - import dataclasses + import dataclasses + + from openadapt_flow import enforcement as _enforcement + result = dataclasses.replace( + result, enforcement=_enforcement.observe(pending.contract.digest, result) + ) + if pending.ledger is not None: result = dataclasses.replace(result, ledger=pending.ledger) if write_receipt: result = issue_write_receipt(result) return result +#: RETRY tier defaults (``docs/VERDICT_TIERS.md``): the first wait, the +#: factor it grows by, and the total budget. ``OPENADAPT_VERIFY_RETRY_S`` +#: sets the budget (0 turns the wait off). +RETRY_FIRST_S = 0.5 +RETRY_FACTOR = 2.0 +RETRY_BUDGET_S = 8.0 +#: Verifier kinds a wait may read: database reads only. A read through an +#: app's API can itself move bookkeeping rows the frame then judges. +_RETRY_READS = frozenset({"surfaces", "sql", "sqlite"}) + + +def _retry_budget() -> float: + raw = os.environ.get("OPENADAPT_VERIFY_RETRY_S") + if raw is None or not raw.strip(): + return RETRY_BUDGET_S + try: + return max(0.0, float(raw)) + except ValueError: + return RETRY_BUDGET_S + + +def _kinds(value: Any) -> set[str]: + found: set[str] = set() + if isinstance(value, Mapping): + kind = value.get("kind") + if isinstance(kind, str): + found.add(kind) + for item in value.values(): + found |= _kinds(item) + elif isinstance(value, (list, tuple)): + for item in value: + found |= _kinds(item) + return found + + +def await_effects( + contract: Contract, + params: Mapping[str, Any], + *, + budget_s: Optional[float] = None, + sleep: Any = None, +) -> int: + """Wait, with backoff, until every effect that expects records reads at + least one, or the budget runs out. Returns how many reads were taken. + + Only a wait: it never decides a verdict, and the judge that follows reads + the store again in full. It reads only through database verifiers, so it + can't move what the frame judges. Any failure ends the wait.""" + + import time as _time + + from openadapt_flow.runtime.effects.effect import record_matches + from openadapt_flow.runtime.effects.surfaces import surface_of + from openadapt_flow.verify_run import _build_verifier + + budget = _retry_budget() if budget_s is None else budget_s + if budget <= 0: + return 0 + cfg = contract.config + try: + if not _kinds(cfg.verifier.model_dump(mode="json")) <= _RETRY_READS: + return 0 + wanted = [e for e in cfg.effects if getattr(e, "expected_count", 0)] + if not wanted: + return 0 + verifier = _build_verifier(cfg, params) + except (OSError, RuntimeError, ValueError, TypeError, KeyError, AttributeError): + return 0 + pause = sleep or _time.sleep + waited, delay, reads = 0.0, RETRY_FIRST_S, 0 + while True: + try: + state = verifier.capture_pre_state() + reads += 1 + visible = True + for effect in wanted: + bound = effect.resolve(params) + name = surface_of(effect) + detail = state.detail or {} + if name is None and "record" not in detail: + # One read, no surfaces: the state is that read. + sub = {"reachable": state.reachable, "records": state.records} + else: + sub = detail.get(name or "record", {}) + if not sub.get("reachable"): + return reads + selector = dict(bound.match) + if not any( + record_matches(dict(r), selector) for r in sub.get("records", []) + ): + visible = False + break + except (OSError, RuntimeError, ValueError, TypeError, KeyError, AttributeError): + return reads + if visible or waited + delay > budget: + return reads + pause(delay) + waited += delay + delay *= RETRY_FACTOR + + def issue_write_receipt( result: WriteResult, out: Optional[Path] = None, **kwargs: Any ) -> WriteResult: diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index e5e646b48e..23af27d0ca 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -1209,7 +1209,7 @@ def _database_frame( if again is None: unreachable.too_large = any(e.startswith(limit_error) for e in errors) return unreachable - if settled_state(new, again): + if settled_state(new, again, database.entity_scope(cfg.frame)): settled = True break if used < attempts: diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index 472eb517c2..a83bb3e291 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -1,7 +1,7 @@ { "columns": 100, "help": { - "openadapt-flow": "usage: openadapt-flow [-h] [--version] {command} ...\n\nRecord a task and compile it into a program that runs on this computer. With a record check\nconfigured, a governed run confirms each save by reading the record back, and a run that can't\nconfirm a save stops and asks a person. When the screen changes, it finds the same field again or\nstops, and a lasting fix needs a person's approval.\n\noptions:\n -h, --help show this help message and exit\n --version Show the version and exit\n\ncommands:\n {command}\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n\nNew here? Run 'openadapt-flow demo' to see a checked run and a stopped run side by side on one\npage.\n\nLegacy commands (original spellings):\n admit\n api\n approve\n approve-sanitized\n approver-grant\n at-rest\n attach-seal\n bench\n benchmark\n bind-record-checks\n browser-accessibility\n business-decisions\n certify\n check\n cleanup\n compile\n compile-agent\n compose\n confirm-surfaces\n connect\n connector\n console\n countersign\n deferred\n demo\n demo-record\n disambiguate\n emit-mcp\n emit-skill\n encrypt\n exceptions\n explain\n fleet\n flight\n for-each\n guard\n handoff\n hooks\n induce\n intake\n item-approval\n jit\n known-ids\n learn\n ledger\n lint\n local-seal\n login\n materialize-approved\n narration\n no-outbound\n plan\n process\n propose-qualification\n proxy\n pull\n push\n qualify\n readiness\n receipt\n reconcile\n record\n redact-report\n repair\n replay\n report-break\n report-run\n resume\n review-sanitized\n rollback\n route\n run\n sanitize\n scaffold-verifier\n sections\n serve-execute\n serve-reward\n service\n shadow\n silent-saves\n skill\n teach\n teach-authorization\n teach-branch\n triage\n tutorial\n undo\n validate-hosted\n variants\n verify-run\n visualize\n wrap-dispatch\n", + "openadapt-flow": "usage: openadapt-flow [-h] [--version] {command} ...\n\nRecord a task and compile it into a program that runs on this computer. With a record check\nconfigured, a governed run confirms each save by reading the record back, and a run that can't\nconfirm a save stops and asks a person. When the screen changes, it finds the same field again or\nstops, and a lasting fix needs a person's approval.\n\noptions:\n -h, --help show this help message and exit\n --version Show the version and exit\n\ncommands:\n {command}\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n\nNew here? Run 'openadapt-flow demo' to see a checked run and a stopped run side by side on one\npage.\n\nLegacy commands (original spellings):\n admit\n api\n approve\n approve-sanitized\n approver-grant\n at-rest\n attach-seal\n bench\n benchmark\n bind-record-checks\n browser-accessibility\n business-decisions\n certify\n check\n cleanup\n compile\n compile-agent\n compose\n confirm-surfaces\n connect\n connector\n console\n countersign\n deferred\n demo\n demo-record\n disambiguate\n emit-mcp\n emit-skill\n encrypt\n exceptions\n explain\n fleet\n flight\n for-each\n gate\n guard\n handoff\n hooks\n induce\n intake\n item-approval\n jit\n known-ids\n learn\n ledger\n lint\n local-seal\n login\n materialize-approved\n narration\n no-outbound\n plan\n process\n propose-qualification\n proxy\n pull\n push\n qualify\n readiness\n receipt\n reconcile\n record\n redact-report\n repair\n replay\n report-break\n report-run\n resume\n review-sanitized\n rollback\n route\n run\n sanitize\n scaffold-verifier\n sections\n serve-execute\n serve-reward\n service\n shadow\n silent-saves\n skill\n teach\n teach-authorization\n teach-branch\n triage\n tutorial\n undo\n validate-hosted\n variants\n verify-run\n visualize\n wrap-dispatch\n", "openadapt-flow admit": "usage: openadapt-flow admit [-h] {run,decide,status} ...\n\npositional arguments:\n {run,decide,status}\n run Compile, induce, propose checks, and stop once for a person's decision (the\n default form: `admit `)\n decide Show a stopped admission's summary and decide it (a person, at a terminal)\n status Print admitted vs not-admitted for Flow from the public ledger. Never mints\n a signature.\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow run --task-admit\n", "openadapt-flow admit decide": "usage: openadapt-flow admit decide [-h] [--by BY] admission\n\npositional arguments:\n admission Admission directory from `admit`\n\noptions:\n -h, --help show this help message and exit\n --by BY Your name for the record\n\nAlso available as: openadapt-flow run --task-admit decide\n", "openadapt-flow admit run": "usage: openadapt-flow admit run [-h] [--candidate ID] [--candidates-root CANDIDATES_ROOT] --out\n OUT --name NAME [--policy-pack {community,cloud,regulated}]\n [--by BY]\n [recordings ...]\n\npositional arguments:\n recordings Recording directories (or compiled bundles) of the same task\n\noptions:\n -h, --help show this help message and exit\n --candidate ID A shadow candidate id under --candidates-root, or its folder. Its\n recordings/ folder is used when no recordings are given\n --candidates-root CANDIDATES_ROOT\n Where shadow candidates are kept (default: ./shadow-candidates)\n --out OUT New admission directory\n --name NAME Workflow name\n --policy-pack {community,cloud,regulated}\n --by BY Your name for the record (default: your login name)\n\nAlso available as: openadapt-flow run --task-admit run\n", @@ -85,6 +85,11 @@ "openadapt-flow fleet status": "usage: openadapt-flow fleet status [-h] [--json]\n\noptions:\n -h, --help show this help message and exit\n --json\n\nAlso available as: openadapt-flow services fleet status\n", "openadapt-flow flight": "usage: openadapt-flow flight [-h] [--task-id TASK_ID] [--out OUT] [--label LABEL]\n [--gate {terminal,file,refuse}] [--approval-timeout APPROVAL_TIMEOUT]\n [--cdp CDP] [--guard-config GUARD_CONFIG] [--guard-task GUARD_TASK]\n [--max-cost-usd MAX_COST_USD] [--no-scrub] [--i-accept-unscrubbed]\n [--safe-label LABEL] [--allow-unenforced-egress] [--no-egress-block]\n [--json]\n ...\n\n``openadapt-flow flight``: record any agent's run, gate its commits.\n\n openadapt-flow flight [--task-id ID] [--cdp URL] [--max-cost-usd N] -- CMD ...\n\nStarts a loopback proxy in front of the model API and runs CMD with\nANTHROPIC_BASE_URL and OPENAI_BASE_URL pointing at it, so every model call\nis metered and priced, and the request's text and its screenshots in PNG,\nJPEG, GIF, BMP, TIFF or WEBP are scrubbed of personal data on this machine\nbefore it is sent (other image formats, and data an agent re-encodes on\npurpose, are not covered; see \"What the scrubber does not cover\" in\nFLIGHT_RECORDER.md). The provider the agent\nalready targets (its own *_BASE_URL, else the provider's API) is the only\nplace anything is sent; the agent's key passes through untouched and is\nnever logged.\n\nCMD also gets OPENADAPT_FLIGHT_GATE_URL: an executor wrapped with\nGatedComputer or GatedComputerCall (one line, see FLIGHT_RECORDER.md) logs\nits actions here and holds each click that is not known to be safe (only\nfocus/view roles and a short list such as Cancel, Close, Back, Search, Open\npass; --safe-label adds to it) for a person: --gate terminal asks y/N on\nthis terminal, --gate file writes an item-approval request Desktop or a\npaired phone answers, --gate refuse holds every one.\n\nCMD runs under an OS egress block (openadapt_flow.flight.egress): on macOS,\nsandbox-exec denies every outbound connection except to loopback, so a\ndirect connection from CMD or anything it starts (a browser included)\nfails; work handed to a process outside that tree is not covered. Where the block isn't available\n(any other system) the run refuses to start unless --allow-unenforced-egress\nis given; --no-egress-block turns it off on macOS too. Either is recorded in\nflight.json and egress.json.\n\nThe run is marked refused (exit 3, flight.json details.egress.refused) when\nmodel calls went around the proxy: CMD's usage.json (OPENADAPT_USAGE_PATH,\nopenadapt.agent-usage/v1) reports more calls than the proxy saw, or a direct\nconnection through the proxy variables was trapped.\n\nWith --cdp (or when CMD starts Chromium with --remote-debugging-port), the\nexisting `openadapt-flow guard` also attaches to the browser, given\n--guard-config and --guard-task.\n\nWrites flight.json (openadapt.flight-run/v1), egress.json, timeline.jsonl,\nscrubbed frame thumbnails and timeline.html in the run directory, and prints\nits path. Exit status: CMD's own; 3 when the run is refused for egress\noutside the proxy; 2 when the run could not start (no scrubber, no egress\nblock, a bad option, CMD not found).\n\npositional arguments:\n command -- CMD ...\n\noptions:\n -h, --help show this help message and exit\n --task-id TASK_ID the task this run does (default: generated)\n --out OUT the run directory (default: flight-runs/