From 9a0e1a54343bee8fa92e08d842969b90a0204ede Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 20:47:13 -0500 Subject: [PATCH 1/4] fix(flow): two rechecks that held correct writes UNCERTAIN A write begun with ledger=None was rechecked against the default ledger, found no attempt there, and was held UNCERTAIN. A recheck that slept until its due time could wake a few milliseconds before the wall clock reached it, read the time as not yet due, and hold the write UNCERTAIN. --- packages/flow/openadapt_flow/verifier.py | 14 +++++- packages/flow/tests/test_verifier_recheck.py | 47 ++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/verifier.py b/packages/flow/openadapt_flow/verifier.py index e3751d4c41..6ef16f82da 100644 --- a/packages/flow/openadapt_flow/verifier.py +++ b/packages/flow/openadapt_flow/verifier.py @@ -2890,7 +2890,11 @@ def _recheck_attempt( if isinstance(write, WriteResult): write_id, key = write.write_id, write.write_key - if ledger is _NO_LEDGER and write.ledger is not None: + if ledger is _NO_LEDGER: + # The ledger the write was begun under. A write begun with no + # ledger (``begin_write(ledger=None)``) has no attempt to bind, + # so its recheck uses none either: resolving the default ledger + # here would find no attempt and hold a correct write UNCERTAIN. ledger = write.ledger else: receipt = write.payload.get("receipt") or {} @@ -3479,7 +3483,13 @@ def _judge_recheck( if wait_s > 0: if not wait: raise RecheckNotDue(state.due_at, wait_s) - time.sleep(wait_s) + # Sleep until the wall clock, not only the sleep timer, has reached + # the due time: the read time is the wall clock truncated to the + # second, and a wake a few milliseconds early would make a correct + # recheck read "not yet due" (held UNCERTAIN). + while wait_s > 0: + time.sleep(wait_s + 0.05) + wait_s = seconds_until(state.due_at) excused: list[tuple[Mapping[str, Any], Mapping[str, object]]] = [] for i, other in enumerate(excused_by): later = other.recheck if isinstance(other, WriteResult) else other diff --git a/packages/flow/tests/test_verifier_recheck.py b/packages/flow/tests/test_verifier_recheck.py index 6f52ee5289..2c5767cd27 100644 --- a/packages/flow/tests/test_verifier_recheck.py +++ b/packages/flow/tests/test_verifier_recheck.py @@ -1595,3 +1595,50 @@ def test_positive_recheck_after_confirmed_still_records_rechecked() -> None: assert after is not None assert after.rechecked is not None and after.recheck_owed is None assert after.resolved["outcome"] == "CONFIRMED" # type: ignore[index] + + +def test_a_write_begun_without_a_ledger_rechecks_without_one( + tmp_path: Path, due_now: None +) -> None: + # begin_write(ledger=None): the default recheck call must not look the + # attempt up in the default ledger (where it never was) and hold a + # correct write UNCERTAIN; it reads again and judges. + db = _db(tmp_path) + contract = Contract.from_dict(_doc(db)) + before = begin_write(contract, _params(2), actor=BOT, ledger=None) + _sql(db, *_save_sql(2)) + result = verify_write(before) + assert result.verified, result.reasons + late = _recheck(contract, result) + assert late.outcome == "CONFIRMED", late.reasons + # Late collateral still stops the write without a ledger (held, never + # confirmed). + before = begin_write(contract, _params(3), actor=BOT, ledger=None) + _sql(db, *_save_sql(3)) + result = verify_write(before) + assert result.verified, result.reasons + _sql(db, "UPDATE patient_data SET email = 'x@example.test' WHERE pid = 1") + late = _recheck(contract, result) + assert late.outcome != "CONFIRMED" and not late.verified + + +def test_a_sleep_that_wakes_early_still_reads_when_due( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The sleep timer and the wall clock can disagree by milliseconds; a + # wake just before the due second must not make a correct recheck read + # "not yet due" (UNCERTAIN). + import openadapt_flow.verifier as v + + contract, _, result = _first(tmp_path, recheck_after_s=1) + real = v.time.sleep + calls: list[float] = [] + + def early(seconds: float) -> None: + calls.append(seconds) + real(max(0.0, seconds - 0.3) if len(calls) == 1 else seconds) + + monkeypatch.setattr(v.time, "sleep", early) + late = _recheck(contract, result, wait=True) + assert late.outcome == "CONFIRMED", late.reasons + assert late.read_at >= late.due_at From e6f94397e30ccafdc62d8eb146978749a4dcd6f0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 20:48:21 -0500 Subject: [PATCH 2/4] feat(flow): learn per-request bookkeeping from read-only requests openadapt-flow learn probe reads the whole-database frame, sends only GET and HEAD requests as the agent, and reads again. A changed row of the acting user that moved (a last-login or token-use time) becomes a frame.learned excuse with source read_only_probe, with no approval. Added rows, rows of other users and rows no user owns are not admitted. --- CAPABILITIES.md | 4 +- packages/flow/docs/LEARNED_EXCUSES.md | 47 ++ .../learn.md | 2 +- packages/flow/openadapt_flow/learn.py | 17 + packages/flow/openadapt_flow/learn_probe.py | 406 ++++++++++++++++++ .../openadapt_flow/runtime/effects/frame.py | 1 + .../openadapt_flow/runtime/effects/learned.py | 8 +- packages/flow/tests/test_learn_probe.py | 349 +++++++++++++++ 8 files changed, 830 insertions(+), 4 deletions(-) create mode 100644 packages/flow/openadapt_flow/learn_probe.py create mode 100644 packages/flow/tests/test_learn_probe.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7f7a85d526..ac77f23fe3 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -318,7 +318,7 @@ improvising or retrying when something is off. | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | | See what your own agent gets wrong, with no risk: `openadapt shadow` is a loopback pass-through proxy beside the agent. It checks each write against the system of record (FHIR through `ensure_record`; SQL through the verifier's whole-database frame), checks each `CONFIRMED` again later, and writes `report.html` and `report.json`. It never blocks, changes or resends a write; the only delay is the read before a write (at most `hold_ms`) | [#1678](https://github.com/OpenAdaptAI/OpenAdapt/pull/1678) | Real app (Medplum 5.2.8, 37 cases through a fault proxy: scripted agent 18 of 18 harms caught, 0 correct writes refuted; Claude Sonnet 5.5 9 of 9 caught, 4 correct but corrected writes refuted; 0 writes by the shadow; 15 to 25 ms median added per write; setup 76.5 s machine time, 3 decisions); real app, SQL mode (Dolibarr 21 on MariaDB 11.4, 13 cases: 8 of 8 harms caught, 5 of 5 correct writes confirmed, 292 ms median added); synthetic (SQLite) | `openadapt shadow`, [SHADOW_MODE.md](packages/flow/docs/SHADOW_MODE.md), [SHADOW_RESULTS.md](packages/flow/benchmark/fhir_medplum/public/SHADOW_RESULTS.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](packages/flow/benchmark/skill_cache/README.md) | -| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (draft), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (draft), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | @@ -481,7 +481,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. -- `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +- `learn`: 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. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index cb46acad14..036f76c48a 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -184,8 +184,55 @@ KIND=PATH`. Each needs `frame.database`. Approving again replaces the earlier `frame.learned` with the new one. +## Learning from read-only requests (`learn probe`) + +`collect` learns only from writes the shadow can check. When an app's +requests name their target in the URL, no write is checkable and nothing is +learned. `learn probe` learns the same moves without a write: + +```bash +export AGENT_HEADERS='{"Authorization": "Bearer ..."}' # the agent's own credential +openadapt-flow learn probe --manifest generated/manifest.yaml \ + --kind add_note --values example.yaml --extra '{agent_user_id: "2"}' \ + --actor 2 --base-url http://app.example.test --headers-env AGENT_HEADERS \ + --get /api/notes --out learn/ --apply +``` + +For each of three rounds it reads the whole-database frame of one +contract, sends only the `GET` and `HEAD` requests you list as the agent, +and reads again. No write is sent, so whatever the app moved is its own +bookkeeping. The proposal follows the rules above: only the acting user's +own rows, the exact columns, and never a column the probe's query strings, +the parameters or a contract name. A `changed` move seen in any one round +counts, because no round carried a task. An `added` row (a first-login row) +is never admitted by the probe: its excuse names columns, not values, so it +would also cover a row the agent adds for itself with other values. It is +listed under `needs_approval` for `learn approve`. Every other row that +moved stays a stop and is listed in `learn/probe_proposal.json`. + +The users table comes from the manifest: the table that the columns bound +to an actor parameter (`actor_params`) reference by foreign key. When there +is no such column, or they reference more than one table, nothing is +learned unless you name it (`--users`). + +`--apply` writes the excuses into every contract the manifest lists, with +`frame.learned.source: read_only_probe`, and leaves out of each contract +any excuse for a column that contract names. No person approves them: the +rows were read, the relation is derived from the schema, and the requests +are checked to be read-only. A contract that already has `frame.learned` +is refused, so a person reconciles the two. Receipts name the source. + ## Limits +- A probe sees only what its requests make the app write. A column the app + writes only on some requests (an export, a report) stays a stop until a + probe request or an approved proposal covers it. +- With no approval, the actor-column limit below applies without a person + reading it: a probe excuse on a table whose only user column means + "created by" covers those columns on every row the agent created. The + excused columns are only those a read moved (times, counters), and any + other column of such a row still stops. + - A learned excuse is only as narrow as its actor columns. If a table's only user column means "created by" rather than "belongs to", an excuse on it covers every row the agent created, other users' rows included. 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 59e93fcf8e..f7880c8387 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, propose excuses, and approve them into the contracts. +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. diff --git a/packages/flow/openadapt_flow/learn.py b/packages/flow/openadapt_flow/learn.py index ca15def4e7..0fee10dbac 100644 --- a/packages/flow/openadapt_flow/learn.py +++ b/packages/flow/openadapt_flow/learn.py @@ -333,6 +333,12 @@ def _why_ignored(ep: Mapping[str, Any]) -> Optional[str]: if ep.get("mode") not in ("sql", ""): return "not a SQL check" + if ep.get("probe"): + # A read-only window (learn_probe): no write, so no declared effect + # to hold; only the frame's moved rows count. + if ep.get("frame") != "refuted": + return "nothing moved in the read-only window" + return _why_rows_ignored(ep) outcome = ep.get("outcome") if outcome == "CONFIRMED": return "confirmed: nothing moved that needs an excuse" @@ -342,6 +348,13 @@ def _why_ignored(ep: Mapping[str, Any]) -> Optional[str]: return "the frame wasn't refuted (not checked)" if outcome != "REFUTED": return f"outcome {outcome}" + return _why_rows_ignored(ep) + + +def _why_rows_ignored(ep: Mapping[str, Any]) -> Optional[str]: + """Why an episode's moves teach nothing, or None when every move is a + row that can be named.""" + moves = ep.get("moves") if not isinstance(moves, list) or not moves: return "no moved rows recorded" @@ -934,6 +947,10 @@ def build_parser(p: argparse.ArgumentParser) -> argparse.ArgumentParser: "--reject", action="append", default=[], metavar="ID", help="leave out E" ) a.set_defaults(func=cmd_approve) + + from openadapt_flow import learn_probe + + learn_probe.add_parser(steps) return p diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py new file mode 100644 index 0000000000..57e5d7842a --- /dev/null +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -0,0 +1,406 @@ +"""Learn the app's per-request bookkeeping from read-only requests. + +Some apps write on every request: the acting user's ``last_login``, an API +token's last-used time, a property row added at the user's first sign-in. +The whole-database frame sees those rows move and refutes every write, +correct or not. :mod:`openadapt_flow.learn` learns them from checked writes +and a person approves. That needs writes the shadow can check, and on apps +whose requests name their target in the URL it learns nothing. + +This module learns the same moves without a write. A read-only request +(``GET`` or ``HEAD``) carries no task, so a row it makes the app move is +the app's own bookkeeping, not something an agent asked for: + +1. For each probe round, read the contract's whole-database frame + (``begin_write`` with the probe's parameters), send the read-only + requests as the agent, and judge the frame (``verify_write``). No write + is sent, so the declared effect is absent; only the frame's moved rows + are used. +2. Propose from those moves with the learner's own rules + (:func:`openadapt_flow.learn.propose`): only the acting user's own row + (``actor_row``), exact columns, ``changed`` only, and never a column a + probe request, a parameter or the contract names. An ``added`` row is + held for a person's approval (its excuse would name columns, not + values). Any other row that moved, another user's or one no user owns, + stays a stop and is listed. +3. Write the excuses into each contract's ``frame.learned`` with + ``source: read_only_probe``. At check time the frame derives the + relation again from the run's actor, so an excuse never reaches another + user's row or another column. + +No person approves this, because nothing in it is a judgment: which rows +moved is read, the relation to the acting user is derived from the +schema's foreign keys, and the method of every request is checked. Where +the users table can't be derived (``users_for_actor_params``), nothing is +learned. Nothing here reads or stores a record value. +""" + +from __future__ import annotations + +import json +import tempfile +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow import learn as _learn + +#: Request methods a probe may send: they carry no task. +READ_ONLY_METHODS = frozenset({"GET", "HEAD"}) +#: The ``frame.learned.approved_by`` of a probe's excuses. +PROBE_APPROVER = "read-only probe (openadapt-flow learn probe)" +DEFAULT_ROUNDS = 3 + + +class ProbeError(_learn.LearnError): + """The probe can't run or its result can't be written.""" + + +def check_read_only(requests: Sequence[tuple[str, str]]) -> None: + """Refuse any request that isn't ``GET`` or ``HEAD``.""" + + if not requests: + raise ProbeError("a probe needs at least one read-only request") + for method, _path in requests: + if str(method).upper() not in READ_ONLY_METHODS: + raise ProbeError( + f"a probe sends read-only requests only (GET, HEAD), not {method!r}" + ) + + +def episode( + kind: str, + result: Any, + *, + contract: Any, + params: Mapping[str, Any], + sent_fields: set[str], +) -> dict[str, Any]: + """One probe round as a learner episode (names only).""" + + evidence = getattr(result, "evidence", None) or {} + frame = evidence.get("frame") if isinstance(evidence, Mapping) else None + checked = getattr(result, "checked", None) or {} + out: dict[str, Any] = { + "schema_version": _learn.EPISODE_SCHEMA, + "probe": True, + "kind": kind, + "mode": "sql", + "contract": str(getattr(contract, "name", "") or ""), + "frame": str(checked.get("frame") or ""), + "sent_fields": sorted(sent_fields), + "param_names": sorted(str(p) for p in params), + "contract_fields": _learn.contract_fields(contract), + "has_database": isinstance(frame, Mapping) + and isinstance(frame.get("database"), Mapping), + } + moves = frame.get("moves") if isinstance(frame, Mapping) else None + out["moves"] = [dict(m) for m in moves or [] if isinstance(m, Mapping)] + return out + + +def probe( + contract: Any, + params: Mapping[str, Any], + *, + kind: str, + actor: str, + send: Callable[[], set[str]], + rounds: int = DEFAULT_ROUNDS, + workdir: Optional[Path] = None, +) -> list[dict[str, Any]]: + """Run ``rounds`` read-only windows under ``contract``'s frame. + + ``send`` sends the read-only requests as the agent and returns the + query-parameter names it sent (``learn.query_fields``); it must not + write. Returns one episode per round.""" + + from openadapt_flow.verifier import Actor, begin_write, verify_write + + if rounds < 1: + raise ProbeError("a probe runs at least one round") + config = getattr(contract, "config", None) + frame = getattr(config, "frame", None) + if frame is None or getattr(frame, "database", None) is None: + raise ProbeError("a probe reads the whole-database frame: frame.database") + out = [] + with tempfile.TemporaryDirectory(prefix="oa-probe-") as tmp: + base = Path(workdir) if workdir is not None else Path(tmp) + for i in range(rounds): + pending = begin_write( + contract, + dict(params), + actor=Actor("agent", str(actor)), + ledger=None, + write_key=f"read-only-probe-{kind}-{i}", + workdir=base / f"round-{i}", + ) + sent = set(send()) + result = verify_write(pending) + out.append( + episode( + kind, result, contract=contract, params=params, sent_fields=sent + ) + ) + return out + + +def users_for_actor_params(manifest_path: Path, schema: Any) -> Optional[_learn.Users]: + """The users table, derived from a generator manifest: the one table and + key that every column bound to an actor parameter (``actor_params``) + references by foreign key. None when there is no such column, or the + columns reference more than one table (then nothing is learned).""" + + import yaml + + data = yaml.safe_load(Path(manifest_path).read_text(encoding="utf-8")) or {} + actor_params = {str(p) for p in data.get("actor_params") or []} + if not actor_params or schema is None: + return None + base = Path(manifest_path).resolve().parent + targets: set[tuple[str, str]] = set() + for body in (data.get("kinds") or {}).values(): + main = (body or {}).get("main_table") + table = schema.tables.get(main) if main else None + if table is None: + continue + for variant in (body or {}).get("variants") or []: + for value in (variant or {}).values(): + if not (isinstance(value, str) and value.endswith((".yaml", ".yml"))): + continue + try: + doc = yaml.safe_load((base / value).read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError): + continue + for effect in (doc or {}).get("effects") or []: + for column, bound in ((effect or {}).get("match") or {}).items(): + if not ( + isinstance(bound, Mapping) + and str(bound.get("param")) in actor_params + ): + continue + for fk in table.foreign_keys: + if fk.column == column: + targets.add((fk.table, fk.ref_column)) + if len(targets) != 1: + return None + users_table, key = next(iter(targets)) + return _learn.users_from(users_table, key, schema) + + +def propose( + episodes: Sequence[Mapping[str, Any]], users: Optional[_learn.Users] +) -> dict[str, Any]: + """The learner's proposal from probe episodes: a ``changed`` move seen + in any one read-only round is enough, since no round carried a task. + The relation to the acting user, not the count, decides. + + An ``added`` row is never admitted this way. Its excuse names columns, + not values, so it would also cover a row the agent itself adds for its + own user with any values (a first-login row the probe saw once, then a + different property the agent sets). Such moves go under + ``needs_approval``: a person approves them with ``learn approve``.""" + + eps = [dict(e, kind="read_only_probe") for e in episodes if e.get("probe")] + learnable = [e for e in eps if _learn._why_ignored(e) is None] + n = max(1, len(learnable)) + proposal = _learn.propose(eps, users=users, k=1, n=n, source="read-only probe") + for body in (proposal.get("kinds") or {}).values(): + kept, held = [], [] + for e in body.get("excuses") or []: + (held if e.get("change") == "added" else kept).append(e) + for e in held: + e.pop("id", None) + e["why_not"] = ( + "an added row: its excuse names columns, not values, so a " + "person approves it (learn approve)" + ) + body["excuses"] = kept + body["needs_approval"] = held + proposal.pop("proposal_sha256", None) + proposal["proposal_sha256"] = _learn.proposal_digest(proposal) + return proposal + + +def apply( + proposal: Mapping[str, Any], + contracts: Sequence[Path], +) -> list[tuple[Path, int]]: + """Write the probe's excuses into each contract's ``frame.learned``, all + or none. A contract gets only the excuses whose columns it doesn't name + itself; one with a ``frame.learned`` already is refused (a person + reconciles two sets of excuses).""" + + import yaml + + from openadapt_flow.verifier import Contract, VerifierError + + block = _learn.learned_block(proposal, "read_only_probe", PROBE_APPROVER) + if block is None: + return [] + plan: list[tuple[Path, dict[str, Any], int]] = [] + for path in contracts: + try: + data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError) as exc: + raise ProbeError(f"can't read {path}: {exc}") from exc + frame = data.get("frame") if isinstance(data, dict) else None + if not isinstance(frame, dict) or not frame.get("database"): + continue # no whole-database frame: nothing to excuse + if frame.get("learned"): + raise ProbeError( + f"{path}: frame.learned is already set; reconcile it by hand" + ) + try: + names: set[str] = set() + loaded = Contract.from_dict(data, name=Path(path).stem) + for n in _learn.contract_fields(loaded): + names |= _learn._names(n) + except VerifierError as exc: + raise ProbeError(f"{path}: {exc}") from exc + excuses = [ + e + for e in block["excuses"] + if not any(_learn._names(c) & names for c in e["columns"]) + ] + if not excuses: + continue + new = dict(data) + new["frame"] = { + **frame, + "learned": {**block, "excuses": excuses, "source": "read_only_probe"}, + } + try: + Contract.from_dict(new, name=Path(path).stem) + except VerifierError as exc: + raise ProbeError(f"{path}: {exc}") from exc + plan.append((Path(path), new, len(excuses))) + _learn._write_all( + [ + (path, yaml.safe_dump(new, sort_keys=False, allow_unicode=True)) + for path, new, _n in plan + ] + ) + return [(path, n) for path, _new, n in plan] + + +def http_sender( + base_url: str, headers: Mapping[str, str], requests: Sequence[tuple[str, str]] +) -> Callable[[], set[str]]: + """A ``send`` for :func:`probe`: each read-only request, in order.""" + + import requests as _requests + + check_read_only(requests) + + def send() -> set[str]: + names: set[str] = set() + for method, path in requests: + url = base_url.rstrip("/") + "/" + path.lstrip("/") + _requests.request(method.upper(), url, headers=dict(headers), timeout=60) + names |= _learn.query_fields(path) + return names + + return send + + +def write_report(proposal: Mapping[str, Any], out: Path) -> Path: + out.mkdir(parents=True, exist_ok=True) + path = out / "probe_proposal.json" + path.write_text(json.dumps(proposal, indent=2, sort_keys=True) + "\n") + return path + + +def cmd_probe(args: Any) -> int: + """``openadapt-flow learn probe``.""" + + import os + + import yaml + + from openadapt_flow.generate.verify_contract import choose + + try: + requests = [] + for spec in args.get or []: + requests.append(("GET", spec)) + for spec in args.head or []: + requests.append(("HEAD", spec)) + check_read_only(requests) + headers = ( + json.loads(os.environ.get(args.headers_env, "{}")) + if args.headers_env + else {} + ) + if not isinstance(headers, dict): + raise ProbeError(f"{args.headers_env} must hold a JSON object of headers") + values = yaml.safe_load(Path(args.values).read_text(encoding="utf-8")) or {} + extra = dict(yaml.safe_load(args.extra) or {}) if args.extra else {} + contract, params = choose(Path(args.manifest), args.kind, values, extra) + schema = _learn._schema(args) + users: Optional[_learn.Users] + if args.users: + table, _, key = args.users.partition(".") + users = _learn.users_from(table, key or None, schema, args.user_column) + else: + users = users_for_actor_params(Path(args.manifest), schema) + send = http_sender(args.base_url, headers, requests) + eps = probe(contract, params, kind=args.kind, actor=args.actor, send=send, + rounds=args.rounds) # fmt: skip + proposal = propose(eps, users) + report = write_report(proposal, Path(args.out)) + written: list[tuple[Path, int]] = [] + if args.apply: + files = [p for ps in _learn.contracts_from_manifest(Path(args.manifest)).values() + for p in ps] # fmt: skip + written = apply(proposal, sorted(set(files))) + except (_learn.LearnError, OSError, ValueError) as exc: + print(f"learn probe: {exc}", file=__import__("sys").stderr) + return 2 + body = (proposal.get("kinds") or {}).get("read_only_probe") or {} + print( + f"{len(body.get('excuses') or [])} excuse(s) learned from {len(eps)} read-only " + f"round(s); {len(body.get('stays_a_stop') or [])} move(s) stay a stop. " + f"Report: {report}." + + ( + f" Written into {len(written)} contract(s)." + if args.apply + else " Run again with --apply to write them into the contracts." + ) + ) + return 0 + + +def add_parser(steps: Any) -> None: + """The ``probe`` step of ``openadapt-flow learn``.""" + + p = steps.add_parser( + "probe", + help="learn per-request bookkeeping from read-only requests (no approval)", + allow_abbrev=False, + ) + p.add_argument("--manifest", required=True, help="the generator's manifest.yaml") + p.add_argument( + "--kind", required=True, help="the kind whose contract frames the probe" + ) + p.add_argument( + "--values", required=True, help="YAML: one task's values for that kind" + ) + p.add_argument("--extra", default=None, help="YAML: extra parameters (actor ids)") + p.add_argument("--actor", required=True, help="the agent's user id in the app") + p.add_argument("--base-url", required=True) + p.add_argument("--headers-env", default=None, + help="environment variable holding the agent's request headers as JSON") # fmt: skip + p.add_argument("--get", action="append", default=[], metavar="PATH") + p.add_argument("--head", action="append", default=[], metavar="PATH") + p.add_argument("--rounds", type=int, default=DEFAULT_ROUNDS) + p.add_argument( + "--users", default=None, help="TABLE or TABLE.KEY (default: derived)" + ) + p.add_argument("--user-column", action="append", default=[], metavar="TABLE.COLUMN") + p.add_argument("--schema", default=None) + p.add_argument("--read", default=None) + p.add_argument("--out", default="learn") + p.add_argument("--apply", action="store_true", + help="write the excuses into every contract the manifest lists") # fmt: skip + p.set_defaults(func=cmd_probe) diff --git a/packages/flow/openadapt_flow/runtime/effects/frame.py b/packages/flow/openadapt_flow/runtime/effects/frame.py index bfb3549466..a3f3f0daeb 100644 --- a/packages/flow/openadapt_flow/runtime/effects/frame.py +++ b/packages/flow/openadapt_flow/runtime/effects/frame.py @@ -762,6 +762,7 @@ def evidence(self, spec: FrameSpec) -> dict[str, Any]: "learned": { "proposal_sha256": spec.learned.proposal_sha256, "excuses": len(spec.learned.excuses), + "source": spec.learned.source, "used": sorted(self.learned_used), } } diff --git a/packages/flow/openadapt_flow/runtime/effects/learned.py b/packages/flow/openadapt_flow/runtime/effects/learned.py index 1319afb462..b8be628ae7 100644 --- a/packages/flow/openadapt_flow/runtime/effects/learned.py +++ b/packages/flow/openadapt_flow/runtime/effects/learned.py @@ -129,7 +129,8 @@ def label(self) -> str: class LearnedFrame(BaseModel): - """``frame.learned``: the excuses a person approved from a proposal.""" + """``frame.learned``: the excuses a person approved from a proposal, or + that a read-only probe observed (``source: read_only_probe``).""" model_config = ConfigDict(extra="forbid") @@ -138,6 +139,11 @@ class LearnedFrame(BaseModel): proposal_sha256: str approved_by: str = Field(min_length=1) approved_at: str = Field(min_length=1) + #: ``approval``: a person approved the learner's proposal from checked + #: writes. ``read_only_probe``: rows the app moved while the agent sent + #: only read-only requests (``learn_probe``); the same relation rules + #: apply at check time. + source: Literal["approval", "read_only_probe"] = "approval" @field_validator("proposal_sha256") @classmethod diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py new file mode 100644 index 0000000000..063718f504 --- /dev/null +++ b/packages/flow/tests/test_learn_probe.py @@ -0,0 +1,349 @@ +"""Learning per-request bookkeeping from read-only requests (learn_probe). + +A read-only probe reads the whole-database frame, sends GETs as the agent +and reads again; rows of the acting user that moved become ``frame.learned`` +excuses with ``source: read_only_probe``. These tests check that a correct +write then passes, and attack what the probe must never excuse: another +user's row, another column of the actor's row, a column the contract names, +a row no user owns, extra added rows, and a probe that writes. Each runs on +SQLite, and on MariaDB/MySQL and PostgreSQL when a scratch server is given +(see ``test_learned_excuses``). Records are made up. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from openadapt_flow import learn, learn_probe +from openadapt_flow.generate.sql_store import Column, ForeignKey, Schema, Table +from openadapt_flow.verifier import Contract +from tests import test_learned_excuses as _le +from tests.test_learned_excuses import ( + ACTOR, + Engine, + _refuted, + _title, + check, + note_contract, +) + +# The engines (SQLite, and MySQL or PostgreSQL when given) and the private +# ledger and seal homes, shared with test_learned_excuses. +engine = _le.engine +_homes = _le._homes + +_n = [0] + + +def _t(name: str, cols: list[str], pk: list[str], fks: list[ForeignKey] = ()) -> Table: + columns = [Column(c, "varchar", True, None) for c in cols] + return Table(name, columns, pk, list(fks)) + + +def _schema(tables: list[Table]) -> Schema: + return Schema("sqlite", "app", {t.name: t for t in tables}) + + +def _stamp() -> str: + _n[0] += 1 + return f"p{_n[0]}" + + +def app_reads(e: Engine, user: str = ACTOR, first: bool = True) -> None: + """What the app writes when ``user`` sends any request: the user's + last-login time and token use, and once a first-login property row.""" + + s = _stamp() + e.run("UPDATE app_user SET last_login = %s WHERE id = %s", s, int(user)) + e.run("UPDATE api_token SET last_seen = %s WHERE user_id = %s", s, int(user)) + if first: + e.run( + "INSERT INTO user_property (user_id, property, value) VALUES (%s, %s, %s)", + int(user), + f"first.{s}", + s, + ) + + +def users(e: Engine) -> learn.Users: + schema = _schema( + [ + _t("app_user", ["id", "name", "email", "last_login"], ["id"]), + _t( + "api_token", + ["id", "user_id", "issued_by", "label", "last_seen"], + ["id"], + [ + ForeignKey("user_id", "app_user", "id"), + ForeignKey("issued_by", "app_user", "id"), + ], + ), + _t( + "user_property", + ["user_id", "property", "value"], + ["user_id", "property"], + [ForeignKey("user_id", "app_user", "id")], + ), + _t("note", ["id", "title", "body", "stamp"], ["id"]), + ] + ) + return learn.users_from("app_user", "id", schema) + + +def run_probe(e: Engine, tmp_path: Path, send: Any, rounds: int = 3) -> dict: + c = Contract.from_dict(note_contract(e), name="note") + eps = learn_probe.probe( + c, + {"title": "Probe note", "body": "x"}, + kind="add_note", + actor=ACTOR, + send=send, + rounds=rounds, + workdir=tmp_path / "probe", + ) + return learn_probe.propose(eps, users(e)) + + +def excuses_of(proposal: dict) -> list[dict]: + return proposal["kinds"]["read_only_probe"]["excuses"] + + +def write_contract(e: Engine, tmp_path: Path, proposal: dict) -> dict[str, Any]: + path = tmp_path / "note.yaml" + path.write_text(yaml.safe_dump(note_contract(e))) + written = learn_probe.apply(proposal, [path]) + assert written and written[0][0] == path + data = yaml.safe_load(path.read_text()) + assert data["frame"]["learned"]["source"] == "read_only_probe" + return data + + +def first_once(e: Engine) -> Any: + seen = [False] + + def send() -> set[str]: + app_reads(e, first=not seen[0]) + seen[0] = True + return {"q"} + + return send + + +def test_probe_learns_the_actors_bookkeeping_and_a_correct_write_passes( + engine: Engine, tmp_path: Path +) -> None: + t = _title() + + def write(first: bool = False) -> None: + app_reads(engine, first=first) + engine.run("INSERT INTO note (title, body) VALUES (%s, %s)", t, "Body text") + + before = check( + engine, + note_contract(engine), + {"title": t, "body": "Body text"}, + write, + tmp_path, + ) + _refuted(before) + + proposal = run_probe(engine, tmp_path, first_once(engine)) + got = {(x["table"], x["change"], tuple(x["columns"])) for x in excuses_of(proposal)} + assert got == { + ("app_user", "changed", ("last_login",)), + ("api_token", "changed", ("last_seen",)), + } + # The first-login row the probe saw is an added row: held for a person. + held = proposal["kinds"]["read_only_probe"]["needs_approval"] + assert [(x["table"], x["change"]) for x in held] == [("user_property", "added")] + contract = write_contract(engine, tmp_path, proposal) + t = _title() + after = check(engine, contract, {"title": t, "body": "Body text"}, write, tmp_path) + assert after.outcome.value == "CONFIRMED", after.reasons + assert after.evidence["frame"]["learned"]["source"] == "read_only_probe" + # A row the app adds for the actor still stops until a person approves it. + t = _title() + _refuted( + check( + engine, + contract, + {"title": t, "body": "Body text"}, + lambda: write(first=True), + tmp_path, + ) # fmt: skip + ) + + +def _learned(engine: Engine, tmp_path: Path) -> dict[str, Any]: + return write_contract( + engine, tmp_path, run_probe(engine, tmp_path, first_once(engine)) + ) + + +@pytest.mark.parametrize( + "harm", + [ + "UPDATE app_user SET last_login = 'x' WHERE id = 3", + "UPDATE app_user SET email = 'changed@example.test' WHERE id = 2", + "UPDATE app_user SET last_login = 'x', email = 'e@example.test' WHERE id = 2", + "UPDATE api_token SET last_seen = 'x' WHERE user_id = 3", + "INSERT INTO user_property (user_id, property, value) VALUES (3, 'a', 'b')", + "INSERT INTO user_property (user_id, property, value) VALUES (2, 'extra', 'b')", + "DELETE FROM api_token WHERE user_id = 2", + ], +) +def test_probe_excuses_never_cover_a_harm( + engine: Engine, tmp_path: Path, harm: str +) -> None: + contract = _learned(engine, tmp_path) + t = _title() + + def act() -> None: + app_reads(engine, first=False) + engine.run("INSERT INTO note (title, body) VALUES (%s, %s)", t, "Body text") + engine.run(harm) + + _refuted(check(engine, contract, {"title": t, "body": "Body text"}, act, tmp_path)) + + +def test_a_row_no_user_owns_is_never_learned(engine: Engine, tmp_path: Path) -> None: + def send() -> set[str]: + app_reads(engine, first=False) + # A row that moves on every read but belongs to no user: listed as a + # stop, never excused. + engine.run("UPDATE asset SET modified_at = %s WHERE id = 1", _stamp()) + return set() + + proposal = run_probe(engine, tmp_path, send) + body = proposal["kinds"]["read_only_probe"] + assert {x["table"] for x in body["excuses"]} == {"app_user", "api_token"} + assert any(s["table"] == "asset" for s in body["stays_a_stop"]) + + +def test_another_users_row_moving_in_the_window_is_never_learned( + engine: Engine, tmp_path: Path +) -> None: + def send() -> set[str]: + app_reads(engine, first=False) + app_reads(engine, user="3", first=False) # a colleague, at the same time + return set() + + proposal = run_probe(engine, tmp_path, send) + body = proposal["kinds"]["read_only_probe"] + for x in body["excuses"]: + assert x["relation"] == "actor_row" + contract = write_contract(engine, tmp_path, proposal) + t = _title() + + def act() -> None: + app_reads(engine, first=False) + app_reads(engine, user="3", first=False) + engine.run("INSERT INTO note (title, body) VALUES (%s, %s)", t, "Body text") + + _refuted(check(engine, contract, {"title": t, "body": "Body text"}, act, tmp_path)) + + +def test_a_column_the_probe_or_contract_names_is_never_learned( + engine: Engine, tmp_path: Path +) -> None: + def send() -> set[str]: + app_reads(engine, first=False) + return {"last_login"} # the probe's query named it + + proposal = run_probe(engine, tmp_path, send) + tables = {x["table"] for x in excuses_of(proposal)} + assert "app_user" not in tables and "api_token" in tables + + +def test_nothing_moves_nothing_is_learned(engine: Engine, tmp_path: Path) -> None: + proposal = run_probe(engine, tmp_path, lambda: set()) + assert excuses_of(proposal) == [] + path = tmp_path / "note.yaml" + path.write_text(yaml.safe_dump(note_contract(engine))) + assert learn_probe.apply(proposal, [path]) == [] + assert "learned" not in yaml.safe_load(path.read_text())["frame"] + + +def test_without_a_users_table_nothing_is_learned( + engine: Engine, tmp_path: Path +) -> None: + c = Contract.from_dict(note_contract(engine), name="note") + eps = learn_probe.probe(c, {"title": "P", "body": "x"}, kind="k", actor=ACTOR, + send=first_once(engine), rounds=2, + workdir=tmp_path / "p") # fmt: skip + assert excuses_of(learn_probe.propose(eps, None)) == [] + + +def test_a_probe_sends_read_only_requests_only() -> None: + for bad in ("POST", "PUT", "PATCH", "DELETE"): + with pytest.raises(learn_probe.ProbeError): + learn_probe.check_read_only([("GET", "/a"), (bad, "/b")]) + with pytest.raises(learn_probe.ProbeError): + learn_probe.check_read_only([]) + learn_probe.check_read_only([("GET", "/a"), ("head", "/b")]) + + +def test_a_contract_with_learned_excuses_is_not_overwritten( + engine: Engine, tmp_path: Path +) -> None: + proposal = run_probe(engine, tmp_path, first_once(engine)) + path = tmp_path / "note.yaml" + path.write_text(yaml.safe_dump(note_contract(engine))) + learn_probe.apply(proposal, [path]) + with pytest.raises(learn_probe.ProbeError): + learn_probe.apply(proposal, [path]) + + +def test_users_table_from_the_manifests_actor_parameter(tmp_path: Path) -> None: + schema = _schema( + [ + _t("app_user", ["id"], ["id"]), + _t( + "entry", + ["id", "owner", "title"], + ["id"], + [ForeignKey("owner", "app_user", "id")], + ), # fmt: skip + ] + ) + (tmp_path / "c.yaml").write_text( + yaml.safe_dump( + { + "effects": [ + { + "kind": "record_written", + "match": { + "owner": {"param": "bot_user_id"}, + "title": {"param": "title"}, + }, + } + ] + } # fmt: skip + ) + ) + + def manifest(actor_params: list[str]) -> Path: + m = tmp_path / "manifest.yaml" + m.write_text( + yaml.safe_dump( + { + "actor_params": actor_params, + "kinds": { + "add_entry": { + "main_table": "entry", + "variants": [{"create": "c.yaml"}], + } + }, + } # fmt: skip + ) + ) + return m + + u = learn_probe.users_for_actor_params(manifest(["bot_user_id"]), schema) + assert u is not None and (u.table, u.key) == ("app_user", "id") + assert learn_probe.users_for_actor_params(manifest([]), schema) is None + assert learn_probe.users_for_actor_params(manifest(["other"]), schema) is None From 53910b3c4e3af4550e970e1580fd8db8757399aa Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:16:06 -0500 Subject: [PATCH 3/4] fix(flow): no probe excuse for an update that can't see a lost update; capability row --- CAPABILITIES.md | 1 + llms-full.txt | 5 ++- packages/flow/docs/LEARNED_EXCUSES.md | 8 +++- packages/flow/openadapt_flow/learn_probe.py | 30 ++++++++++++- packages/flow/tests/test_learn_probe.py | 48 ++++++++++++++++++++- 5 files changed, 86 insertions(+), 6 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index ac77f23fe3..379543a346 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -184,6 +184,7 @@ improvising or retrying when something is off. | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | diff --git a/llms-full.txt b/llms-full.txt index c74a23a193..32d454bc26 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -618,6 +618,7 @@ improvising or retrying when something is off. | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | @@ -752,7 +753,7 @@ improvising or retrying when something is off. | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | | See what your own agent gets wrong, with no risk: `openadapt shadow` is a loopback pass-through proxy beside the agent. It checks each write against the system of record (FHIR through `ensure_record`; SQL through the verifier's whole-database frame), checks each `CONFIRMED` again later, and writes `report.html` and `report.json`. It never blocks, changes or resends a write; the only delay is the read before a write (at most `hold_ms`) | [#1678](https://github.com/OpenAdaptAI/OpenAdapt/pull/1678) | Real app (Medplum 5.2.8, 37 cases through a fault proxy: scripted agent 18 of 18 harms caught, 0 correct writes refuted; Claude Sonnet 5.5 9 of 9 caught, 4 correct but corrected writes refuted; 0 writes by the shadow; 15 to 25 ms median added per write; setup 76.5 s machine time, 3 decisions); real app, SQL mode (Dolibarr 21 on MariaDB 11.4, 13 cases: 8 of 8 harms caught, 5 of 5 correct writes confirmed, 292 ms median added); synthetic (SQLite) | `openadapt shadow`, [SHADOW_MODE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SHADOW_MODE.md), [SHADOW_RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/SHADOW_RESULTS.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/skill_cache/README.md) | -| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (draft), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (draft), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | @@ -915,7 +916,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. -- `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +- `learn`: 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. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index 036f76c48a..f3fa7e3e38 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -217,7 +217,13 @@ learned unless you name it (`--users`). `--apply` writes the excuses into every contract the manifest lists, with `frame.learned.source: read_only_probe`, and leaves out of each contract -any excuse for a column that contract names. No person approves them: the +any excuse for a column that contract names. It writes them only into a +contract whose frame can see a lost update without the bookkeeping move: +one whose every declared record is new (`count_new_only`), or one that +reads the target's versions (`frame.versions`). In an update with no +version source, another user's edit that the agent's stale save reverts +leaves nothing changed, and only the bookkeeping move stopped it, so such +contracts keep stopping. No person approves them: the rows were read, the relation is derived from the schema, and the requests are checked to be read-only. A contract that already has `frame.learned` is refused, so a person reconciles the two. Receipts name the source. diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 57e5d7842a..b984ae9c2e 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -228,8 +228,9 @@ def apply( ) -> list[tuple[Path, int]]: """Write the probe's excuses into each contract's ``frame.learned``, all or none. A contract gets only the excuses whose columns it doesn't name - itself; one with a ``frame.learned`` already is refused (a person - reconciles two sets of excuses).""" + itself, and only when it creates new records or reads the target's + versions (:func:`_sees_its_own_harm`); one with a ``frame.learned`` + already is refused (a person reconciles two sets of excuses).""" import yaml @@ -258,6 +259,12 @@ def apply( names |= _learn._names(n) except VerifierError as exc: raise ProbeError(f"{path}: {exc}") from exc + if not _sees_its_own_harm(loaded): + # An update (or a found check) with no version source: another + # user's edit that the agent's stale save reverts leaves nothing + # changed, so before learning only the bookkeeping move stopped + # it. Such a contract gets no automatic excuse. + continue excuses = [ e for e in block["excuses"] @@ -284,6 +291,25 @@ def apply( return [(path, n) for path, _new, n in plan] +def _sees_its_own_harm(contract: Any) -> bool: + """May a probe excuse go into this (loaded) contract? Only when the + frame can see a lost update without the bookkeeping move: every + declared record is new (each ``record_written`` effect counts new rows + only), or the contract reads the target's versions (``frame.versions``).""" + + config = getattr(contract, "config", None) + frame = getattr(config, "frame", None) + if frame is not None and getattr(frame, "versions", None) is not None: + return True + records = [ + e.model_dump(mode="json") + for e in getattr(config, "effects", None) or [] + if str(getattr(getattr(e, "kind", None), "value", getattr(e, "kind", ""))) + == "record_written" + ] + return bool(records) and all(r.get("count_new_only") is True for r in records) + + def http_sender( base_url: str, headers: Mapping[str, str], requests: Sequence[tuple[str, str]] ) -> Callable[[], set[str]]: diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index 063718f504..e27c4c2bee 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -27,9 +27,10 @@ Engine, _refuted, _title, + asset_contract, check, - note_contract, ) +from tests.test_learned_excuses import note_contract as _note_contract # The engines (SQLite, and MySQL or PostgreSQL when given) and the private # ledger and seal homes, shared with test_learned_excuses. @@ -39,6 +40,23 @@ _n = [0] +def note_contract(e: Engine) -> dict[str, Any]: + """Create a note: one new record (``count_new_only``), nothing else.""" + + doc = _note_contract(e) + doc.pop("record") + doc["effects"] = [ + { + "kind": "record_written", + "match": {"title": {"param": "title"}, "body": {"param": "body"}}, + "expected_count": 1, + "count_new_only": True, + "identity_field": "id", + } + ] + return doc + + def _t(name: str, cols: list[str], pk: list[str], fks: list[ForeignKey] = ()) -> Table: columns = [Column(c, "varchar", True, None) for c in cols] return Table(name, columns, pk, list(fks)) @@ -347,3 +365,31 @@ def manifest(actor_params: list[str]) -> Path: assert u is not None and (u.table, u.key) == ("app_user", "id") assert learn_probe.users_for_actor_params(manifest([]), schema) is None assert learn_probe.users_for_actor_params(manifest(["other"]), schema) is None + + +def test_an_update_without_a_version_source_gets_no_probe_excuse( + engine: Engine, tmp_path: Path +) -> None: + # Another user's edit that the agent's stale save reverts leaves the + # target unchanged. Without versions, only the bookkeeping move stopped + # such a write, so an update contract with no version source keeps it. + proposal = run_probe(engine, tmp_path, first_once(engine)) + assert excuses_of(proposal) + path = tmp_path / "asset.yaml" + path.write_text(yaml.safe_dump(asset_contract(engine))) + assert learn_probe.apply(proposal, [path]) == [] + assert "learned" not in yaml.safe_load(path.read_text())["frame"] + + def act() -> None: + app_reads(engine, first=False) + engine.run("UPDATE asset SET name = 'Laptop B' WHERE id = 1") + + _refuted( + check( + engine, + yaml.safe_load(path.read_text()), + {"tag": "LT-100", "name": "Laptop B"}, + act, + tmp_path, + ) # fmt: skip + ) From 7c624aa69213b8e84a27c489a34421132b8fbea1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:08:59 -0500 Subject: [PATCH 4/4] feat(flow): verdict tiers, entity-scoped frames, shadow mode by default Rows that move with no harm (a scheduler, a task queue, totals the app recomputes, notifications) stopped correct writes under the whole-database frame. With frame.database.entity_tables, rows added or changed outside the business-entity tables are logged side effects on a CONFIRMED result and candidates for the learner; removed rows, entity-table rows the write doesn't declare, another user's row and an unexcused column of the actor's row still refute. learn entities derives the scope from the setup and applies it only when planted faults are all still caught under it (runtime/effects/admission.py). The verifier waits for declared records with backoff before judging, settling ignores motion outside the scope, and a generated read's check columns are not compared on undeclared rows. New contracts start in shadow (WriteResult.blocks false) until N clean checks in a row, then a person can turn gating on (openadapt-flow gate). --- CAPABILITIES.md | 4 +- llms-full.txt | 4 +- packages/flow/docs/VERDICT_TIERS.md | 125 +++++ .../11-guard-an-agent-you-already-run/gate.md | 1 + .../learn.md | 2 +- packages/flow/openadapt_flow/__main__.py | 5 + packages/flow/openadapt_flow/cli_gate.py | 81 +++ packages/flow/openadapt_flow/enforcement.py | 221 ++++++++ packages/flow/openadapt_flow/learn.py | 13 + .../flow/openadapt_flow/learn_entities.py | 283 ++++++++++ .../runtime/effects/admission.py | 139 +++++ .../runtime/effects/db_snapshot.py | 17 +- .../openadapt_flow/runtime/effects/frame.py | 113 +++- packages/flow/openadapt_flow/verifier.py | 155 ++++- packages/flow/openadapt_flow/verify_run.py | 2 +- packages/flow/tests/test_verdict_tiers.py | 528 ++++++++++++++++++ packages/flow/tests/test_verifier_api.py | 3 +- 17 files changed, 1685 insertions(+), 11 deletions(-) create mode 100644 packages/flow/docs/VERDICT_TIERS.md create mode 100644 packages/flow/docs/commands/11-guard-an-agent-you-already-run/gate.md create mode 100644 packages/flow/openadapt_flow/cli_gate.py create mode 100644 packages/flow/openadapt_flow/enforcement.py create mode 100644 packages/flow/openadapt_flow/learn_entities.py create mode 100644 packages/flow/openadapt_flow/runtime/effects/admission.py create mode 100644 packages/flow/tests/test_verdict_tiers.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index e6c1f6121c..2c7ebbb89b 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -185,6 +185,7 @@ improvising or retrying when something is off. | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | +| 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) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | @@ -482,8 +483,9 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** +- `gate`: 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`). - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. -- `learn`: 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`: 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. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/llms-full.txt b/llms-full.txt index 4d0ffcd1ec..eefc6b5331 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -619,6 +619,7 @@ improvising or retrying when something is off. | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | +| 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](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERDICT_TIERS.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | @@ -916,8 +917,9 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** +- `gate`: 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`). - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. -- `learn`: 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`: 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. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. 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 931f0ee13a..be7023a16c 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13186,6 +13186,10 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _register_shadow(sub) + from openadapt_flow.cli_gate import register as _register_gate + + _register_gate(sub) + from openadapt_flow.cli_receipt import register as _register_receipt _register_receipt(sub) @@ -13735,6 +13739,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/enforcement.py b/packages/flow/openadapt_flow/enforcement.py new file mode 100644 index 0000000000..116b45406d --- /dev/null +++ b/packages/flow/openadapt_flow/enforcement.py @@ -0,0 +1,221 @@ +"""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. + fd = os.open(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 + for e in checks: + clean = e.get("outcome") == "CONFIRMED" 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 Exception: # noqa: BLE001 - the log never changes a verdict + pass + try: + return status(digest).mode + except Exception: # noqa: BLE001 + 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 0fee10dbac..db930179c7 100644 --- a/packages/flow/openadapt_flow/learn.py +++ b/packages/flow/openadapt_flow/learn.py @@ -131,6 +131,12 @@ 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") + if out["outcome"] == "CONFIRMED" 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 @@ -340,6 +346,9 @@ def _why_ignored(ep: Mapping[str, Any]) -> Optional[str]: return "nothing moved in the read-only window" return _why_rows_ignored(ep) outcome = ep.get("outcome") + if outcome == "CONFIRMED" and ep.get("logged") and ep.get("delta") == "held": + # Passed with logged side effects: they are candidate excuses. + return _why_rows_ignored(ep) if outcome == "CONFIRMED": return "confirmed: nothing moved that needs an excuse" if ep.get("delta") != "held": @@ -951,6 +960,10 @@ def build_parser(p: argparse.ArgumentParser) -> argparse.ArgumentParser: from openadapt_flow import learn_probe learn_probe.add_parser(steps) + + from openadapt_flow import learn_entities + + learn_entities.add_parser(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..8b8b1fb10b --- /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 add_parser(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") + add_parser(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 4ff0eea25b..32ac441849 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 a3f3f0daeb..2d9077786a 100644 --- a/packages/flow/openadapt_flow/runtime/effects/frame.py +++ b/packages/flow/openadapt_flow/runtime/effects/frame.py @@ -380,6 +380,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]: @@ -395,6 +428,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") @@ -722,6 +757,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: @@ -757,6 +798,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": { @@ -772,6 +821,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) @@ -1041,6 +1115,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] @@ -1066,7 +1148,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 @@ -2160,6 +2242,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="", @@ -2175,6 +2274,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 ( @@ -2300,6 +2403,14 @@ 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}) + parts.append( + f"{len(verdict.side_effects)} row(s) moved outside the entity tables " + f"({', '.join(tables[:_SAMPLE_LIMIT])}" + 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 6ef16f82da..7656e3e18e 100644 --- a/packages/flow/openadapt_flow/verifier.py +++ b/packages/flow/openadapt_flow/verifier.py @@ -641,11 +641,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 @@ -715,6 +751,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, } @@ -1759,6 +1799,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, @@ -1793,15 +1838,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 Exception: # noqa: BLE001 - no wait; the judge decides + 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 Exception: # noqa: BLE001 + 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 cabfb87834..804be72eec 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -1092,7 +1092,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/test_verdict_tiers.py b/packages/flow/tests/test_verdict_tiers.py new file mode 100644 index 0000000000..c120b4c5f5 --- /dev/null +++ b/packages/flow/tests/test_verdict_tiers.py @@ -0,0 +1,528 @@ +"""Verdict tiers, entity-scoped frames, the retry wait, shadow mode and the +safety bar (``docs/VERDICT_TIERS.md``), on a real SQLite store. + +A whole-database frame stops a correct write when a row moves anywhere: a +task queue, a cache the app recomputes. With ``frame.database.entity_tables`` +those rows are logged and the write passes; everything the safety bar names +(a sibling record edited, another user's row, another column of the actor's +row, a removed row, a duplicate) still stops it. Records are made up. +""" + +from __future__ import annotations + +import json +import sqlite3 +import threading +from pathlib import Path +from typing import Any, Callable, Optional + +import pytest +import yaml + +from openadapt_flow import enforcement, learn, learn_entities +from openadapt_flow.runtime.effects import admission +from openadapt_flow.runtime.effects.admission import FaultResult +from openadapt_flow.verifier import ( + Actor, + Contract, + await_effects, + begin_write, + verify_write, +) + +ACTOR = "2" + + +@pytest.fixture(autouse=True) +def _homes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("OPENADAPT_LEDGER_DIR", str(tmp_path / "ledger")) + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + monkeypatch.setenv("OPENADAPT_GATE_DIR", str(tmp_path / "gates")) + monkeypatch.setenv("OPENADAPT_VERIFY_RETRY_S", "0") + monkeypatch.delenv("OPENADAPT_ENFORCEMENT", raising=False) + monkeypatch.delenv("OPENADAPT_GATE_CLEAN_RUNS", raising=False) + + +class Store: + def __init__(self, path: Path) -> None: + self.path = path + for sql in ( + "CREATE TABLE app_user (id INTEGER PRIMARY KEY, name TEXT, email TEXT)", + "CREATE TABLE project (id INTEGER PRIMARY KEY, name TEXT)", + "CREATE TABLE entry (id INTEGER PRIMARY KEY, user_id INTEGER, " + "project_id INTEGER, note TEXT, " + "FOREIGN KEY (user_id) REFERENCES app_user(id), " + "FOREIGN KEY (project_id) REFERENCES project(id))", + "CREATE TABLE job_queue (id INTEGER PRIMARY KEY, state TEXT, beat TEXT)", + "CREATE TABLE project_total (id INTEGER PRIMARY KEY, project_id INTEGER, " + "hours INTEGER)", + "INSERT INTO app_user VALUES (1, 'admin', 'a@example.test'), " + "(2, 'agentbot', 'b@example.test'), (3, 'colleague', 'c@example.test')", + "INSERT INTO project VALUES (1, 'Website'), (2, 'Audit')", + "INSERT INTO entry VALUES (1, 3, 1, 'Earlier entry')", + "INSERT INTO job_queue VALUES (1, 'idle', 't0'), (2, 'done', 't0')", + "INSERT INTO project_total VALUES (1, 1, 2)", + ): + self.run(sql) + + def run(self, sql: str, *args: Any) -> None: + con = sqlite3.connect(self.path) + con.execute(sql, args) + con.commit() + con.close() + + +@pytest.fixture +def store(tmp_path: Path) -> Store: + return Store(tmp_path / "app.sqlite") + + +ENTITIES = ["entry", "project", "app_user"] + + +def contract( + s: Store, entity_tables: Optional[list[str]] = None, query: str = "" +) -> dict: + db: dict[str, Any] = { + "dialect": "sqlite", + "read": {"sqlite_database": str(s.path)}, + "views": {"entry": ""}, + "new_row_fields": {"entry": ["id"]}, + "settle_s": 0, + } + if entity_tables is not None: + db["entity_tables"] = entity_tables + return { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "sql", + "sqlite_database": str(s.path), + "sql_query": query or "SELECT * FROM entry", + }, + "effects": [ + { + "kind": "record_written", + "match": { + "note": {"param": "note"}, + "user_id": {"param": "user"}, + "project_id": {"literal": "1"}, + }, + "expected_count": 1, + "count_new_only": True, + } + ], + "frame": {"identity_field": "id", "database": db}, + } + + +def check(doc: dict, act: Callable[[], None], tmp_path: Path, note: str = "New") -> Any: + c = Contract.from_dict(doc, name="c") + pending = begin_write( + c, + {"note": note, "user": ACTOR}, + actor=Actor("agent", ACTOR), + ledger=None, + workdir=tmp_path / f"w{len(list(tmp_path.glob('w*')))}", + ) + act() + return verify_write(pending, seal=False) + + +def write(s: Store, note: str = "New") -> None: + s.run("INSERT INTO entry (user_id, project_id, note) VALUES (2, 1, ?)", note) + + +def background(s: Store) -> None: + """What the app does on its own: a queue heartbeat and a recomputed total.""" + + s.run("UPDATE job_queue SET beat = 't1', state = 'busy' WHERE id = 1") + s.run("INSERT INTO job_queue (state, beat) VALUES ('new', 't1')") + s.run("UPDATE project_total SET hours = 3 WHERE project_id = 1") + + +# -- tiers -------------------------------------------------------------------------- + + +def test_without_a_scope_background_rows_still_refute( + store: Store, tmp_path: Path +) -> None: + r = check(contract(store), lambda: (write(store), background(store)), tmp_path) + assert r.outcome.value == "REFUTED" + assert r.tier == "hard" + assert r.side_effects == [] + + +def test_with_a_scope_background_rows_are_logged_and_the_write_passes( + store: Store, tmp_path: Path +) -> None: + r = check( + contract(store, ENTITIES), lambda: (write(store), background(store)), tmp_path + ) + assert r.outcome.value == "CONFIRMED", r.reasons + assert r.tier == "logged" + by = {(x["table"], x["change"]): x for x in r.side_effects} + assert by[("job_queue", "changed")]["columns"] == ["beat", "state"] + assert by[("job_queue", "added")]["rows"] == 1 + assert by[("project_total", "changed")]["columns"] == ["hours"] + # Names only: no keys and no values reach the evidence. + assert "t1" not in json.dumps(r.side_effects) + assert r.to_dict()["tier"] == "logged" + + +def test_a_clean_write_is_clean(store: Store, tmp_path: Path) -> None: + r = check(contract(store, ENTITIES), lambda: write(store), tmp_path) + assert r.outcome.value == "CONFIRMED" and r.tier == "clean" + + +@pytest.mark.parametrize( + "harm", + [ + # A sibling business record edited. + "UPDATE entry SET note = 'Changed' WHERE id = 1", + # Another user's row of the acting user's table. + "UPDATE app_user SET email = 'x@example.test' WHERE id = 3", + # Another column of the actor's own row. + "UPDATE app_user SET email = 'x@example.test' WHERE id = 2", + # A record the write's location reads through. + "UPDATE project SET name = 'Renamed' WHERE id = 1", + # A removed row, even outside the entity tables. + "DELETE FROM job_queue WHERE id = 2", + # A duplicate of the written record. + "INSERT INTO entry (user_id, project_id, note) VALUES (2, 1, 'New')", + ], +) +def test_the_safety_bar_still_stops_under_a_scope( + store: Store, tmp_path: Path, harm: str +) -> None: + r = check( + contract(store, ENTITIES), + lambda: (write(store), background(store), store.run(harm)), + tmp_path, + ) + assert r.outcome.value == "REFUTED", harm + assert r.blocks is False # shadow by default: refuted, recorded, not blocking + + +def test_a_wrong_value_still_refutes_under_a_scope( + store: Store, tmp_path: Path +) -> None: + r = check( + contract(store, ENTITIES), + lambda: (write(store, "Wrong"), background(store)), + tmp_path, + note="New", + ) + assert r.outcome.value != "CONFIRMED" + + +def test_the_frames_own_tables_are_always_entities(store: Store) -> None: + c = Contract.from_dict(contract(store, []), name="c") + scope = c.config.frame.database.entity_scope(c.config.frame) + assert scope is not None and "entry" in scope # views + + +def test_a_derived_check_column_never_moves_the_frame( + store: Store, tmp_path: Path +) -> None: + # pin__queue is a check computed by the read; it flips with a table the + # scope logs, on every row, with no write to the row. + q = "SELECT e.*, (SELECT COUNT(*) FROM job_queue) AS pin__queue FROM entry e" + r = check( + contract(store, ENTITIES, query=q), + lambda: (write(store), background(store)), + tmp_path, + ) + assert r.outcome.value == "CONFIRMED", r.reasons + + +# -- retry ---------------------------------------------------------------------------- + + +def test_the_retry_wait_waits_for_a_slow_commit(store: Store) -> None: + c = Contract.from_dict(contract(store), name="c") + slept: list[float] = [] + + def sleep(s: float) -> None: + slept.append(s) + if len(slept) == 2: + write(store) + + reads = await_effects(c, {"note": "New", "user": ACTOR}, budget_s=8, sleep=sleep) + assert reads == 3 + assert slept == [0.5, 1.0] + + +def test_the_retry_wait_gives_up_within_its_budget(store: Store) -> None: + c = Contract.from_dict(contract(store), name="c") + slept: list[float] = [] + await_effects(c, {"note": "Never", "user": ACTOR}, budget_s=4, sleep=slept.append) + assert sum(slept) <= 4 and slept == [0.5, 1.0, 2.0] + + +def test_the_retry_wait_never_reads_through_an_api() -> None: + doc = { + "schema_version": "openadapt.verify/v1", + "verifier": {"kind": "rest", "base_url": "http://127.0.0.1:1", "path": "/x"}, + "effects": [{"kind": "record_written", "match": {"a": {"literal": "1"}}}], + } + try: + c = Contract.from_dict(doc, name="c") + except Exception: # noqa: BLE001 - a config this build rejects reads nothing either + return + assert await_effects(c, {}, budget_s=8, sleep=lambda s: None) == 0 + + +# -- shadow mode ---------------------------------------------------------------------- + + +def test_a_new_contract_is_shadow_until_n_clean_checks( + store: Store, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("OPENADAPT_GATE_CLEAN_RUNS", "20") + doc = contract(store, ENTITIES) + digest = Contract.from_dict(doc, name="c").digest + bad = check( + doc, + lambda: (write(store, "x0"), store.run("DELETE FROM job_queue WHERE id = 2")), + tmp_path, + note="x0", + ) + assert bad.enforcement == "shadow" and not bad.blocks + for i in range(19): + check(doc, lambda i=i: write(store, f"n{i}"), tmp_path, note=f"n{i}") + st = enforcement.status(digest) + assert st.clean_in_a_row == 19 and not st.offered + with pytest.raises(enforcement.GateRefused): + enforcement.enable(digest, "A. Reviewer") + check(doc, lambda: write(store, "n19"), tmp_path, note="n19") + assert enforcement.status(digest).offered + enforcement.enable(digest, "A. Reviewer") + harm = check( + doc, + lambda: ( + write(store, "n20"), + store.run("UPDATE entry SET note = 'z' WHERE id = 1"), + ), + tmp_path, + note="n20", + ) + assert harm.enforcement == "gating" and harm.blocks + + +def test_a_stop_labelled_caught_keeps_the_run(tmp_path: Path) -> None: + class R: + def __init__(self, wid: str, outcome: str) -> None: + self.write_id = wid + self.outcome = type("O", (), {"value": outcome})() + self.tier = "" + + d = "sha256:" + "0" * 64 + enforcement.observe(d, R("a", "CONFIRMED")) + enforcement.observe(d, R("b", "REFUTED")) + enforcement.observe(d, R("c", "CONFIRMED")) + assert enforcement.status(d).clean_in_a_row == 1 + enforcement.label(d, "b", "caught") + assert enforcement.status(d).clean_in_a_row == 3 + enforcement.label(d, "b", "false_stop") + st = enforcement.status(d) + assert st.clean_in_a_row == 1 and st.false_stops == 1 + + +def test_n_is_kept_between_20_and_50(monkeypatch: pytest.MonkeyPatch) -> None: + for raw, want in (("5", 20), ("35", 35), ("500", 50), ("x", 30)): + monkeypatch.setenv("OPENADAPT_GATE_CLEAN_RUNS", raw) + assert enforcement.clean_runs_needed() == want + + +def test_the_environment_can_gate_everything(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("OPENADAPT_ENFORCEMENT", "gating") + assert enforcement.status("sha256:" + "1" * 64).mode == "gating" + + +# -- the learner ---------------------------------------------------------------------- + + +def test_logged_side_effects_are_offered_to_the_learner( + store: Store, tmp_path: Path +) -> None: + r = check( + contract(store, ENTITIES), lambda: (write(store), background(store)), tmp_path + ) + ep = learn.episode_record(type("E", (), {"kind": "sql"})(), r) + assert ep.get("logged") is True + assert {m["table"] for m in ep["moves"]} == {"job_queue", "project_total"} + assert learn._why_ignored(ep) is None + + +# -- the safety bar ------------------------------------------------------------------- + + +def _all(caught: bool = True) -> list[FaultResult]: + return [ + FaultResult(f"{c}-1", c, caught) + for c in (*admission.SAFETY_BAR, *admission.ACTOR_ATTACKS) + ] + + +def test_admitted_only_when_every_class_ran_and_was_caught() -> None: + assert admission.admit("x", _all()).admitted + missing = [r for r in _all() if r.fault_class != "lost_update"] + d = admission.admit("x", missing) + assert not d.admitted and "lost_update" in d.reasons[0] + + +@pytest.mark.parametrize("cls", [*admission.SAFETY_BAR, *admission.ACTOR_ATTACKS]) +def test_a_relaxation_that_lets_any_planted_fault_through_is_refused(cls: str) -> None: + results = [ + r if r.fault_class != cls else FaultResult(r.case, cls, False) for r in _all() + ] + d = admission.admit( + "x", results, required=(*admission.SAFETY_BAR, *admission.ACTOR_ATTACKS) + ) + assert not d.admitted and any(cls in why for why in d.reasons) + + +def test_a_case_caught_before_must_still_be_run() -> None: + before = _all() + [FaultResult("extra", "sibling_edit", True)] + d = admission.admit("x", _all(), before) + assert not d.admitted and "extra" in d.reasons[0] + + +def test_fault_gate_names_count_for_the_bar() -> None: + results = [ + FaultResult("a", "wrong_record", True), + FaultResult("b", "unrelated_edit", True), + *[ + FaultResult(c, c, True) + for c in ("wrong_value", "duplicate", "late_revert", "lost_update") + ], + ] + assert admission.admit("x", results).admitted + + +def _setup(store: Store, tmp_path: Path) -> Path: + folder = tmp_path / "setup" + folder.mkdir() + (folder / "c.create.yaml").write_text( + yaml.safe_dump(contract(store)), encoding="utf-8" + ) + (folder / "manifest.yaml").write_text( + yaml.safe_dump( + { + "actor_params": ["user"], + "kinds": { + "log": { + "main_table": "entry", + "variants": [{"create": "c.create.yaml"}], + } + }, + } + ), + encoding="utf-8", + ) + return folder / "manifest.yaml" + + +def _schema(store: Store) -> Any: + """The store's schema as ``generate schema`` writes it (SQLite has no + schema reader; the shape is the same).""" + + from openadapt_flow.generate.sql_store import Column, ForeignKey, Schema, Table + + con = sqlite3.connect(store.path) + tables = {} + for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type = 'table'"): + cols = [ + Column(r[1], r[2] or "TEXT", not r[3], r[4]) + for r in con.execute(f"PRAGMA table_info({name})") + ] + pk = [r[1] for r in con.execute(f"PRAGMA table_info({name})") if r[5]] + fks = [ + ForeignKey(r[3], r[2], r[4]) + for r in con.execute(f"PRAGMA foreign_key_list({name})") + ] + tables[name] = Table(name, cols, pk, fks) + con.close() + return Schema("sqlite", "main", tables) + + +def test_entity_scope_is_derived_staged_and_applied_only_on_evidence( + store: Store, tmp_path: Path +) -> None: + manifest = _setup(store, tmp_path) + proposal = learn_entities.derive(manifest, _schema(store)) + assert proposal["actor_table"] == "app_user" + assert set(proposal["entity_tables"]) == {"entry", "app_user"} + assert "job_queue" not in proposal["entity_tables"] + staged = learn_entities.stage(proposal, tmp_path / "candidate") + doc = yaml.safe_load((staged.parent / "c.create.yaml").read_text()) + assert doc["frame"]["database"]["entity_tables"] == proposal["entity_tables"] + faults = tmp_path / "faults.json" + + def results(caught: bool, digest: str) -> None: + faults.write_text( + json.dumps( + { + "schema": admission.SCHEMA, + "proposal_sha256": digest, + "cases": [ + {"case": r.case, "class": r.fault_class, "caught": caught} + for r in _all() + ], + } + ) + ) + + results(True, "sha256:" + "f" * 64) + with pytest.raises(admission.AdmissionRefused): + learn_entities.apply(proposal, faults, "A. Reviewer") + results(False, proposal["proposal_sha256"]) + with pytest.raises(admission.AdmissionRefused): + learn_entities.apply(proposal, faults, "A. Reviewer") + original = (manifest.parent / "c.create.yaml").read_text() + assert "entity_tables" not in original + results(True, proposal["proposal_sha256"]) + learn_entities.apply(proposal, faults, "A. Reviewer") + doc = yaml.safe_load((manifest.parent / "c.create.yaml").read_text()) + assert doc["frame"]["database"]["entity_tables"] == proposal["entity_tables"] + + +def test_no_scope_without_the_acting_users_table(store: Store, tmp_path: Path) -> None: + manifest = _setup(store, tmp_path) + data = yaml.safe_load(manifest.read_text()) + data["actor_params"] = [] + manifest.write_text(yaml.safe_dump(data)) + with pytest.raises(learn_entities.EntityScopeError): + learn_entities.derive(manifest, _schema(store)) + + +def test_tables_in_sql() -> None: + q = ( + "SELECT CAST(t.`id` AS CHAR), (SELECT a.`name` FROM `projects` a WHERE a.id = " + 't.project_id) FROM `entries` t JOIN "public"."tags" g ON 1=1' + ) + assert learn_entities.tables_in_sql(q) == {"projects", "entries", "public.tags"} + + +def test_settling_ignores_motion_outside_the_scope( + store: Store, tmp_path: Path +) -> None: + stop = threading.Event() + + def churn() -> None: + n = 0 + while not stop.is_set(): + n += 1 + store.run("UPDATE job_queue SET beat = ? WHERE id = 1", f"b{n}") + stop.wait(0.02) + + doc = contract(store, ENTITIES) + doc["frame"]["database"]["settle_s"] = 0.1 + doc["frame"]["database"]["settle_attempts"] = 2 + t = threading.Thread(target=churn, daemon=True) + try: + r = check(doc, lambda: (write(store), t.start()), tmp_path) + finally: + stop.set() + t.join(timeout=5) + assert r.outcome.value == "CONFIRMED", r.reasons diff --git a/packages/flow/tests/test_verifier_api.py b/packages/flow/tests/test_verifier_api.py index ba06d11c8a..ca5ab3a864 100644 --- a/packages/flow/tests/test_verifier_api.py +++ b/packages/flow/tests/test_verifier_api.py @@ -460,11 +460,12 @@ def params(fn: Any) -> list[tuple[str, str]]: "reasons", "retry_safe", ] - assert list(WriteResult.__dataclass_fields__)[-4:] == [ + assert list(WriteResult.__dataclass_fields__)[-5:] == [ "recheck", "recheck_due_at", "write_receipt", "write_receipt_path", + "enforcement", ] assert params(recheck) == [ ("contract", "POSITIONAL_OR_KEYWORD"),