From e6f94397e30ccafdc62d8eb146978749a4dcd6f0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 20:48:21 -0500 Subject: [PATCH 01/14] 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 02/14] 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 e41327345c3b4f62bac9b35bbf8fc18f6ff00db5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:45:16 -0500 Subject: [PATCH 03/14] feat(flow): row versions held from the baseline count who saved the target On PostgreSQL, a read-only REPEATABLE READ snapshot opened at the baseline still sees the row version that was current then. Its xmax names the transaction that replaced it; the current row's xmin names the last writer. Equal: one transaction wrote the target in the window. Different: two or more, which is a lost update. frame.row_versions turns this on per contract, and learn probe now writes it beside a bookkeeping excuse on an update or found check whose generated read it can trace to one table. MySQL and MariaDB targets get no source: a last-saved marker reads the same after one save as after two. --- packages/flow/openadapt_flow/learn_probe.py | 89 +++- .../openadapt_flow/runtime/effects/frame.py | 13 + .../runtime/effects/row_versions.py | 314 +++++++++++++ packages/flow/openadapt_flow/verify_run.py | 172 ++++++-- packages/flow/tests/test_row_versions.py | 411 ++++++++++++++++++ 5 files changed, 956 insertions(+), 43 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/effects/row_versions.py create mode 100644 packages/flow/tests/test_row_versions.py diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index b984ae9c2e..61ac690d7d 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -38,6 +38,7 @@ from __future__ import annotations import json +import re import tempfile from collections.abc import Callable, Mapping, Sequence from pathlib import Path @@ -259,12 +260,16 @@ def apply( names |= _learn._names(n) except VerifierError as exc: raise ProbeError(f"{path}: {exc}") from exc + row_versions = None 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 + # it. Such a contract gets an excuse only with a version source + # derived here, written beside it. + row_versions = detect_row_versions(data) + if row_versions is None: + continue excuses = [ e for e in block["excuses"] @@ -277,6 +282,8 @@ def apply( **frame, "learned": {**block, "excuses": excuses, "source": "read_only_probe"}, } + if row_versions is not None: + new["frame"]["row_versions"] = row_versions try: Contract.from_dict(new, name=Path(path).stem) except VerifierError as exc: @@ -295,11 +302,15 @@ 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``).""" + only), or the contract reads the target's versions (``frame.versions`` + or ``frame.row_versions``).""" config = getattr(contract, "config", None) frame = getattr(config, "frame", None) - if frame is not None and getattr(frame, "versions", None) is not None: + if frame is not None and ( + getattr(frame, "versions", None) is not None + or getattr(frame, "row_versions", None) is not None + ): return True records = [ e.model_dump(mode="json") @@ -310,6 +321,76 @@ def _sees_its_own_harm(contract: Any) -> bool: return bool(records) and all(r.get("count_new_only") is True for r in records) +_IDENT = r'(?:"[A-Za-z_][A-Za-z0-9_$]*"|[A-Za-z_][A-Za-z0-9_$]*)' +#: The main relation of a generated read: ``... FROM "table" t`` at the end. +_MAIN_FROM = re.compile( + rf"\bFROM\s+({_IDENT}(?:\.{_IDENT})?)\s+(?:AS\s+)?t\s*;?\s*$", re.IGNORECASE +) + + +def _unquote(name: str) -> str: + return ".".join(p.strip('"') for p in name.split(".")) + + +def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: + """A version source for an update or found check, from the contract + alone: on PostgreSQL, the target's own row versions + (``frame.row_versions``). Found only when every write effect reads one + surface, that surface's read is a plain ``SELECT ... FROM t`` + over the frame's own connection, and it selects the identity field + straight from one column. Anything else: None (no excuse). + + A MySQL or MariaDB target has no such source: ``updated_at`` and + ``ON UPDATE`` columns read the same after one save as after two, so they + can't count saves. Those need a history read (``frame.versions``) or the + database's change log.""" + + frame = data.get("frame") if isinstance(data, Mapping) else None + database = frame.get("database") if isinstance(frame, Mapping) else None + if not isinstance(database, Mapping) or database.get("dialect") != "postgresql": + return None + surfaces: set[str] = set() + for effect in data.get("effects") or []: + if not isinstance(effect, Mapping): + return None + if effect.get("kind") not in ("record_written", "field_equals"): + continue + if effect.get("kind") == "record_written" and effect.get("expected_count") == 0: + continue # a guard reads; it has no target + probe = str(effect.get("probe") or "") + if not probe.startswith("surface="): + return None + surfaces.add(probe[len("surface=") :].split("|", 1)[0].strip()) + if len(surfaces) != 1: + return None + (surface,) = surfaces + verifier = data.get("verifier") if isinstance(data, Mapping) else None + source = ((verifier or {}).get("surfaces") or {}).get(surface) + if not isinstance(source, Mapping) or source.get("kind") != "sql": + return None + read = database.get("read") or {} + if any(source.get(k) != read.get(k) for k in ("sql_driver", "sql_connect_args")): + return None # another database: its rows aren't the frame's + query = " ".join(str(source.get("sql_query") or "").split()) + main = _MAIN_FROM.search(query) + if main is None: + return None + field = str(frame.get("identity_field") or "id") + column = re.search( + rf'(?:CAST\(\s*)?t\.({_IDENT})(?:\s+AS\s+TEXT\s*\))?\s+AS\s+"?{re.escape(field)}"?\s*,', + query, + re.IGNORECASE, + ) + if column is None: + return None + return { + "source": "postgresql_xmin", + "table": _unquote(main.group(1)), + "key_column": _unquote(column.group(1)), + "target_surface": surface, + } + + def http_sender( base_url: str, headers: Mapping[str, str], requests: Sequence[tuple[str, str]] ) -> Callable[[], set[str]]: diff --git a/packages/flow/openadapt_flow/runtime/effects/frame.py b/packages/flow/openadapt_flow/runtime/effects/frame.py index a3f3f0daeb..885b322b24 100644 --- a/packages/flow/openadapt_flow/runtime/effects/frame.py +++ b/packages/flow/openadapt_flow/runtime/effects/frame.py @@ -99,6 +99,7 @@ covers, set_columns, ) +from openadapt_flow.runtime.effects.row_versions import FrameRowVersions from openadapt_flow.runtime.effects.versions import FrameVersions, VersionVerdict FrameStatus = Literal["held", "refuted", "not_checked"] @@ -516,6 +517,10 @@ class FrameSpec(BaseModel): #: (``versions.FrameVersions``): a version in the window that isn't the #: agent's own is a lost update. versions: Optional[FrameVersions] = None + #: The target's own row versions, held from the baseline + #: (``row_versions.FrameRowVersions``, PostgreSQL): two transactions + #: writing the target in the window are a lost update. + row_versions: Optional[FrameRowVersions] = None #: Complete type/table change feeds for a provisional then final verdict. history: Optional[FrameHistory] = None #: Moves a person approved from ``openadapt-flow learn`` @@ -534,6 +539,8 @@ def _compact(self, handler: Any) -> dict[str, Any]: data.pop("identities", None) if data.get("versions") is None: data.pop("versions", None) + if data.get("row_versions") is None: + data.pop("row_versions", None) if data.get("learned") is None: data.pop("learned", None) if data.get("target_fields_by_surface") is None: @@ -543,6 +550,12 @@ def _compact(self, handler: Any) -> dict[str, Any]: @model_validator(mode="after") def _database_attribution(self) -> "FrameSpec": a = self.attribution + if self.row_versions is not None: + if self.database is None or self.database.dialect != "postgresql": + raise ValueError( + "frame.row_versions reads through frame.database, PostgreSQL only" + ) + self.row_versions.names() if ( self.history is not None and self.database is not None diff --git a/packages/flow/openadapt_flow/runtime/effects/row_versions.py b/packages/flow/openadapt_flow/runtime/effects/row_versions.py new file mode 100644 index 0000000000..0b258aa82e --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/effects/row_versions.py @@ -0,0 +1,314 @@ +"""Row versions held from the baseline: count who saved the target. + +Two snapshots can't see a lost update (``versions.py``). A "last saved" +marker on the row, such as PostgreSQL's ``xmin`` or an ``updated_at`` +column, can't either: after another user's save and the agent's stale save, +it reads the same as after the agent's save alone. A marker only proves that +nobody saved. + +PostgreSQL keeps more than the marker. A read-only REPEATABLE READ +transaction opened at the baseline keeps seeing the row version that was +current then, and that old version's ``xmax`` names the transaction that +replaced it. The current version's ``xmin`` names the transaction that wrote +it. So, per target row: + +- ``xmin`` unchanged: no transaction wrote the row in the window (0). +- the old ``xmax`` equals the current ``xmin``: one transaction replaced the + version the baseline saw, and nothing replaced it since (1). +- anything else: two or more transactions wrote the row (2+). A lock taken + while the row was being updated also lands here; that is a stop, never a + pass. + +``frame.row_versions`` names the target's table and key column. The +verifier opens the held read before it reads the baseline records, keeps it +in this process until the judge, and closes it there. A judge in another +process, a read that fails, or a target the held read can't find stops the +run as not checked. Never a pass. + +A target that existed may have been written by at most one transaction, and +one that changed by exactly one: two writers mean another user's save sits +inside the window. That is the lost-update rule of ``versions.py`` (one step +per save) with the row's own transaction ids as the steps. + +Known limit: a lock shared by two transactions sets ``xmax`` to a multixact +id, a separate counter. If that number happened to equal the later writer's +transaction id, two writers would read as one. Nothing here can tell the two +counters apart without the ``pageinspect`` extension. +""" + +from __future__ import annotations + +import re +import threading +import time +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Callable, Optional + +from pydantic import BaseModel, ConfigDict, Field, model_serializer + +from openadapt_flow.runtime.effects.versions import VersionVerdict + +#: Where the baseline says whether the held read was opened (no values). +DETAIL = "openadapt:frame_row_versions" + +_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_$]*$") + + +class FrameRowVersions(BaseModel): + """``frame.row_versions``: the target table whose row versions are held.""" + + model_config = ConfigDict(extra="forbid") + + #: Only PostgreSQL keeps the replaced version visible to an old snapshot. + source: str = Field(default="postgresql_xmin", pattern="^postgresql_xmin$") + #: The target's table, ``table`` or ``schema.table`` (plain identifiers). + table: str = Field(min_length=1) + #: The table's key column, whose value is the target record's + #: ``target_field``. + key_column: str = Field(default="id", min_length=1) + #: The target record's field holding the key. Unset: + #: ``frame.identity_field``, else ``id``. + target_field: Optional[str] = None + #: Only records matched on this surface are targets. Unset: every record + #: a confirmed write effect matched. + target_surface: Optional[str] = None + + @model_serializer(mode="wrap") + def _compact(self, handler: Any) -> dict[str, Any]: + data: dict[str, Any] = handler(self) + for key in ("target_field", "target_surface"): + if data.get(key) is None: + data.pop(key, None) + return data + + def names(self) -> tuple[Optional[str], str, str]: + """(schema or None, table, key column), each a plain identifier.""" + + parts = self.table.split(".") + if len(parts) > 2 or not all(_NAME.match(p) for p in parts): + raise ValueError( + f"frame.row_versions.table {self.table!r} is not a plain " + "table or schema.table name" + ) + if not _NAME.match(self.key_column): + raise ValueError( + f"frame.row_versions.key_column {self.key_column!r} is not a " + "plain column name" + ) + schema = parts[0] if len(parts) == 2 else None + return schema, parts[-1], self.key_column + + +def _quote(name: str) -> str: + return '"' + name.replace('"', '""') + '"' + + +def _query(spec: FrameRowVersions) -> str: + schema, table, key = spec.names() + relation = (_quote(schema) + "." if schema else "") + _quote(table) + return ( + f"SELECT CAST({_quote(key)} AS TEXT), CAST(xmin AS TEXT), " + f"CAST(xmax AS TEXT) FROM {relation} " + f"WHERE CAST({_quote(key)} AS TEXT) = ANY(%s)" + ) + + +def _relkind_query(spec: FrameRowVersions) -> tuple[str, tuple[str, ...]]: + schema, table, _key = spec.names() + if schema is None: + return ( + "SELECT c.relkind FROM pg_class c WHERE c.oid = to_regclass(%s)", + (_quote(table),), + ) + return ( + "SELECT c.relkind FROM pg_class c WHERE c.oid = to_regclass(%s)", + (_quote(schema) + "." + _quote(table),), + ) + + +@dataclass +class HeldRead: + """An open read-only REPEATABLE READ transaction from the baseline.""" + + conn: Any + opened: float + + def rows(self, spec: FrameRowVersions, keys: Sequence[str]) -> dict[str, tuple]: + cur = self.conn.cursor() + cur.execute(_query(spec), (list(keys),)) + return {str(k): (x, m) for k, x, m in cur.fetchall()} + + def close(self) -> None: + try: + self.conn.cursor().execute("ROLLBACK") + except Exception: # noqa: BLE001 - closing changes nothing + pass + try: + self.conn.close() + except Exception: # noqa: BLE001 + pass + + +_LOCK = threading.Lock() +_HELD: dict[str, HeldRead] = {} +#: A held read older than this is closed when the next one opens (seconds). +MAX_HOLD_S = 3600.0 + + +def open_held(spec: FrameRowVersions, connect: Callable[[], Any]) -> HeldRead: + """Open the held read and take its snapshot now. Raises on any failure + (the caller records the baseline as not held).""" + + conn = connect() + try: + if type(conn).__module__.split(".")[0] not in ("psycopg2", "psycopg"): + raise ValueError("frame.row_versions reads PostgreSQL only") + # Autocommit off would start its own transaction at the first + # statement, at the default isolation; begin one explicitly instead. + conn.autocommit = True + cur = conn.cursor() + # The server ends a hold the judge never closes. + cur.execute( + "SET idle_in_transaction_session_timeout = %s", (f"{int(MAX_HOLD_S)}s",) + ) + cur.execute("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY") + cur.execute( + "SELECT current_setting('transaction_isolation'), " + "current_setting('transaction_read_only')" + ) + if tuple(cur.fetchone() or ()) != ("repeatable read", "on"): + raise ValueError("the held read is not a read-only snapshot") + sql, args = _relkind_query(spec) + cur.execute(sql, args) + kind = cur.fetchone() + # An ordinary or partitioned table keeps row versions; a view doesn't. + if kind is None or str(kind[0]) not in ("r", "p"): + raise ValueError("frame.row_versions.table is not a table") + except Exception: + try: + conn.close() + except Exception: # noqa: BLE001 + pass + raise + return HeldRead(conn, time.monotonic()) + + +def hold(token: str, held: HeldRead) -> None: + now = time.monotonic() + with _LOCK: + for key in [k for k, h in _HELD.items() if now - h.opened > MAX_HOLD_S]: + _HELD.pop(key).close() + old = _HELD.pop(token, None) + _HELD[token] = held + if old is not None: + old.close() + + +def take(token: str) -> Optional[HeldRead]: + with _LOCK: + return _HELD.pop(token, None) + + +def judge_row_versions( + spec: FrameRowVersions, + held: Optional[HeldRead], + connect: Callable[[], Any], + targets: Sequence[tuple[Optional[str], bool, bool]], +) -> VersionVerdict: + """Count the writers of every target that existed. ``targets``: per + record a confirmed write effect matched, its key (None when it has + none), whether it existed before the write, and whether it changed.""" + + if held is None: + return VersionVerdict( + "not_checked", + "unreadable", + reason="the row versions held from the baseline are not open in " + "this process, so who saved the target can't be told", + ) + try: + keys = sorted({t for t, existed, _c in targets if existed and t is not None}) + old = held.rows(spec, keys) if keys else {} + conn = connect() + try: + cur = conn.cursor() + cur.execute(_query(spec), (keys,)) + now = {str(k): (x, m) for k, x, m in cur.fetchall()} + conn.rollback() + finally: + conn.close() + except Exception: # noqa: BLE001 - unreadable -> the check stops the run + return VersionVerdict( + "not_checked", + "unreadable", + reason="the target's row versions could not be read", + ) + finally: + held.close() + out = VersionVerdict("held") + worst: Optional[VersionVerdict] = None + + def stop(status: str, problem: str, reason: str) -> None: + nonlocal worst + if worst is None or (worst.status == "not_checked" and status == "refuted"): + worst = VersionVerdict(status, problem, reason=reason) # type: ignore[arg-type] + + seen: set[Optional[str]] = set() + for target, existed, changed in targets: + if target in seen or not existed: + continue # created in the window: no earlier version to overwrite + seen.add(target) + if target is None: + stop( + "not_checked", + "no_target_id", + "a target record has no key field, so its row can't be found", + ) + continue + out.targets += 1 + base, cur = old.get(target), now.get(target) + if base is None or cur is None: + stop( + "not_checked", + "missing", + "the target existed but its row isn't in the table " + "frame.row_versions names, before or after the write", + ) + continue + (base_xmin, base_xmax), (cur_xmin, _cur_xmax) = base, cur + if cur_xmin == base_xmin: + writers = 0 + elif base_xmax not in (None, "0") and base_xmax == cur_xmin: + writers = 1 + else: + writers = 2 + out.new_versions += min(writers, 2) + if writers >= 2: + stop( + "refuted", + "extra_steps", + "lost update: two or more transactions wrote the target inside " + "the window; one save is the agent's, and nothing says whose " + "the others are", + ) + elif changed and writers == 0: + stop( + "not_checked", + "no_new_version", + "the target changed in the window but its row version didn't, " + "so who saved it can't be told", + ) + if worst is not None: + worst.targets, worst.new_versions = out.targets, out.new_versions + return worst + out.reason = f"{out.targets} target(s): at most one save each in the window" + return out + + +def baseline_detail(held: Optional[HeldRead], error: Optional[str]) -> dict[str, Any]: + return {"held": held is not None, "error": error} + + +def stored_held(detail: Optional[Mapping[str, Any]]) -> bool: + return isinstance(detail, Mapping) and detail.get("held") is True diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index cabfb87834..68d5f4ac8e 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -660,7 +660,72 @@ def _judge_versions( spec = cfg.frame.versions if cfg.frame is not None else None if spec is None: return frame - field_name = spec.target_field or cfg.frame.identity_field or "id" # type: ignore[union-attr] + targets = _version_targets( + cfg, before, effects, verdicts, spec.target_field, spec.target_surface + ) + stored = (before.detail or {}).get(FRAME_VERSIONS_DETAIL) + if spec.target_surface is not None and not _surface_has_target( + effects, spec.target_surface + ): + # A surface no write target is read from (a typo in a hand-written + # contract, or a surface only a guard reads) would leave no target, + # and no target holds. + result = VersionVerdict( + "not_checked", + "unknown_surface", + reason="frame.versions.target_surface names a surface no write " + "target is read from, so no target's versions can be judged", + ) + else: + result = judge_versions( + spec, + stored if isinstance(stored, Mapping) else {}, + _read_versions(cfg, params), + targets, + _mac_key(salt), + params, + ) + frame.versions = result + return _apply_version_result(frame, result) + + +def _apply_version_result(frame: FrameVerdict, result: Any) -> FrameVerdict: + if result.status == "refuted": + frame.status = "refuted" + frame.reason = result.reason + elif result.status == "not_checked" and frame.status == "held": + frame.status = "not_checked" + frame.reason = result.reason + return frame + + +def _writes_a_target(effect: Effect) -> bool: + """A write effect whose records can be targets. A guard ("nothing + here", ``record_written`` with ``expected_count`` 0) never is.""" + + if effect.kind not in (EffectKind.RECORD_WRITTEN, EffectKind.FIELD_EQUALS): + return False + return not (effect.kind is EffectKind.RECORD_WRITTEN and effect.expected_count == 0) + + +def _surface_has_target(effects: Sequence[Effect], surface: str) -> bool: + from openadapt_flow.runtime.effects.surfaces import surface_of + + return any(_writes_a_target(e) and surface_of(e) == surface for e in effects) + + +def _version_targets( + cfg: VerifyConfig, + before: EffectState, + effects: Sequence[Effect], + verdicts: Sequence[EffectVerdict], + target_field: Optional[str], + target_surface: Optional[str], +) -> list[tuple[Optional[str], bool, bool]]: + """Per record a confirmed write effect matched: its ``target_field`` + value, whether it existed before the write, and whether it changed.""" + + field_name = target_field or cfg.frame.identity_field or "id" # type: ignore[union-attr] # Whether a target existed is told by its identity, which a save doesn't # change, never by the target field's value after the write: a target # field the write changed would make an old record look created. @@ -688,27 +753,14 @@ def before_rows(effect: Effect) -> Optional[dict[str, dict[str, Any]]]: return index(rows) if isinstance(rows, list) else None return index(before.records) if before.reachable else None - def writes_a_target(effect: Effect) -> bool: - """A write effect whose records can be targets. A guard ("nothing - here", ``record_written`` with ``expected_count`` 0) never is.""" - - if effect.kind not in (EffectKind.RECORD_WRITTEN, EffectKind.FIELD_EQUALS): - return False - return not ( - effect.kind is EffectKind.RECORD_WRITTEN and effect.expected_count == 0 - ) - ignored = set(cfg.frame.ignore_fields) # type: ignore[union-attr] targets: list[tuple[Optional[str], bool, bool]] = [] for effect, verdict in zip(effects, verdicts): - if not writes_a_target(effect): + if not _writes_a_target(effect): continue if not verdict.confirmed: continue - if ( - spec.target_surface is not None - and surface_of(effect) != spec.target_surface - ): + if target_surface is not None and surface_of(effect) != target_surface: continue # a row beside the target, not the target old = before_rows(effect) for record in verdict.matched_records: @@ -726,36 +778,66 @@ def writes_a_target(effect: Effect) -> bool: or any(record.get(k) != v for k, v in was.items() if k not in ignored) ) targets.append((text, existed, changed)) - stored = (before.detail or {}).get(FRAME_VERSIONS_DETAIL) - if spec.target_surface is not None and not any( - writes_a_target(e) and surface_of(e) == spec.target_surface for e in effects + return targets + + +def _hold_row_versions(cfg: VerifyConfig, execution_id: str) -> dict[str, Any]: + """Open ``frame.row_versions``' held read before the baseline records.""" + + from openadapt_flow.runtime.effects import row_versions as rv + + spec = cfg.frame.row_versions # type: ignore[union-attr] + try: + held = rv.open_held(spec, _db_connect(cfg.frame.database.read)) # type: ignore[union-attr,arg-type] + except Exception as exc: # noqa: BLE001 - not held -> the judge stops + return rv.baseline_detail(None, type(exc).__name__) + rv.hold(execution_id, held) + return rv.baseline_detail(held, None) + + +def _judge_row_versions( + cfg: VerifyConfig, + frame: FrameVerdict, + before: EffectState, + effects: Sequence[Effect], + verdicts: Sequence[EffectVerdict], + execution_id: str, +) -> FrameVerdict: + """Add ``frame.row_versions``: two writers of a target in the window + refute the frame; a read that can't count them leaves it not checked.""" + + from openadapt_flow.runtime.effects import row_versions as rv + from openadapt_flow.runtime.effects.versions import VersionVerdict + + spec = cfg.frame.row_versions if cfg.frame is not None else None + if spec is None: + return frame + held = rv.take(execution_id) + if not rv.stored_held((before.detail or {}).get(rv.DETAIL)): + if held is not None: + held.close() + held = None + if spec.target_surface is not None and not _surface_has_target( + effects, spec.target_surface ): - # A surface no write target is read from (a typo in a hand-written - # contract, or a surface only a guard reads) would leave no target, - # and no target holds. + if held is not None: + held.close() result = VersionVerdict( "not_checked", "unknown_surface", - reason="frame.versions.target_surface names a surface no write " - "target is read from, so no target's versions can be judged", + reason="frame.row_versions.target_surface names a surface no " + "write target is read from", ) else: - result = judge_versions( - spec, - stored if isinstance(stored, Mapping) else {}, - _read_versions(cfg, params), - targets, - _mac_key(salt), - params, + targets = _version_targets( + cfg, before, effects, verdicts, spec.target_field, spec.target_surface ) - frame.versions = result - if result.status == "refuted": - frame.status = "refuted" - frame.reason = result.reason - elif result.status == "not_checked" and frame.status == "held": - frame.status = "not_checked" - frame.reason = result.reason - return frame + result = rv.judge_row_versions( + spec, held, _db_connect(cfg.frame.database.read), targets # type: ignore[union-attr,arg-type] + ) + if frame.versions is None or result.status != "held": + frame.versions = result + return _apply_version_result(frame, result) def _db_connect(read: Mapping[str, Any]) -> Any: @@ -2483,6 +2565,11 @@ def capture_baseline( history_before, _history_rows = _read_history(cfg, params, _now(), salt) except Exception as exc: history_error = type(exc).__name__ + row_versions_detail = ( + _hold_row_versions(cfg, execution_id) + if cfg.frame is not None and cfg.frame.row_versions is not None + else None + ) # The versions first: a save between this read and the record read is # then in the record baseline too, never hidden in the versions one. versions_rows = ( @@ -2538,6 +2625,10 @@ def capture_baseline( "reachable": entries is not None, "ids": _audit_ids(entries or [], salt), } + if row_versions_detail is not None: + from openadapt_flow.runtime.effects.row_versions import DETAIL as RV_DETAIL + + detail[RV_DETAIL] = row_versions_detail if cfg.frame is not None and cfg.frame.versions is not None: from openadapt_flow.runtime.effects.versions import seal_versions @@ -3276,6 +3367,9 @@ def verify_run( frame = _judge_versions( cfg, frame, before, bound_effects, verdicts, params, salt ) + frame = _judge_row_versions( + cfg, frame, before, bound_effects, verdicts, execution_id + ) else: frame = FrameVerdict( status="not_checked", diff --git a/packages/flow/tests/test_row_versions.py b/packages/flow/tests/test_row_versions.py new file mode 100644 index 0000000000..509726862d --- /dev/null +++ b/packages/flow/tests/test_row_versions.py @@ -0,0 +1,411 @@ +"""Row versions held from the baseline (``frame.row_versions``). + +On PostgreSQL the verifier holds a read-only snapshot from the baseline and +counts the transactions that wrote each target row in the window. These +tests check that one save passes and that every lost update stops: another +user's save then the agent's stale save (with and without a gap), two +same-value rewrites, an edit and a revert against a found check, and a +target whose held read is gone. They also check that the probe writes the +version source beside an excuse only where it can derive one, and that a +learned bookkeeping excuse no longer hides a lost update. + +The judge's arithmetic runs everywhere on recorded transaction ids; the +round trips need ``OPENADAPT_SNAPSHOT_POSTGRES``. Records are made up. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Optional + +import pytest + +from openadapt_flow import learn_probe +from openadapt_flow.runtime.effects import row_versions as rv +from openadapt_flow.runtime.effects.frame import FrameSpec +from openadapt_flow.verifier import Contract +from tests import test_learned_excuses as _le +from tests.test_learned_excuses import ( + LOGIN, + SEEN, + Engine, + check, + learned_block, +) + +_homes = _le._homes + + +@pytest.fixture +def pg(request: pytest.FixtureRequest, tmp_path: Path) -> Any: + if not _le._PG: + pytest.skip("set OPENADAPT_SNAPSHOT_POSTGRES") + e = _le._postgres() + try: + for statement in e.ddl(): + e.run(statement) + for table in ("app_user", "api_token", "note", "asset"): + e.run( + f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), " + f"(SELECT MAX(id) FROM {table}))" + ) + yield e + finally: + for fn in e.cleanup: + fn() + + +SPEC = {"table": "asset", "key_column": "id"} +_n = [0] + + +def request_bookkeeping(e: Engine, user: str = _le.ACTOR) -> None: + """What the app changes on every request by ``user``: the moves a + read-only probe learns (no added row).""" + + _n[0] += 1 + e.run("UPDATE app_user SET last_login = %s WHERE id = %s", f"r{_n[0]}", int(user)) + e.run( + "UPDATE api_token SET last_seen = %s WHERE user_id = %s", f"r{_n[0]}", int(user) + ) + + +def rename_contract(e: Engine, *, versions: bool = True, found: bool = False) -> dict: + """Rename asset LT-100 (an update), or check it is already named (a + found check), with the bookkeeping on the agent's own rows excused.""" + + doc = _le.asset_contract(e, learned_block(LOGIN, SEEN)) + if versions: + doc["frame"]["row_versions"] = dict(SPEC) + if found: + doc["frame"]["target_fields"] = [] + return doc + + +def rename(e: Engine, name: str, user: str = _le.ACTOR) -> None: + request_bookkeeping(e, user) + e.run("UPDATE asset SET name = %s WHERE tag = 'LT-100'", name) + + +def _outcome(result: Any) -> str: + return result.outcome.value + + +# -- the judge's arithmetic, on recorded transaction ids --------------------------- + + +class _Held: + def __init__(self, rows: dict[str, tuple]) -> None: + self._rows, self.closed = rows, False + + def rows(self, spec: Any, keys: Any) -> dict[str, tuple]: + return {k: v for k, v in self._rows.items() if k in keys} + + def close(self) -> None: + self.closed = True + + +class _Cur: + def __init__(self, rows: list[tuple]) -> None: + self._rows = rows + + def execute(self, *a: Any) -> None: + pass + + def fetchall(self) -> list[tuple]: + return self._rows + + +class _Conn: + def __init__(self, rows: list[tuple]) -> None: + self._rows = rows + + def cursor(self) -> _Cur: + return _Cur(self._rows) + + def rollback(self) -> None: + pass + + def close(self) -> None: + pass + + +def _judge( + old: tuple, now: tuple, *, changed: bool, held: bool = True +) -> rv.VersionVerdict: + spec = rv.FrameRowVersions(**SPEC) + h: Optional[_Held] = _Held({"1": old}) if held else None + result = rv.judge_row_versions( + spec, h, lambda: _Conn([("1", *now)]), [("1", True, changed)] + ) + if h is not None: + assert h.closed + return result + + +def test_judge_counts_writers() -> None: + # Nobody wrote it: xmin unchanged. + assert _judge(("100", "0"), ("100", "0"), changed=False).status == "held" + # One transaction replaced the version the baseline saw. + assert _judge(("100", "105"), ("105", "0"), changed=True).status == "held" + # Two: the old version was replaced by 105, the current one is 107's. + two = _judge(("100", "105"), ("107", "0"), changed=True) + assert (two.status, two.problem) == ("refuted", "extra_steps") + # An edit and a revert leave the content unchanged, still two writers. + assert _judge(("100", "105"), ("107", "0"), changed=False).status == "refuted" + # Changed, yet the row version didn't move: can't say who saved it. + odd = _judge(("100", "0"), ("100", "0"), changed=True) + assert (odd.status, odd.problem) == ("not_checked", "no_new_version") + # A lock left on the old version (xmax) but no save: still nobody. + assert _judge(("100", "103"), ("100", "103"), changed=False).status == "held" + + +def test_judge_stops_without_the_held_read() -> None: + v = _judge(("100", "0"), ("105", "0"), changed=True, held=False) + assert (v.status, v.problem) == ("not_checked", "unreadable") + + +def test_judge_stops_on_a_missing_row() -> None: + spec = rv.FrameRowVersions(**SPEC) + v = rv.judge_row_versions( + spec, _Held({}), lambda: _Conn([("1", "5", "0")]), [("1", True, True)] + ) + assert (v.status, v.problem) == ("not_checked", "missing") + # A record created in the window has no earlier version: not judged. + v = rv.judge_row_versions( + spec, _Held({}), lambda: _Conn([]), [("9", False, False)] + ) + assert v.status == "held" + + +def test_spec_is_postgresql_only_and_plain_names() -> None: + db = {"dialect": "postgresql", "read": {"sql_driver": "psycopg2"}} + FrameSpec.model_validate({"database": db, "row_versions": SPEC}) + with pytest.raises(ValueError, match="PostgreSQL only"): + FrameSpec.model_validate( + { + "database": {"dialect": "mysql", "read": {"sql_driver": "pymysql"}}, + "row_versions": SPEC, + } + ) + with pytest.raises(ValueError, match="PostgreSQL only"): + FrameSpec.model_validate({"row_versions": SPEC}) + with pytest.raises(ValueError, match="plain"): + FrameSpec.model_validate( + {"database": db, "row_versions": {"table": 'asset"; DROP TABLE x; --'}} + ) + # Unset, it is left out, so existing contracts keep their digests. + assert "row_versions" not in FrameSpec.model_validate({"database": db}).model_dump() + + +# -- the probe writes the version source beside the excuse ------------------------ + + +def _generated(dialect: str, query: str, *, read_same: bool = True) -> dict: + read = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "db"}} + other = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "elsewhere"}} + return { + "verifier": { + "kind": "surfaces", + "surfaces": { + "record": {"kind": "sql", **(read if read_same else other), "sql_query": query} + }, + }, + "effects": [ + {"kind": "record_written", "probe": "surface=record|x", "expected_count": 1} + ], + "frame": {"database": {"dialect": dialect, "read": read}}, + } + + +GENERATED = ( + 'SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."name" AS TEXT) AS "name", ' + 'CASE WHEN (SELECT COUNT(*) FROM "part_note" n WHERE n.part_id = t.id) = 0 ' + 'THEN \'1\' ELSE \'0\' END AS "p__notes" FROM "part_part" t' +) + + +def test_detects_the_row_versions_of_a_generated_read() -> None: + got = learn_probe.detect_row_versions(_generated("postgresql", GENERATED)) + assert got == { + "source": "postgresql_xmin", + "table": "part_part", + "key_column": "id", + "target_surface": "record", + } + + +@pytest.mark.parametrize( + "doc", + [ + # MySQL and MariaDB: a marker can't count saves. + _generated("mysql", GENERATED), + # A read over another connection. + _generated("postgresql", GENERATED, read_same=False), + # A join or any shape the detector can't read: no source. + _generated( + "postgresql", + 'SELECT CAST(t."id" AS TEXT) AS "id" FROM "part_part" t JOIN x ON x.id = t.id', + ), + _generated("postgresql", 'SELECT CAST(t."pk" + 1 AS TEXT) AS "id" FROM "p" t'), + ], +) +def test_no_row_versions_where_none_can_be_derived(doc: dict) -> None: + assert learn_probe.detect_row_versions(doc) is None + + +def test_probe_excuse_goes_in_only_with_a_version_source(tmp_path: Path) -> None: + proposal = { + "kinds": {"read_only_probe": {"excuses": [dict(LOGIN)]}}, + "proposal_sha256": "sha256:" + "0" * 64, + } + pg_doc = _generated("postgresql", GENERATED) + my_doc = _generated("mysql", GENERATED) + import yaml + + paths = [] + for name, doc in (("pg", pg_doc), ("my", my_doc)): + doc["schema_version"] = "openadapt.verify/v1" + doc["effects"][0]["match"] = {"name": {"param": "name"}} + doc["verifier"]["surfaces"]["record"]["sql_password_env"] = "X" + doc["frame"]["database"]["read"]["sql_password_env"] = "X" + p = tmp_path / f"{name}.yaml" + p.write_text(yaml.safe_dump(doc)) + paths.append(p) + written = learn_probe.apply(proposal, paths) + names = {p.stem for p, _n in written} + assert names == {"pg"} + pg_new = yaml.safe_load(paths[0].read_text()) + assert pg_new["frame"]["row_versions"]["table"] == "part_part" + assert "learned" not in (yaml.safe_load(paths[1].read_text())["frame"] or {}) + Contract.from_dict(pg_new, name="pg") + + +# -- round trips on PostgreSQL --------------------------------------------------- + + +def test_one_save_passes(pg: Engine, tmp_path: Path) -> None: + r = check( + pg, + rename_contract(pg), + {"tag": "LT-100", "name": "Laptop B"}, + lambda: rename(pg, "Laptop B"), + tmp_path, + ) + assert _outcome(r) == "CONFIRMED", r.reasons + + +def test_bookkeeping_excuse_alone_hides_a_lost_update( + pg: Engine, tmp_path: Path +) -> None: + """Why #2413 holds these contracts back: excused bookkeeping, no + version source, and a colleague's edit the stale save reverts.""" + + def act() -> None: + pg.run("UPDATE asset SET assigned_to = 3 WHERE tag = 'LT-100'") + rename(pg, "Laptop B") + pg.run("UPDATE asset SET assigned_to = NULL WHERE tag = 'LT-100'") + + r = check( + pg, + rename_contract(pg, versions=False), + {"tag": "LT-100", "name": "Laptop B"}, + act, + tmp_path, + ) + assert _outcome(r) == "CONFIRMED", r.reasons + + +@pytest.mark.parametrize("gap", [False, True]) +def test_lost_update_stops(pg: Engine, tmp_path: Path, gap: bool) -> None: + """A colleague's save, then the agent's stale full save over it.""" + + def act() -> None: + pg.run("UPDATE asset SET assigned_to = 3 WHERE tag = 'LT-100'") + if gap: + import time + + time.sleep(1.0) + request_bookkeeping(pg) + pg.run( + "UPDATE asset SET name = 'Laptop B', assigned_to = NULL WHERE tag = 'LT-100'" + ) + + r = check( + pg, + rename_contract(pg), + {"tag": "LT-100", "name": "Laptop B"}, + act, + tmp_path, + ) + assert _outcome(r) == "REFUTED", r.reasons + assert r.evidence["frame"]["versions"]["problem"] == "extra_steps" + + +def test_same_value_rewrite_twice_stops(pg: Engine, tmp_path: Path) -> None: + def act() -> None: + rename(pg, "Laptop B") + pg.run("UPDATE asset SET name = 'Laptop B' WHERE tag = 'LT-100'") + + r = check( + pg, + rename_contract(pg), + {"tag": "LT-100", "name": "Laptop B"}, + act, + tmp_path, + ) + assert _outcome(r) == "REFUTED", r.reasons + + +def test_found_check(pg: Engine, tmp_path: Path) -> None: + params = {"tag": "LT-100", "name": "Laptop A"} + ok = check( + pg, + rename_contract(pg, found=True), + params, + lambda: request_bookkeeping(pg), + tmp_path, + ) + assert _outcome(ok) == "CONFIRMED", ok.reasons + + def edit_and_revert() -> None: + # A colleague edits the record; the agent's stale save puts it back. + pg.run("UPDATE asset SET assigned_to = 3 WHERE tag = 'LT-100'") + request_bookkeeping(pg) + pg.run("UPDATE asset SET assigned_to = NULL WHERE tag = 'LT-100'") + + bad = check(pg, rename_contract(pg, found=True), params, edit_and_revert, tmp_path) + assert _outcome(bad) == "REFUTED", bad.reasons + + +def test_judge_without_the_held_read_stops( + pg: Engine, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A judge in another process finds no held read: never a pass.""" + + monkeypatch.setattr(rv, "take", lambda token: None) + r = check( + pg, + rename_contract(pg), + {"tag": "LT-100", "name": "Laptop B"}, + lambda: rename(pg, "Laptop B"), + tmp_path, + ) + assert _outcome(r) != "CONFIRMED" + assert r.evidence["frame"]["versions"]["problem"] == "unreadable" + + +def test_held_read_is_a_read_only_snapshot(pg: Engine) -> None: + from openadapt_flow.verify_run import _db_connect + + held = rv.open_held(rv.FrameRowVersions(**SPEC), _db_connect(pg.read)) + try: + cur = held.conn.cursor() + with pytest.raises(Exception, match="read-only"): + cur.execute("UPDATE asset SET name = 'x'") + finally: + held.close() + with pytest.raises(Exception): + rv.open_held( + rv.FrameRowVersions(table="no_such_table"), _db_connect(pg.read) + ) From 8fb9a79307f5d67144609cf1a5aa62637c1951d2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 04:02:55 -0500 Subject: [PATCH 04/14] fix(flow): row versions: a shared-lock xmax is not one writer; probe needs a one-table read --- packages/flow/openadapt_flow/learn_probe.py | 7 +- .../runtime/effects/row_versions.py | 51 +++++++++++-- .../runtime/effects/versions.py | 1 + packages/flow/openadapt_flow/verifier.py | 2 + packages/flow/tests/test_row_versions.py | 72 +++++++++++++++---- 5 files changed, 113 insertions(+), 20 deletions(-) diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 61ac690d7d..87aca3b8e5 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -337,7 +337,7 @@ def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: alone: on PostgreSQL, the target's own row versions (``frame.row_versions``). Found only when every write effect reads one surface, that surface's read is a plain ``SELECT ... FROM
t`` - over the frame's own connection, and it selects the identity field + with no other ``FROM`` over the frame's own connection, and it selects the identity field straight from one column. Anything else: None (no excuse). A MySQL or MariaDB target has no such source: ``updated_at`` and @@ -373,7 +373,10 @@ def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: return None # another database: its rows aren't the frame's query = " ".join(str(source.get("sql_query") or "").split()) main = _MAIN_FROM.search(query) - if main is None: + # One FROM: the declared record is one row, so the row's versions are + # the record's. A read that also looks into other tables (a list of + # tags, a child row) declares rows this source doesn't count. + if main is None or len(re.findall(r"\bFROM\b", query, re.IGNORECASE)) != 1: return None field = str(frame.get("identity_field") or "id") column = re.search( diff --git a/packages/flow/openadapt_flow/runtime/effects/row_versions.py b/packages/flow/openadapt_flow/runtime/effects/row_versions.py index 0b258aa82e..385721b621 100644 --- a/packages/flow/openadapt_flow/runtime/effects/row_versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/row_versions.py @@ -30,10 +30,14 @@ inside the window. That is the lost-update rule of ``versions.py`` (one step per save) with the row's own transaction ids as the steps. -Known limit: a lock shared by two transactions sets ``xmax`` to a multixact -id, a separate counter. If that number happened to equal the later writer's -transaction id, two writers would read as one. Nothing here can tell the two -counters apart without the ``pageinspect`` extension. +A lock shared by two transactions sets ``xmax`` to a multixact id, a +separate counter. If that number equals the later writer's transaction id, +two writers could read as one; when a multixact with that id exists and +names another updater, the check is not checked rather than held. + +What it doesn't see: a row the window adds and removes again (no snapshot +holds it; the frame's counter check catches it when the key comes from a +sequence), and writes to rows other than the target, which the frame judges. """ from __future__ import annotations @@ -210,6 +214,27 @@ def take(token: str) -> Optional[HeldRead]: return _HELD.pop(token, None) +#: ``pg_get_multixact_members`` modes that update a row (not just lock it). +_UPDATE_MODES = frozenset({"nokeyupd", "upd"}) + + +def _multixact_updater_other_than(cur: Any, value: str, writer: str) -> bool: + """Could ``value``, read as the old version's ``xmax``, be a multixact id + (a shared lock) whose updater is a transaction other than ``writer``? + Then two writers could read as one. A value that is no multixact (the + function errors) can't.""" + + try: + cur.execute( + "SELECT CAST(xid AS TEXT), mode FROM pg_get_multixact_members(CAST(%s AS xid))", + (value,), + ) + members = cur.fetchall() + except Exception: # noqa: BLE001 - not a multixact id: a plain xid + return False + return any(str(m) in _UPDATE_MODES and str(x) != writer for x, m in members) + + def judge_row_versions( spec: FrameRowVersions, held: Optional[HeldRead], @@ -232,10 +257,18 @@ def judge_row_versions( old = held.rows(spec, keys) if keys else {} conn = connect() try: + conn.autocommit = True cur = conn.cursor() cur.execute(_query(spec), (keys,)) now = {str(k): (x, m) for k, x, m in cur.fetchall()} - conn.rollback() + ambiguous = { + k + for k, (base_xmin, base_xmax) in old.items() + if k in now + and now[k][0] != base_xmin + and base_xmax == now[k][0] + and _multixact_updater_other_than(cur, base_xmax, now[k][0]) + } finally: conn.close() except Exception: # noqa: BLE001 - unreadable -> the check stops the run @@ -277,6 +310,14 @@ def stop(status: str, problem: str, reason: str) -> None: ) continue (base_xmin, base_xmax), (cur_xmin, _cur_xmax) = base, cur + if target in ambiguous: + stop( + "not_checked", + "ambiguous_xmax", + "the version the baseline saw was replaced under a shared lock, " + "so one save can't be told from two", + ) + continue if cur_xmin == base_xmin: writers = 0 elif base_xmax not in (None, "0") and base_xmax == cur_xmin: diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py index 3f10ca3026..9c8f25176b 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -59,6 +59,7 @@ "no_new_version", "history_changed", "unknown_surface", + "ambiguous_xmax", ) _WHOLE = re.compile(r"^(0|[1-9][0-9]*)$") diff --git a/packages/flow/openadapt_flow/verifier.py b/packages/flow/openadapt_flow/verifier.py index e3751d4c41..6122252422 100644 --- a/packages/flow/openadapt_flow/verifier.py +++ b/packages/flow/openadapt_flow/verifier.py @@ -2382,6 +2382,8 @@ def _scope( "no_new_version": "the target changed in the window but no new version of it was read", "history_changed": "a version of the target read before the write is gone after it, " "so a save in the window could be hidden", + "ambiguous_xmax": "the target's row was replaced under a shared lock, so one " + "save can't be told from two", } diff --git a/packages/flow/tests/test_row_versions.py b/packages/flow/tests/test_row_versions.py index 509726862d..7382f8eaba 100644 --- a/packages/flow/tests/test_row_versions.py +++ b/packages/flow/tests/test_row_versions.py @@ -36,6 +36,12 @@ _homes = _le._homes +@pytest.fixture(autouse=True) +def _no_leaked_holds() -> Any: + yield + assert not rv._HELD, "a held read was left open" + + @pytest.fixture def pg(request: pytest.FixtureRequest, tmp_path: Path) -> Any: if not _le._PG: @@ -106,22 +112,24 @@ def close(self) -> None: class _Cur: - def __init__(self, rows: list[tuple]) -> None: - self._rows = rows + def __init__(self, rows: list[tuple], members: Optional[list[tuple]]) -> None: + self._rows, self._members, self._sql = rows, members, "" - def execute(self, *a: Any) -> None: - pass + def execute(self, sql: str, *a: Any) -> None: + self._sql = sql + if "multixact" in sql and self._members is None: + raise RuntimeError("MultiXactId has not been created yet") def fetchall(self) -> list[tuple]: - return self._rows + return list(self._members or []) if "multixact" in self._sql else self._rows class _Conn: - def __init__(self, rows: list[tuple]) -> None: - self._rows = rows + def __init__(self, rows: list[tuple], members: Optional[list[tuple]] = None) -> None: + self._rows, self._members, self.autocommit = rows, members, False def cursor(self) -> _Cur: - return _Cur(self._rows) + return _Cur(self._rows, self._members) def rollback(self) -> None: pass @@ -131,12 +139,17 @@ def close(self) -> None: def _judge( - old: tuple, now: tuple, *, changed: bool, held: bool = True + old: tuple, + now: tuple, + *, + changed: bool, + held: bool = True, + members: Optional[list[tuple]] = None, ) -> rv.VersionVerdict: spec = rv.FrameRowVersions(**SPEC) h: Optional[_Held] = _Held({"1": old}) if held else None result = rv.judge_row_versions( - spec, h, lambda: _Conn([("1", *now)]), [("1", True, changed)] + spec, h, lambda: _Conn([("1", *now)], members), [("1", True, changed)] ) if h is not None: assert h.closed @@ -160,6 +173,23 @@ def test_judge_counts_writers() -> None: assert _judge(("100", "103"), ("100", "103"), changed=False).status == "held" +def test_judge_never_reads_a_shared_lock_as_one_writer() -> None: + """The old version's xmax may be a multixact id equal to the current + xmin by chance; if that multixact names another updater, not checked.""" + + v = _judge( + ("100", "105"), ("105", "0"), changed=True, members=[("103", "upd"), ("104", "keysh")] + ) + assert (v.status, v.problem) == ("not_checked", "ambiguous_xmax") + # Lockers only, or the writer itself as the updater: still one writer. + assert _judge( + ("100", "105"), ("105", "0"), changed=True, members=[("104", "keysh")] + ).status == "held" + assert _judge( + ("100", "105"), ("105", "0"), changed=True, members=[("105", "nokeyupd")] + ).status == "held" + + def test_judge_stops_without_the_held_read() -> None: v = _judge(("100", "0"), ("105", "0"), changed=True, held=False) assert (v.status, v.problem) == ("not_checked", "unreadable") @@ -220,8 +250,8 @@ def _generated(dialect: str, query: str, *, read_same: bool = True) -> dict: GENERATED = ( 'SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."name" AS TEXT) AS "name", ' - 'CASE WHEN (SELECT COUNT(*) FROM "part_note" n WHERE n.part_id = t.id) = 0 ' - 'THEN \'1\' ELSE \'0\' END AS "p__notes" FROM "part_part" t' + 'CASE WHEN CAST(t."minimum_stock" AS numeric) = CAST(%(v0)s AS numeric) ' + 'THEN \'1\' ELSE \'0\' END AS "p__minimum_stock" FROM "part_part" t' ) @@ -248,6 +278,14 @@ def test_detects_the_row_versions_of_a_generated_read() -> None: 'SELECT CAST(t."id" AS TEXT) AS "id" FROM "part_part" t JOIN x ON x.id = t.id', ), _generated("postgresql", 'SELECT CAST(t."pk" + 1 AS TEXT) AS "id" FROM "p" t'), + # A read that also counts child rows: those rows have versions of + # their own, which this source doesn't count. + _generated( + "postgresql", + 'SELECT CAST(t."id" AS TEXT) AS "id", CASE WHEN (SELECT COUNT(*) ' + 'FROM "part_tag" g WHERE g.part_id = t.id) = 1 THEN \'1\' ELSE ' + '\'0\' END AS "p__tags" FROM "part_part" t', + ), ], ) def test_no_row_versions_where_none_can_be_derived(doc: dict) -> None: @@ -383,7 +421,15 @@ def test_judge_without_the_held_read_stops( ) -> None: """A judge in another process finds no held read: never a pass.""" - monkeypatch.setattr(rv, "take", lambda token: None) + real_take = rv.take + + def gone(token: str) -> None: + held = real_take(token) # the other process never had it + if held is not None: + held.close() + return None + + monkeypatch.setattr(rv, "take", gone) r = check( pg, rename_contract(pg), From efad0ee6a9fd4b91ca0417e88479513bd376bb87 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 04:20:00 -0500 Subject: [PATCH 05/14] fix(flow): row versions never vouch for a target created in the window; mypy and format --- packages/flow/docs/LEARNED_EXCUSES.md | 21 +++++- packages/flow/openadapt_flow/learn_probe.py | 20 +++--- .../runtime/effects/row_versions.py | 21 ++++-- .../runtime/effects/versions.py | 1 + packages/flow/openadapt_flow/verifier.py | 2 + packages/flow/openadapt_flow/verify_run.py | 8 +-- packages/flow/tests/test_row_versions.py | 64 +++++++++++++------ 7 files changed, 101 insertions(+), 36 deletions(-) diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index f3fa7e3e38..cf965ba7a2 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -223,7 +223,26 @@ 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 +contracts keep stopping unless the probe can give them a version source. + +On PostgreSQL it can, for a contract whose write effects all read one +surface, and whose read is one `SELECT ... FROM
t` (no other +`FROM`) over the frame's own connection with the identity field taken from +one column. The probe then writes `frame.row_versions` (table and key +column) beside the excuse. At check time the verifier opens a read-only +REPEATABLE READ transaction before it reads the baseline and keeps it open +until the judge. That transaction still sees the target row's version from +the baseline, and that version's `xmax` names the transaction that replaced +it. If it equals the current row's `xmin`, one transaction saved the +target. Anything else means two or more did, and the frame is refuted as a +lost update. A judge in another process, a failed read, or a replaced +version whose `xmax` could be a shared lock naming another updater makes the +frame not checked. A last-saved marker (`xmin` alone, `updated_at`, +`ON UPDATE CURRENT_TIMESTAMP`) is not used: it reads the same after one +save as after two. MySQL and MariaDB updates get no automatic source; they +need `frame.versions` over a history table, or the database's change log. + +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 87aca3b8e5..074c709668 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -207,7 +207,8 @@ def propose( 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 = [], [] + kept: list[Any] = [] + held: list[Any] = [] for e in body.get("excuses") or []: (held if e.get("change") == "added" else kept).append(e) for e in held: @@ -346,10 +347,12 @@ def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: database's change log.""" frame = data.get("frame") if isinstance(data, Mapping) else None - database = frame.get("database") if isinstance(frame, Mapping) else None + if not isinstance(frame, Mapping): + return None + database = frame.get("database") if not isinstance(database, Mapping) or database.get("dialect") != "postgresql": return None - surfaces: set[str] = set() + names: set[str] = set() for effect in data.get("effects") or []: if not isinstance(effect, Mapping): return None @@ -360,12 +363,13 @@ def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: probe = str(effect.get("probe") or "") if not probe.startswith("surface="): return None - surfaces.add(probe[len("surface=") :].split("|", 1)[0].strip()) - if len(surfaces) != 1: + names.add(probe[len("surface=") :].split("|", 1)[0].strip()) + if len(names) != 1: return None - (surface,) = surfaces - verifier = data.get("verifier") if isinstance(data, Mapping) else None - source = ((verifier or {}).get("surfaces") or {}).get(surface) + (surface,) = names + verifier = data.get("verifier") + surfaces = verifier.get("surfaces") if isinstance(verifier, Mapping) else None + source = surfaces.get(surface) if isinstance(surfaces, Mapping) else None if not isinstance(source, Mapping) or source.get("kind") != "sql": return None read = database.get("read") or {} diff --git a/packages/flow/openadapt_flow/runtime/effects/row_versions.py b/packages/flow/openadapt_flow/runtime/effects/row_versions.py index 385721b621..68225822ac 100644 --- a/packages/flow/openadapt_flow/runtime/effects/row_versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/row_versions.py @@ -25,8 +25,10 @@ process, a read that fails, or a target the held read can't find stops the run as not checked. Never a pass. -A target that existed may have been written by at most one transaction, and -one that changed by exactly one: two writers mean another user's save sits +Every target must have existed at the baseline: a record created in the +window (a duplicate made instead of the update) has no earlier version, so +it stops the run as not checked. A target may have been written by at most +one transaction, and one that changed by exactly one: two writers mean another user's save sits inside the window. That is the lost-update rule of ``versions.py`` (one step per save) with the row's own transaction ids as the steps. @@ -289,9 +291,20 @@ def stop(status: str, problem: str, reason: str) -> None: seen: set[Optional[str]] = set() for target, existed, changed in targets: - if target in seen or not existed: - continue # created in the window: no earlier version to overwrite + if target in seen: + continue seen.add(target) + if not existed: + # An update or a found check names a record that was there. One + # created in the window (a duplicate made instead of the update) + # has no earlier version, so this source can't vouch for it. + stop( + "not_checked", + "created_target", + "the record an update or found check names was created in the " + "window, not saved over", + ) + continue if target is None: stop( "not_checked", diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py index 9c8f25176b..cf2732fb94 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -60,6 +60,7 @@ "history_changed", "unknown_surface", "ambiguous_xmax", + "created_target", ) _WHOLE = re.compile(r"^(0|[1-9][0-9]*)$") diff --git a/packages/flow/openadapt_flow/verifier.py b/packages/flow/openadapt_flow/verifier.py index 6122252422..c5664bea58 100644 --- a/packages/flow/openadapt_flow/verifier.py +++ b/packages/flow/openadapt_flow/verifier.py @@ -2384,6 +2384,8 @@ def _scope( "so a save in the window could be hidden", "ambiguous_xmax": "the target's row was replaced under a shared lock, so one " "save can't be told from two", + "created_target": "the record an update or found check names was created in " + "the window, not saved over", } diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 68d5f4ac8e..af53293db8 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -788,7 +788,8 @@ def _hold_row_versions(cfg: VerifyConfig, execution_id: str) -> dict[str, Any]: spec = cfg.frame.row_versions # type: ignore[union-attr] try: - held = rv.open_held(spec, _db_connect(cfg.frame.database.read)) # type: ignore[union-attr,arg-type] + read = cfg.frame.database.read # type: ignore[union-attr] + held = rv.open_held(spec, _db_connect(read)) # type: ignore[arg-type] except Exception as exc: # noqa: BLE001 - not held -> the judge stops return rv.baseline_detail(None, type(exc).__name__) rv.hold(execution_id, held) @@ -832,9 +833,8 @@ def _judge_row_versions( targets = _version_targets( cfg, before, effects, verdicts, spec.target_field, spec.target_surface ) - result = rv.judge_row_versions( - spec, held, _db_connect(cfg.frame.database.read), targets # type: ignore[union-attr,arg-type] - ) + read = cfg.frame.database.read # type: ignore[union-attr] + result = rv.judge_row_versions(spec, held, _db_connect(read), targets) if frame.versions is None or result.status != "held": frame.versions = result return _apply_version_result(frame, result) diff --git a/packages/flow/tests/test_row_versions.py b/packages/flow/tests/test_row_versions.py index 7382f8eaba..f8cd65de4f 100644 --- a/packages/flow/tests/test_row_versions.py +++ b/packages/flow/tests/test_row_versions.py @@ -125,7 +125,9 @@ def fetchall(self) -> list[tuple]: class _Conn: - def __init__(self, rows: list[tuple], members: Optional[list[tuple]] = None) -> None: + def __init__( + self, rows: list[tuple], members: Optional[list[tuple]] = None + ) -> None: self._rows, self._members, self.autocommit = rows, members, False def cursor(self) -> _Cur: @@ -178,16 +180,25 @@ def test_judge_never_reads_a_shared_lock_as_one_writer() -> None: xmin by chance; if that multixact names another updater, not checked.""" v = _judge( - ("100", "105"), ("105", "0"), changed=True, members=[("103", "upd"), ("104", "keysh")] + ("100", "105"), + ("105", "0"), + changed=True, + members=[("103", "upd"), ("104", "keysh")], ) assert (v.status, v.problem) == ("not_checked", "ambiguous_xmax") # Lockers only, or the writer itself as the updater: still one writer. - assert _judge( - ("100", "105"), ("105", "0"), changed=True, members=[("104", "keysh")] - ).status == "held" - assert _judge( - ("100", "105"), ("105", "0"), changed=True, members=[("105", "nokeyupd")] - ).status == "held" + assert ( + _judge( + ("100", "105"), ("105", "0"), changed=True, members=[("104", "keysh")] + ).status + == "held" + ) + assert ( + _judge( + ("100", "105"), ("105", "0"), changed=True, members=[("105", "nokeyupd")] + ).status + == "held" + ) def test_judge_stops_without_the_held_read() -> None: @@ -201,11 +212,10 @@ def test_judge_stops_on_a_missing_row() -> None: spec, _Held({}), lambda: _Conn([("1", "5", "0")]), [("1", True, True)] ) assert (v.status, v.problem) == ("not_checked", "missing") - # A record created in the window has no earlier version: not judged. - v = rv.judge_row_versions( - spec, _Held({}), lambda: _Conn([]), [("9", False, False)] - ) - assert v.status == "held" + # A record created in the window (a duplicate made instead of the + # update) has no earlier version: never held. + v = rv.judge_row_versions(spec, _Held({}), lambda: _Conn([]), [("9", False, False)]) + assert (v.status, v.problem) == ("not_checked", "created_target") def test_spec_is_postgresql_only_and_plain_names() -> None: @@ -238,7 +248,11 @@ def _generated(dialect: str, query: str, *, read_same: bool = True) -> dict: "verifier": { "kind": "surfaces", "surfaces": { - "record": {"kind": "sql", **(read if read_same else other), "sql_query": query} + "record": { + "kind": "sql", + **(read if read_same else other), + "sql_query": query, + } }, }, "effects": [ @@ -251,7 +265,7 @@ def _generated(dialect: str, query: str, *, read_same: bool = True) -> dict: GENERATED = ( 'SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."name" AS TEXT) AS "name", ' 'CASE WHEN CAST(t."minimum_stock" AS numeric) = CAST(%(v0)s AS numeric) ' - 'THEN \'1\' ELSE \'0\' END AS "p__minimum_stock" FROM "part_part" t' + "THEN '1' ELSE '0' END AS \"p__minimum_stock\" FROM \"part_part\" t" ) @@ -283,7 +297,7 @@ def test_detects_the_row_versions_of_a_generated_read() -> None: _generated( "postgresql", 'SELECT CAST(t."id" AS TEXT) AS "id", CASE WHEN (SELECT COUNT(*) ' - 'FROM "part_tag" g WHERE g.part_id = t.id) = 1 THEN \'1\' ELSE ' + "FROM \"part_tag\" g WHERE g.part_id = t.id) = 1 THEN '1' ELSE " '\'0\' END AS "p__tags" FROM "part_part" t', ), ], @@ -380,6 +394,20 @@ def act() -> None: assert r.evidence["frame"]["versions"]["problem"] == "extra_steps" +def test_duplicate_instead_of_update_stops(pg: Engine, tmp_path: Path) -> None: + """The agent adds a second record with the asked values instead of + saving the existing one; the effect matches the new record.""" + + def act() -> None: + request_bookkeeping(pg) + pg.run("INSERT INTO asset (tag, name) VALUES ('LT-100', 'Laptop B')") + + doc = rename_contract(pg) + doc["frame"]["target_fields"] = ["name", "tag"] + r = check(pg, doc, {"tag": "LT-100", "name": "Laptop B"}, act, tmp_path) + assert _outcome(r) != "CONFIRMED", r.reasons + + def test_same_value_rewrite_twice_stops(pg: Engine, tmp_path: Path) -> None: def act() -> None: rename(pg, "Laptop B") @@ -452,6 +480,4 @@ def test_held_read_is_a_read_only_snapshot(pg: Engine) -> None: finally: held.close() with pytest.raises(Exception): - rv.open_held( - rv.FrameRowVersions(table="no_such_table"), _db_connect(pg.read) - ) + rv.open_held(rv.FrameRowVersions(table="no_such_table"), _db_connect(pg.read)) From 165a094f91a2d2b69d8f5ccf3dda06b07d9edd1d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:27:20 -0500 Subject: [PATCH 06/14] docs: capability row for row versions; refresh llms-full --- CAPABILITIES.md | 1 + llms-full.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 379543a346..609e6e8b8a 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) | +| Count who saved an update's target on PostgreSQL, so learned bookkeeping can be excused on updates and found checks too: `frame.row_versions` holds a read-only REPEATABLE READ snapshot from the baseline to the judge; the replaced row version's `xmax` against the current row's `xmin` says whether one transaction or more wrote the target. Two or more refute the frame as a lost update; a judge in another process, a failed read, a target created in the window, or an `xmax` that could be a shared lock naming another updater stop it as not checked. `learn probe --apply` writes the source beside the excuse when the contract's read is one table. Not yet: MySQL and MariaDB targets (a last-saved marker can't count saves; they need a history read or the change log), rows a window adds and removes on a composite key | (this PR) | Real app replay (InvenTree on PostgreSQL, first-contact retest, frozen vs fix vs this branch on identical writes): correct writes stopped 65, 48 and 27 of 65; the 21 released were all bookkeeping stops on updates and found checks, and none newly stopped; 0 of 31 planted and agent harms passed in any variant, and the row-version check itself refuted the planted lost updates (the pack's 2 plus a no-gap PATCH, a no-gap PUT, a found-check revert and a child-row revert); 9 of 9 excuse attacks stopped. No change on MariaDB apps (no source is derived) | `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 32d454bc26..d793ffbb70 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) | +| Count who saved an update's target on PostgreSQL, so learned bookkeeping can be excused on updates and found checks too: `frame.row_versions` holds a read-only REPEATABLE READ snapshot from the baseline to the judge; the replaced row version's `xmax` against the current row's `xmin` says whether one transaction or more wrote the target. Two or more refute the frame as a lost update; a judge in another process, a failed read, a target created in the window, or an `xmax` that could be a shared lock naming another updater stop it as not checked. `learn probe --apply` writes the source beside the excuse when the contract's read is one table. Not yet: MySQL and MariaDB targets (a last-saved marker can't count saves; they need a history read or the change log), rows a window adds and removes on a composite key | (this PR) | Real app replay (InvenTree on PostgreSQL, first-contact retest, frozen vs fix vs this branch on identical writes): correct writes stopped 65, 48 and 27 of 65; the 21 released were all bookkeeping stops on updates and found checks, and none newly stopped; 0 of 31 planted and agent harms passed in any variant, and the row-version check itself refuted the planted lost updates (the pack's 2 plus a no-gap PATCH, a no-gap PUT, a found-check revert and a child-row revert); 9 of 9 excuse attacks stopped. No change on MariaDB apps (no source is derived) | `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) | From f1d7a65833b626b169fcb16ecefa895c643340d0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:54:05 -0500 Subject: [PATCH 07/14] fix(flow): a probe excuses only a move every round shows; no excuse beside an update the versions don't cover Review blockers on #2413: - A move must show in every read-only round (at least two), so a one-off edit to the acting user's own row during one round is not excused. - _sees_its_own_harm judged only record_written effects. Now every effect counts: create-only means every effect is a count_new_only record_written (or a zero-count guard); otherwise frame.versions must cover each other effect on its target_surface. - Annotate the kept/held lists (mypy). - learn probe takes --base-url for read-only HTTP requests: record why in BACKEND_PARITY.md's URL flags table. - Rename learn_probe.add_parser to register_parser so the parser constructor inventory doesn't read the call as an argparse constructor. --- packages/flow/docs/BACKEND_PARITY.md | 1 + packages/flow/openadapt_flow/learn.py | 2 +- packages/flow/openadapt_flow/learn_probe.py | 80 +++++++++++++++------ packages/flow/tests/test_learn_probe.py | 72 ++++++++++++++++++- 4 files changed, 131 insertions(+), 24 deletions(-) diff --git a/packages/flow/docs/BACKEND_PARITY.md b/packages/flow/docs/BACKEND_PARITY.md index f82f749236..d43679092f 100644 --- a/packages/flow/docs/BACKEND_PARITY.md +++ b/packages/flow/docs/BACKEND_PARITY.md @@ -343,6 +343,7 @@ and `--log-url`, the transparency log) are not app URLs. | `openadapt-flow validate-hosted` | `--target-url` | The surface comes from the signed run report. A non-web report refuses a target URL ("Target URL is web-only and must be omitted"). | | `openadapt-agent authoring connect` | `--url` | `--url` opens a fresh browser. Without it the command pins the local app window (one macOS or Linux window). Windows, RDP and Citrix are coach-only on the mailbox: the person drives and Capture records (`COACH_ONLY_BACKENDS` in `agent/mailbox.py`). | | `openadapt-agent seal keys pin` | `--url` | The seal key server's address, not an app. | +| `openadapt-flow learn probe` | `--base-url` | The probe sends read-only HTTP requests (`GET`, `HEAD`) to the app's API as the agent; it drives no UI, so there is no backend to choose. The frame it reads comes from the contract's `frame.database`. | diff --git a/packages/flow/openadapt_flow/learn.py b/packages/flow/openadapt_flow/learn.py index 0fee10dbac..eb11a04cf6 100644 --- a/packages/flow/openadapt_flow/learn.py +++ b/packages/flow/openadapt_flow/learn.py @@ -950,7 +950,7 @@ def build_parser(p: argparse.ArgumentParser) -> argparse.ArgumentParser: from openadapt_flow import learn_probe - learn_probe.add_parser(steps) + learn_probe.register_parser(steps) return p diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index b984ae9c2e..8d55ecf303 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -50,6 +50,10 @@ #: The ``frame.learned.approved_by`` of a probe's excuses. PROBE_APPROVER = "read-only probe (openadapt-flow learn probe)" DEFAULT_ROUNDS = 3 +#: A move is excused only when every one of at least this many rounds shows +#: it: per-request bookkeeping moves on every request, while a one-off edit +#: (a person changing the acting user's own row during a round) does not. +MIN_ROUNDS = 2 class ProbeError(_learn.LearnError): @@ -117,8 +121,8 @@ def probe( from openadapt_flow.verifier import Actor, begin_write, verify_write - if rounds < 1: - raise ProbeError("a probe runs at least one round") + if rounds < MIN_ROUNDS: + raise ProbeError(f"a probe runs at least {MIN_ROUNDS} rounds") config = getattr(contract, "config", None) frame = getattr(config, "frame", None) if frame is None or getattr(frame, "database", None) is None: @@ -191,9 +195,10 @@ def users_for_actor_params(manifest_path: Path, schema: Any) -> Optional[_learn. 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. + """The learner's proposal from probe episodes: a ``changed`` move must + show in every read-only round (at least :data:`MIN_ROUNDS`), so a + one-off edit to the acting user's own row during one round is not + excused. The relation to the acting user then 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 @@ -204,9 +209,19 @@ def propose( 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") + proposal = _learn.propose(eps, users=users, k=n, n=n, source="read-only probe") + # A round that showed no usable move (nothing moved, or no frame) means + # the move isn't per-request bookkeeping; too few rounds can't tell. + every_round = len(learnable) >= MIN_ROUNDS and len(learnable) == len(eps) for body in (proposal.get("kinds") or {}).values(): - kept, held = [], [] + if not every_round: + body["excuses"] = [] + body["not_learned"] = ( + f"a move is excused only when all of at least {MIN_ROUNDS} " + f"read-only rounds show it ({len(learnable)} of {len(eps)} did)" + ) + kept: list[dict[str, Any]] = [] + held: list[dict[str, Any]] = [] for e in body.get("excuses") or []: (held if e.get("change") == "added" else kept).append(e) for e in held: @@ -293,21 +308,46 @@ def apply( 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``).""" + frame can see a lost update without the bookkeeping move. + + Either every declared effect creates new records (``record_written`` + with ``count_new_only``; a zero-count guard writes nothing), or the + contract reads the target's versions (``frame.versions``) and those + versions cover every other effect: with a ``target_surface``, each + effect that isn't a create must be read on that surface. Anything else, + such as a create plus a ``field_equals`` update, gets no excuse.""" + + from openadapt_flow.runtime.effects.surfaces import surface_of 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) + effects = list(getattr(config, "effects", None) or []) + + def kind(effect: Any) -> str: + k = getattr(effect, "kind", "") + return str(getattr(k, "value", k)) + + def creates(effect: Any) -> bool: + return ( + kind(effect) == "record_written" + and getattr(effect, "count_new_only", None) is True + and getattr(effect, "expected_count", 1) != 0 + ) + + def guard(effect: Any) -> bool: + return ( + kind(effect) == "record_written" + and getattr(effect, "expected_count", 1) == 0 + ) + + others = [e for e in effects if not creates(e) and not guard(e)] + if not others: + return any(creates(e) for e in effects) + versions = getattr(frame, "versions", None) if frame is not None else None + if versions is None: + return False + surface = getattr(versions, "target_surface", None) + return surface is None or all(surface_of(e) == surface for e in others) def http_sender( @@ -397,7 +437,7 @@ def cmd_probe(args: Any) -> int: return 0 -def add_parser(steps: Any) -> None: +def register_parser(steps: Any) -> None: """The ``probe`` step of ``openadapt-flow learn``.""" p = steps.add_parser( diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index e27c4c2bee..4499093a46 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -175,9 +175,9 @@ def write(first: bool = False) -> None: ("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")] + # The first-login row showed in one round only: not bookkeeping, so it is + # neither excused nor held for approval; it stays a stop. + assert proposal["kinds"]["read_only_probe"]["needs_approval"] == [] contract = write_contract(engine, tmp_path, proposal) t = _title() after = check(engine, contract, {"title": t, "body": "Body text"}, write, tmp_path) @@ -393,3 +393,69 @@ def act() -> None: tmp_path, ) # fmt: skip ) + + +def test_a_move_in_one_round_only_is_not_excused( + engine: Engine, tmp_path: Path +) -> None: + """A person editing the acting user's own row during one probe round + is not per-request bookkeeping: only moves every round shows are.""" + + rounds = [0] + + def send() -> set[str]: + app_reads(engine, first=False) + if rounds[0] == 0: + engine.run( + "UPDATE app_user SET email = %s WHERE id = %s", + f"{_stamp()}@example.test", + int(ACTOR), + ) + rounds[0] += 1 + return {"q"} + + got = { + (x["table"], tuple(x["columns"])) + for x in excuses_of(run_probe(engine, tmp_path, send)) + } + assert not any(t == "app_user" and "email" in cols for t, cols in got) + # The token row moved the same way every round: still bookkeeping. + assert ("api_token", ("last_seen",)) in got + + +def test_one_round_learns_nothing(engine: Engine, tmp_path: Path) -> None: + with pytest.raises(learn_probe.ProbeError): + run_probe(engine, tmp_path, first_once(engine), rounds=1) + + +def test_a_create_plus_an_update_gets_no_probe_excuse( + engine: Engine, tmp_path: Path +) -> None: + """``record_written`` with ``count_new_only`` beside a ``field_equals`` + update is not create-only: the update can't see a lost update.""" + + proposal = run_probe(engine, tmp_path, first_once(engine)) + doc = note_contract(engine) + doc["effects"].append( + {"kind": "field_equals", "match": {"id": {"literal": "1"}}, + "field": "title", "value": {"param": "title"}} + ) # fmt: skip + path = tmp_path / "mixed.yaml" + path.write_text(yaml.safe_dump(doc)) + assert learn_probe.apply(proposal, [path]) == [] + assert "learned" not in yaml.safe_load(path.read_text())["frame"] + + +def test_versions_on_another_surface_do_not_cover_an_update() -> None: + from types import SimpleNamespace as NS + + from openadapt_flow.runtime.effects.effect import EffectKind + from openadapt_flow.runtime.effects.surfaces import surface_probe + + update = NS(kind=EffectKind.FIELD_EQUALS, probe=surface_probe("secondary"), + expected_count=1, count_new_only=False) # fmt: skip + versions = NS(target_surface="primary") + contract = NS(config=NS(frame=NS(versions=versions), effects=[update])) + assert learn_probe._sees_its_own_harm(contract) is False + contract.config.frame.versions = NS(target_surface=None) + assert learn_probe._sees_its_own_harm(contract) is True From 9397a64c87dc570ec53b7d32b921de6d4aed4062 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:55:47 -0500 Subject: [PATCH 08/14] docs(flow): learn probe excuses only moves every round shows --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/docs/LEARNED_EXCUSES.md | 15 ++++++++++----- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 199b347f44..fcd0c0c3e6 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -184,7 +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) | +| 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 that every round (at least two) shows (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 whose every effect creates new records, or that read the target's versions on every other effect's surface, 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 a56c7e6585..403484f60b 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -618,7 +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) | +| 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 that every round (at least two) shows (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 whose every effect creates new records, or that read the target's versions on every other effect's surface, 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) | diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index f3fa7e3e38..1b76185010 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -203,9 +203,12 @@ 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 +the parameters or a contract name. A `changed` move counts only when every +round shows it (`--rounds`, at least two): per-request bookkeeping moves on +every request, while an edit someone makes to the acting user's own row +during one round does not, so it stays a stop. A round in which nothing +moved means nothing is learned. 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`. @@ -219,8 +222,10 @@ learned unless you name it (`--users`). `frame.learned.source: read_only_probe`, and leaves out of each contract 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 +one whose every declared effect creates a new record (`count_new_only`; +a create beside a `field_equals` update doesn't count), or one that reads +the target's versions (`frame.versions`) on the surface of every other +effect (its `target_surface`, when set). 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 From 9a0976ebadd5ba772993c2e3df3dc1ae4943a5b4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:56:03 -0500 Subject: [PATCH 09/14] fix(flow): row versions bound to the target's own table; only no-such-multixact means a plain xid; one-table reads only Review blockers on #2457: - frame.row_versions is judged only when its table and key_column are the table and column the target_surface's read takes the target_field from, over the frame's own connection (row_versions.binding_problem). A decoy table with the same key now leaves the frame not checked (unbound_source) instead of vouching for a target it never held. - _multixact_updater_other_than treats only PostgreSQL's "MultiXactId N has not been created yet" / "does no longer exist" as a plain xid. Any other error is raised, so the judge reports not checked. - detect_row_versions (now row_versions.single_table_read) accepts one SELECT over one table and rejects UNION, INTERSECT, EXCEPT, JOIN, LATERAL, WITH, subqueries and a second statement. --- packages/flow/openadapt_flow/learn_probe.py | 39 +++----- .../runtime/effects/row_versions.py | 97 ++++++++++++++++++- .../runtime/effects/versions.py | 1 + packages/flow/openadapt_flow/verify_run.py | 11 +++ packages/flow/tests/test_row_versions.py | 92 +++++++++++++++++- 5 files changed, 209 insertions(+), 31 deletions(-) diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 074c709668..db9b501844 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -38,7 +38,6 @@ from __future__ import annotations import json -import re import tempfile from collections.abc import Callable, Mapping, Sequence from pathlib import Path @@ -322,17 +321,6 @@ def _sees_its_own_harm(contract: Any) -> bool: return bool(records) and all(r.get("count_new_only") is True for r in records) -_IDENT = r'(?:"[A-Za-z_][A-Za-z0-9_$]*"|[A-Za-z_][A-Za-z0-9_$]*)' -#: The main relation of a generated read: ``... FROM "table" t`` at the end. -_MAIN_FROM = re.compile( - rf"\bFROM\s+({_IDENT}(?:\.{_IDENT})?)\s+(?:AS\s+)?t\s*;?\s*$", re.IGNORECASE -) - - -def _unquote(name: str) -> str: - return ".".join(p.strip('"') for p in name.split(".")) - - def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: """A version source for an update or found check, from the contract alone: on PostgreSQL, the target's own row versions @@ -375,25 +363,22 @@ def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]: read = database.get("read") or {} if any(source.get(k) != read.get(k) for k in ("sql_driver", "sql_connect_args")): return None # another database: its rows aren't the frame's - query = " ".join(str(source.get("sql_query") or "").split()) - main = _MAIN_FROM.search(query) - # One FROM: the declared record is one row, so the row's versions are - # the record's. A read that also looks into other tables (a list of - # tags, a child row) declares rows this source doesn't count. - if main is None or len(re.findall(r"\bFROM\b", query, re.IGNORECASE)) != 1: - return None - field = str(frame.get("identity_field") or "id") - column = re.search( - rf'(?:CAST\(\s*)?t\.({_IDENT})(?:\s+AS\s+TEXT\s*\))?\s+AS\s+"?{re.escape(field)}"?\s*,', - query, - re.IGNORECASE, + from openadapt_flow.runtime.effects.row_versions import single_table_read + + # One SELECT over one table: the declared record is one row, so the + # row's versions are the record's. A read that also looks into other + # tables (a list of tags, a child row, a UNION) declares rows this + # source doesn't count. + found = single_table_read( + str(source.get("sql_query") or ""), str(frame.get("identity_field") or "id") ) - if column is None: + if found is None: return None + table, key_column = found return { "source": "postgresql_xmin", - "table": _unquote(main.group(1)), - "key_column": _unquote(column.group(1)), + "table": table, + "key_column": key_column, "target_surface": surface, } diff --git a/packages/flow/openadapt_flow/runtime/effects/row_versions.py b/packages/flow/openadapt_flow/runtime/effects/row_versions.py index 68225822ac..5d180d3c6e 100644 --- a/packages/flow/openadapt_flow/runtime/effects/row_versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/row_versions.py @@ -106,6 +106,91 @@ def names(self) -> tuple[Optional[str], str, str]: return schema, parts[-1], self.key_column +_IDENT = r'(?:"[A-Za-z_][A-Za-z0-9_$]*"|[A-Za-z_][A-Za-z0-9_$]*)' +#: The main relation of a generated read: ``... FROM "table" t`` at the end. +_MAIN_FROM = re.compile( + rf"\bFROM\s+({_IDENT}(?:\.{_IDENT})?)\s+(?:AS\s+)?t\s*;?\s*$", re.IGNORECASE +) +#: Anything that lets one read return rows that aren't the main table's. +_NOT_ONE_TABLE = re.compile( + r"\b(?:UNION|INTERSECT|EXCEPT|JOIN|LATERAL|WITH)\b|;(?!\s*$)", re.IGNORECASE +) + + +def _unquote(name: str) -> str: + return ".".join(p.strip('"') for p in name.split(".")) + + +def single_table_read(query: str, field: str) -> Optional[tuple[str, str]]: + """``(table, key column)`` when ``query`` is one ``SELECT`` over one + table aliased ``t`` that selects ``field`` straight from one of its + columns; None for anything else (a ``UNION``, a join, a subquery, a CTE, + a second statement, a second ``FROM``).""" + + text = " ".join(str(query or "").split()) + if ( + len(re.findall(r"\bSELECT\b", text, re.IGNORECASE)) != 1 + or len(re.findall(r"\bFROM\b", text, re.IGNORECASE)) != 1 + or _NOT_ONE_TABLE.search(text) + or not re.match(r"^\s*SELECT\b", text, re.IGNORECASE) + ): + return None + main = _MAIN_FROM.search(text) + if main is None: + return None + column = re.search( + rf'(?:CAST\(\s*)?t\.({_IDENT})(?:\s+AS\s+TEXT\s*\))?\s+AS\s+"?{re.escape(field)}"?\s*,', + text, + re.IGNORECASE, + ) + if column is None: + return None + return _unquote(main.group(1)), _unquote(column.group(1)) + + +def binding_problem( + spec: FrameRowVersions, + surfaces: Mapping[str, Any], + database_read: Mapping[str, Any], + identity_field: Optional[str], +) -> Optional[str]: + """Why ``spec`` isn't bound to the record the contract reads, or None. + + The held rows count saves only when they are the target's own rows: the + table and key column must be the ones the ``target_surface`` read takes + the target's ``target_field`` from, over the frame's own connection. A + hand-written ``table`` with the same key (a decoy that nobody else + edits) would otherwise vouch for a target it never held.""" + + if not spec.target_surface: + return "frame.row_versions names no target_surface" + source = surfaces.get(spec.target_surface) + get = ( + source.get + if isinstance(source, Mapping) + else (lambda k, d=None: getattr(source, k, d)) + ) + if source is None or get("kind") != "sql": + return "frame.row_versions.target_surface is not a SQL read" + for key in ("sql_driver", "sql_connect_args"): + if (get(key) or None) != (database_read.get(key) or None): + return "the target surface reads another database than the frame" + field = spec.target_field or identity_field or "id" + found = single_table_read(str(get("sql_query") or ""), field) + if found is None: + return ( + "the target surface's read is not one SELECT over one table that " + "selects the target field from one column" + ) + table, key = found + if (table, key) != (_unquote(spec.table), spec.key_column): + return ( + "frame.row_versions.table and key_column are not the table and " + "column the target surface reads the target from" + ) + return None + + def _quote(name: str) -> str: return '"' + name.replace('"', '""') + '"' @@ -216,6 +301,11 @@ def take(token: str) -> Optional[HeldRead]: return _HELD.pop(token, None) +#: PostgreSQL's errors for a number that names no multixact (multixact.c): +#: only these mean the old ``xmax`` is a plain transaction id. +_NO_SUCH_MULTIXACT = re.compile( + r"MultiXactId \d+ (?:has not been created yet|does no longer exist)" +) #: ``pg_get_multixact_members`` modes that update a row (not just lock it). _UPDATE_MODES = frozenset({"nokeyupd", "upd"}) @@ -224,7 +314,8 @@ def _multixact_updater_other_than(cur: Any, value: str, writer: str) -> bool: """Could ``value``, read as the old version's ``xmax``, be a multixact id (a shared lock) whose updater is a transaction other than ``writer``? Then two writers could read as one. A value that is no multixact (the - function errors) can't.""" + function's "has not been created yet" or "does no longer exist" error) + can't. Any other error is raised, so the target is not checked.""" try: cur.execute( @@ -232,7 +323,9 @@ def _multixact_updater_other_than(cur: Any, value: str, writer: str) -> bool: (value,), ) members = cur.fetchall() - except Exception: # noqa: BLE001 - not a multixact id: a plain xid + except Exception as exc: # noqa: BLE001 - only "no such multixact" is a plain xid + if not _NO_SUCH_MULTIXACT.search(str(exc)): + raise # any other failure: the judge leaves the target not checked return False return any(str(m) in _UPDATE_MODES and str(x) != writer for x, m in members) diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py index cf2732fb94..7df84f17fb 100644 --- a/packages/flow/openadapt_flow/runtime/effects/versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/versions.py @@ -61,6 +61,7 @@ "unknown_surface", "ambiguous_xmax", "created_target", + "unbound_source", ) _WHOLE = re.compile(r"^(0|[1-9][0-9]*)$") diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index af53293db8..5fdf26d527 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -829,6 +829,17 @@ def _judge_row_versions( reason="frame.row_versions.target_surface names a surface no " "write target is read from", ) + elif ( + unbound := rv.binding_problem( + spec, + cfg.verifier.surfaces, + cfg.frame.database.read, # type: ignore[union-attr] + cfg.frame.identity_field, # type: ignore[union-attr] + ) + ) is not None: + if held is not None: + held.close() + result = VersionVerdict("not_checked", "unbound_source", reason=unbound) else: targets = _version_targets( cfg, before, effects, verdicts, spec.target_field, spec.target_surface diff --git a/packages/flow/tests/test_row_versions.py b/packages/flow/tests/test_row_versions.py index f8cd65de4f..77f748830a 100644 --- a/packages/flow/tests/test_row_versions.py +++ b/packages/flow/tests/test_row_versions.py @@ -62,6 +62,11 @@ def pg(request: pytest.FixtureRequest, tmp_path: Path) -> Any: SPEC = {"table": "asset", "key_column": "id"} +BOUND_READ = ( + 'SELECT CAST(t."id" AS TEXT) AS "id", t."tag" AS "tag", t."name" AS "name", ' + 't."assigned_to" AS "assigned_to", t."modified_at" AS "modified_at" ' + 'FROM "asset" t' +) _n = [0] @@ -82,7 +87,15 @@ def rename_contract(e: Engine, *, versions: bool = True, found: bool = False) -> doc = _le.asset_contract(e, learned_block(LOGIN, SEEN)) if versions: - doc["frame"]["row_versions"] = dict(SPEC) + # The held rows must be the ones the target surface reads the + # record from (rv.binding_problem): one SELECT over "asset" t. + doc["verifier"] = { + "kind": "surfaces", + "surfaces": {"record": _le._verifier(e, BOUND_READ)}, + } + for effect in doc["effects"]: + effect["probe"] = "surface=record" + doc["frame"]["row_versions"] = {**SPEC, "target_surface": "record"} if found: doc["frame"]["target_fields"] = [] return doc @@ -118,7 +131,9 @@ def __init__(self, rows: list[tuple], members: Optional[list[tuple]]) -> None: def execute(self, sql: str, *a: Any) -> None: self._sql = sql if "multixact" in sql and self._members is None: - raise RuntimeError("MultiXactId has not been created yet") + raise RuntimeError( + "MultiXactId 105 has not been created yet -- apparent wraparound" + ) def fetchall(self) -> list[tuple]: return list(self._members or []) if "multixact" in self._sql else self._rows @@ -481,3 +496,76 @@ def test_held_read_is_a_read_only_snapshot(pg: Engine) -> None: held.close() with pytest.raises(Exception): rv.open_held(rv.FrameRowVersions(table="no_such_table"), _db_connect(pg.read)) + + +# -- review blockers: binding, multixact errors, one-table reads -------------- + + +class _FailingCur(_Cur): + def execute(self, sql: str, *a: Any) -> None: + self._sql = sql + if "multixact" in sql: + raise RuntimeError( + "permission denied for function pg_get_multixact_members" + ) + + +def test_any_other_multixact_error_is_not_checked() -> None: + """Only "no such multixact" means a plain xid; any other failure (a + permission error, a dropped connection) can't rule out two writers.""" + + class Conn(_Conn): + def cursor(self) -> _Cur: + return _FailingCur(self._rows, self._members) + + spec = rv.FrameRowVersions(**SPEC) + v = rv.judge_row_versions( + spec, + _Held({"1": ("100", "105")}), + lambda: Conn([("1", "105", "0")]), + [("1", True, True)], + ) + assert v.status == "not_checked" + + +@pytest.mark.parametrize( + "query", + [ + 'SELECT 1 AS "x" UNION SELECT CAST(t."id" AS TEXT) AS "id", t."n" AS "n" ' + 'FROM "part_part" t', + 'WITH d AS (SELECT 1) SELECT CAST(t."id" AS TEXT) AS "id", t."n" AS "n" ' + 'FROM "part_part" t', + 'SELECT CAST(t."id" AS TEXT) AS "id", t."n" AS "n" FROM "part_part" t; ' + 'SELECT 1 FROM "part_part" t', + 'SELECT CAST(t."id" AS TEXT) AS "id", (SELECT 1) AS "n" FROM "part_part" t', + ], +) +def test_a_read_that_is_not_one_select_over_one_table_has_no_source( + query: str, +) -> None: + assert rv.single_table_read(query, "id") is None + assert learn_probe.detect_row_versions(_generated("postgresql", query)) is None + + +def _bound(spec: dict, query: str = GENERATED) -> Optional[str]: + doc = _generated("postgresql", query) + return rv.binding_problem( + rv.FrameRowVersions(**spec), + doc["verifier"]["surfaces"], + doc["frame"]["database"]["read"], + "id", + ) + + +def test_row_versions_must_be_the_target_surfaces_own_table() -> None: + """A decoy table with the same key (one nobody edits) would vouch for a + target it never held: an edit and a revert would pass.""" + + good = {"table": "part_part", "key_column": "id", "target_surface": "record"} + assert _bound(good) is None + assert _bound({**good, "table": "decoy"}) is not None + assert _bound({**good, "key_column": "other_id"}) is not None + assert _bound({**good, "target_surface": "elsewhere"}) is not None + assert _bound({"table": "part_part", "key_column": "id"}) is not None + joined = GENERATED.replace('FROM "part_part" t', 'FROM "part_part" t JOIN x ON 1=1') + assert _bound(good, query=joined) is not None From 83138c03a184693760694410b702e8af0ac4786d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:55:45 -0500 Subject: [PATCH 10/14] fix(learn): attribute probe excuses with control windows; one surface for unscoped versions Codex review blockers on #2413. fail-open class: correlation-as-attribution. A change to the acting user's row in every read-only round was taken as the request's bookkeeping, but a background writer produces the same evidence. Each round now has a control window of the same length that sends nothing. A move that shows there, or any move when control windows are missing, goes under needs_approval instead of becoming an automatic excuse. fail-open class: ambiguous-subject-binding. With frame.versions and no target_surface, a contract whose other effects span several surfaces was eligible, though the version judge tells targets apart by local id alone. Such a contract now gets no automatic excuse. --- packages/flow/docs/LEARNED_EXCUSES.md | 9 ++- packages/flow/openadapt_flow/learn_probe.py | 80 ++++++++++++++++++--- packages/flow/tests/test_learn_probe.py | 69 +++++++++++++++++- 3 files changed, 146 insertions(+), 12 deletions(-) diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index 1b76185010..7fcbb45ad0 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -206,7 +206,11 @@ own rows, the exact columns, and never a column the probe's query strings, the parameters or a contract name. A `changed` move counts only when every round shows it (`--rounds`, at least two): per-request bookkeeping moves on every request, while an edit someone makes to the acting user's own row -during one round does not, so it stays a stop. A round in which nothing +during one round does not, so it stays a stop. After each round the probe +also reads a control window of the same length in which it sends nothing. +A column that moves in a control window moves without a request (a +background job, or another session), so it is not excused automatically: +it goes under `needs_approval`. A round in which nothing moved means nothing is learned. 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 @@ -225,7 +229,8 @@ contract whose frame can see a lost update without the bookkeeping move: one whose every declared effect creates a new record (`count_new_only`; a create beside a `field_equals` update doesn't count), or one that reads the target's versions (`frame.versions`) on the surface of every other -effect (its `target_surface`, when set). In an update with no +effect (its `target_surface`; with none set, every other effect must be +on one surface, since an unscoped read tells records apart by id alone). 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 diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 8d55ecf303..1950d3f291 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -15,7 +15,8 @@ (``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. + are used. A control window of the same length follows each round with + no request; a move it shows is not the request's and is not excused. 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 @@ -39,6 +40,7 @@ import json import tempfile +import time from collections.abc import Callable, Mapping, Sequence from pathlib import Path from typing import Any, Optional @@ -112,12 +114,16 @@ def probe( send: Callable[[], set[str]], rounds: int = DEFAULT_ROUNDS, workdir: Optional[Path] = None, + idle: Callable[[float], None] = time.sleep, ) -> 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.""" + write. After each request window, a control window as long as it sends + nothing (``idle``): a row that moves there moves without a request, so + it is not the request's bookkeeping. Returns one request episode and + one control episode (``control: True``) per round.""" from openadapt_flow.verifier import Actor, begin_write, verify_write @@ -139,13 +145,33 @@ def probe( write_key=f"read-only-probe-{kind}-{i}", workdir=base / f"round-{i}", ) + started = time.monotonic() sent = set(send()) + elapsed = time.monotonic() - started result = verify_write(pending) out.append( episode( kind, result, contract=contract, params=params, sent_fields=sent ) ) + control = begin_write( + contract, + dict(params), + actor=Actor("agent", str(actor)), + ledger=None, + write_key=f"read-only-probe-{kind}-{i}-control", + workdir=base / f"round-{i}-control", + ) + idle(elapsed) + ep = episode( + kind, + verify_write(control), + contract=contract, + params=params, + sent_fields=set(), + ) + ep["control"] = True + out.append(ep) return out @@ -206,7 +232,18 @@ def propose( 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")] + probes = [e for e in episodes if e.get("probe")] + controls = [e for e in probes if e.get("control")] + eps = [dict(e, kind="read_only_probe") for e in probes if not e.get("control")] + # fail-open class: correlation-as-attribution. A move seen in every + # request round is only timing; it is the request's bookkeeping only + # when the control windows (no request) show it never moving on its own. + background = { + (str(m.get("table")), str(c)) + for e in controls + for m in e.get("moves") or [] + for c in m.get("columns") or [None] + } 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=n, n=n, source="read-only probe") @@ -223,13 +260,33 @@ def propose( kept: list[dict[str, Any]] = [] held: list[dict[str, Any]] = [] for e in body.get("excuses") or []: - (held if e.get("change") == "added" else kept).append(e) + if e.get("change") == "added": + e["why_not"] = ( + "an added row: its excuse names columns, not values, so a " + "person approves it (learn approve)" + ) + elif len(controls) < len(eps): + e["why_not"] = ( + "no control window without requests for every round: " + "nothing shows the move comes from the request, so a " + "person approves it (learn approve)" + ) + elif any( + (str(e.get("table")), str(c)) in background + or (str(e.get("table")), "None") in background + for c in e.get("columns") or [] + ): + e["why_not"] = ( + "it also moved in a control window with no request: a " + "background writer, not the request's bookkeeping, so a " + "person approves it (learn approve)" + ) + else: + kept.append(e) + continue + held.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) @@ -347,7 +404,12 @@ def guard(effect: Any) -> bool: if versions is None: return False surface = getattr(versions, "target_surface", None) - return surface is None or all(surface_of(e) == surface for e in others) + if surface is None: + # fail-open class: ambiguous-subject-binding. An unscoped version + # read judges targets by their local id alone, so two records with + # one id on two surfaces would share one version check. + return len({surface_of(e) for e in others}) == 1 + return all(surface_of(e) == surface for e in others) def http_sender( diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index 4499093a46..08f29ec783 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -112,7 +112,9 @@ def users(e: Engine) -> learn.Users: return learn.users_from("app_user", "id", schema) -def run_probe(e: Engine, tmp_path: Path, send: Any, rounds: int = 3) -> dict: +def run_probe( + e: Engine, tmp_path: Path, send: Any, rounds: int = 3, idle: Any = None +) -> dict: c = Contract.from_dict(note_contract(e), name="note") eps = learn_probe.probe( c, @@ -122,6 +124,7 @@ def run_probe(e: Engine, tmp_path: Path, send: Any, rounds: int = 3) -> dict: send=send, rounds=rounds, workdir=tmp_path / "probe", + idle=idle or (lambda _s: None), ) return learn_probe.propose(eps, users(e)) @@ -459,3 +462,67 @@ def test_versions_on_another_surface_do_not_cover_an_update() -> None: assert learn_probe._sees_its_own_harm(contract) is False contract.config.frame.versions = NS(target_surface=None) assert learn_probe._sees_its_own_harm(contract) is True + + +def test_a_background_writer_on_the_actors_row_is_not_excused( + engine: Engine, tmp_path: Path +) -> None: + """A job that bumps the acting user's row whether or not a request is + sent moves in the control windows too: timing alone is no attribution, + so it waits for a person instead of becoming an automatic excuse.""" + + def background(_seconds: float) -> None: + engine.run( + "UPDATE app_user SET last_login = %s WHERE id = %s", _stamp(), int(ACTOR) + ) + + def send() -> set[str]: + background(0) + engine.run( + "UPDATE api_token SET last_seen = %s WHERE user_id = %s", + _stamp(), + int(ACTOR), + ) + return {"q"} + + proposal = run_probe(engine, tmp_path, send, idle=background) + got = {(x["table"], tuple(x["columns"])) for x in excuses_of(proposal)} + assert not any(t == "app_user" for t, _cols in got) + held = proposal["kinds"]["read_only_probe"]["needs_approval"] + assert any(x["table"] == "app_user" for x in held) + # The token row moved only with requests: still bookkeeping. + assert ("api_token", ("last_seen",)) in got + + +def test_episodes_without_control_windows_excuse_nothing_automatically( + engine: Engine, tmp_path: Path +) -> None: + c = Contract.from_dict(note_contract(engine), name="note") + eps = learn_probe.probe( + c, {"title": "Probe note", "body": "x"}, kind="add_note", actor=ACTOR, + send=first_once(engine), workdir=tmp_path / "probe", idle=lambda _s: None, + ) # fmt: skip + proposal = learn_probe.propose( + [e for e in eps if not e.get("control")], users(engine) + ) + assert excuses_of(proposal) == [] + assert proposal["kinds"]["read_only_probe"]["needs_approval"] + + +def test_unscoped_versions_over_two_surfaces_do_not_cover_updates() -> None: + from types import SimpleNamespace as NS + + from openadapt_flow.runtime.effects.effect import EffectKind + from openadapt_flow.runtime.effects.surfaces import surface_probe + + def update(surface: str) -> Any: + return NS(kind=EffectKind.FIELD_EQUALS, probe=surface_probe(surface), + expected_count=1, count_new_only=False) # fmt: skip + + versions = NS(target_surface=None) + two = NS(config=NS(frame=NS(versions=versions), + effects=[update("primary"), update("secondary")])) # fmt: skip + assert learn_probe._sees_its_own_harm(two) is False + one = NS(config=NS(frame=NS(versions=versions), + effects=[update("primary"), update("primary")])) # fmt: skip + assert learn_probe._sees_its_own_harm(one) is True From b0769172825fd35daefbcc5b441cd5358fac302f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:06:17 -0500 Subject: [PATCH 11/14] fix(row-versions): bind the key projection exactly; refuse duplicate keys and expired multixacts Codex review blockers on #2457. fail-open class: ambiguous-subject-binding. The projection matcher found the key column anywhere in the select list, so a computed identity ending with that column qualified while returning a different value than the lookup column. The select item must now be exactly t. or CAST(t. AS TEXT). When a key maps to more than one physical row in the baseline or current read, the target is not_checked instead of one version silently replacing the other. fail-open class: absent-evidence-as-success. PostgreSQL also says "does no longer exist" for a multixact older than its retained range, whose members are gone. Only "has not been created yet" now means a plain xid; an expired lookup leaves the target not_checked. --- .../runtime/effects/row_versions.py | 54 +++++++++++---- packages/flow/tests/test_row_versions.py | 66 +++++++++++++++++++ 2 files changed, 108 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/effects/row_versions.py b/packages/flow/openadapt_flow/runtime/effects/row_versions.py index 5d180d3c6e..671160caf8 100644 --- a/packages/flow/openadapt_flow/runtime/effects/row_versions.py +++ b/packages/flow/openadapt_flow/runtime/effects/row_versions.py @@ -138,14 +138,19 @@ def single_table_read(query: str, field: str) -> Optional[tuple[str, str]]: main = _MAIN_FROM.search(text) if main is None: return None + # fail-open class: ambiguous-subject-binding. The whole select item must + # be the column itself (or its text cast): an expression that merely + # ends with the column returns another value than the one the row is + # looked up by. column = re.search( - rf'(?:CAST\(\s*)?t\.({_IDENT})(?:\s+AS\s+TEXT\s*\))?\s+AS\s+"?{re.escape(field)}"?\s*,', + rf"(?:\bSELECT\s+|,\s*)(?:CAST\(\s*t\.({_IDENT})\s+AS\s+TEXT\s*\)|t\.({_IDENT}))" + rf'\s+AS\s+"?{re.escape(field)}"?\s*(?:,|\bFROM\b)', text, re.IGNORECASE, ) if column is None: return None - return _unquote(main.group(1)), _unquote(column.group(1)) + return _unquote(main.group(1)), _unquote(column.group(1) or column.group(2)) def binding_problem( @@ -218,6 +223,23 @@ def _relkind_query(spec: FrameRowVersions) -> tuple[str, tuple[str, ...]]: ) +class DuplicateKey(ValueError): + """A key column value names more than one physical row.""" + + +def _unique_rows(fetched: Sequence[tuple]) -> dict[str, tuple]: + """``key -> (xmin, xmax)``. fail-open class: ambiguous-subject-binding: + when a key maps to several rows, one version would silently replace the + other, so the read refuses instead.""" + + out: dict[str, tuple] = {} + for k, x, m in fetched: + if str(k) in out: + raise DuplicateKey(str(k)) + out[str(k)] = (x, m) + return out + + @dataclass class HeldRead: """An open read-only REPEATABLE READ transaction from the baseline.""" @@ -228,7 +250,7 @@ class HeldRead: def rows(self, spec: FrameRowVersions, keys: Sequence[str]) -> dict[str, tuple]: cur = self.conn.cursor() cur.execute(_query(spec), (list(keys),)) - return {str(k): (x, m) for k, x, m in cur.fetchall()} + return _unique_rows(cur.fetchall()) def close(self) -> None: try: @@ -301,11 +323,11 @@ def take(token: str) -> Optional[HeldRead]: return _HELD.pop(token, None) -#: PostgreSQL's errors for a number that names no multixact (multixact.c): -#: only these mean the old ``xmax`` is a plain transaction id. -_NO_SUCH_MULTIXACT = re.compile( - r"MultiXactId \d+ (?:has not been created yet|does no longer exist)" -) +#: PostgreSQL's error for a number past every multixact made (multixact.c): +#: only this means the old ``xmax`` is a plain transaction id. "does no +#: longer exist" is also raised for an expired multixact, whose members are +#: gone (fail-open class: absent-evidence-as-success), so it is not checked. +_NO_SUCH_MULTIXACT = re.compile(r"MultiXactId \d+ has not been created yet") #: ``pg_get_multixact_members`` modes that update a row (not just lock it). _UPDATE_MODES = frozenset({"nokeyupd", "upd"}) @@ -313,9 +335,10 @@ def take(token: str) -> Optional[HeldRead]: def _multixact_updater_other_than(cur: Any, value: str, writer: str) -> bool: """Could ``value``, read as the old version's ``xmax``, be a multixact id (a shared lock) whose updater is a transaction other than ``writer``? - Then two writers could read as one. A value that is no multixact (the - function's "has not been created yet" or "does no longer exist" error) - can't. Any other error is raised, so the target is not checked.""" + Then two writers could read as one. A value past every multixact made + (the function's "has not been created yet" error) can't. Any other error, + an expired multixact's "does no longer exist" among them, is raised, so + the target is not checked.""" try: cur.execute( @@ -355,7 +378,7 @@ def judge_row_versions( conn.autocommit = True cur = conn.cursor() cur.execute(_query(spec), (keys,)) - now = {str(k): (x, m) for k, x, m in cur.fetchall()} + now = _unique_rows(cur.fetchall()) ambiguous = { k for k, (base_xmin, base_xmax) in old.items() @@ -366,6 +389,13 @@ def judge_row_versions( } finally: conn.close() + except DuplicateKey: + return VersionVerdict( + "not_checked", + "unreadable", + reason="frame.row_versions.key_column names more than one row " + "for a target, so the target's own versions can't be told", + ) except Exception: # noqa: BLE001 - unreadable -> the check stops the run return VersionVerdict( "not_checked", diff --git a/packages/flow/tests/test_row_versions.py b/packages/flow/tests/test_row_versions.py index 77f748830a..353b63e74b 100644 --- a/packages/flow/tests/test_row_versions.py +++ b/packages/flow/tests/test_row_versions.py @@ -569,3 +569,69 @@ def test_row_versions_must_be_the_target_surfaces_own_table() -> None: assert _bound({"table": "part_part", "key_column": "id"}) is not None joined = GENERATED.replace('FROM "part_part" t', 'FROM "part_part" t JOIN x ON 1=1') assert _bound(good, query=joined) is not None + + +@pytest.mark.parametrize( + "item", + [ + 'CAST(t."id" + 0 AS TEXT) AS "id"', + 'COALESCE(NULL, t."id") AS "id"', + 'lower(t."code") || t."id" AS "id"', + ], +) +def test_a_computed_identity_is_not_the_key_column(item: str) -> None: + """The returned identity must be the column itself (or its text cast), + not an expression that ends with it.""" + + query = f'SELECT {item}, t."n" AS "n" FROM "part_part" t' + assert rv.single_table_read(query, "id") is None + + +def test_a_direct_or_cast_identity_is_the_key_column() -> None: + for item in ('CAST(t."id" AS TEXT) AS "id"', 't."id" AS "id"'): + query = f'SELECT t."n" AS "n", {item} FROM "part_part" t' + assert rv.single_table_read(query, "id") == ("part_part", "id") + + +def test_a_key_naming_two_rows_is_not_checked() -> None: + spec = rv.FrameRowVersions(**SPEC) + two_now = rv.judge_row_versions( + spec, + _Held({"1": ("100", "105")}), + lambda: _Conn([("1", "105", "0"), ("1", "107", "0")]), + [("1", True, True)], + ) + assert two_now.status == "not_checked" + assert "more than one row" in two_now.reason + + class TwoHeld(_Held): + def rows(self, spec: Any, keys: Any) -> dict[str, tuple]: + return rv._unique_rows([("1", "100", "105"), ("1", "101", "0")]) + + two_before = rv.judge_row_versions( + spec, TwoHeld({}), lambda: _Conn([("1", "105", "0")]), [("1", True, True)] + ) + assert two_before.status == "not_checked" + + +def test_an_expired_multixact_is_not_checked() -> None: + """PostgreSQL says "does no longer exist" for a multixact older than its + retained range too; its members are gone, so one writer can't be told.""" + + class ExpiredCur(_Cur): + def execute(self, sql: str, *a: Any) -> None: + self._sql = sql + if "multixact" in sql: + raise RuntimeError("MultiXactId 105 does no longer exist -- wraparound") + + class Conn(_Conn): + def cursor(self) -> _Cur: + return ExpiredCur(self._rows, self._members) + + v = rv.judge_row_versions( + rv.FrameRowVersions(**SPEC), + _Held({"1": ("100", "105")}), + lambda: Conn([("1", "105", "0")]), + [("1", True, True)], + ) + assert v.status == "not_checked" From c274d556aad313eab70ebdcba45c3699656e5e65 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:16:27 -0500 Subject: [PATCH 12/14] fix(learn): an unreadable control window is no evidence of no background move Gemini review blocker on #2413 (fail-open class: absent-evidence-as-success). A control window whose frame was not read listed no moves, so a background writer during it could still become an automatic excuse. Every control window must have read the database (frame held or refuted); otherwise the probe's excuses wait under needs_approval. --- packages/flow/openadapt_flow/learn_probe.py | 13 +++++++++---- packages/flow/tests/test_learn_probe.py | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 1950d3f291..4ad53d1ada 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -265,11 +265,16 @@ def propose( "an added row: its excuse names columns, not values, so a " "person approves it (learn approve)" ) - elif len(controls) < len(eps): + elif len(controls) < len(eps) or not all( + c.get("has_database") and c.get("frame") in ("held", "refuted") + for c in controls + ): + # A control window whose frame wasn't read shows nothing, + # which is no evidence that nothing moved. e["why_not"] = ( - "no control window without requests for every round: " - "nothing shows the move comes from the request, so a " - "person approves it (learn approve)" + "no readable control window without requests for every " + "round: nothing shows the move comes from the request, " + "so a person approves it (learn approve)" ) elif any( (str(e.get("table")), str(c)) in background diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index 08f29ec783..92f1d0ab3d 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -526,3 +526,22 @@ def update(surface: str) -> Any: one = NS(config=NS(frame=NS(versions=versions), effects=[update("primary"), update("primary")])) # fmt: skip assert learn_probe._sees_its_own_harm(one) is True + + +def test_an_unreadable_control_window_excuses_nothing_automatically( + engine: Engine, tmp_path: Path +) -> None: + """A control window whose frame read failed lists no moves; that is no + evidence the actor's row stays still without a request.""" + + c = Contract.from_dict(note_contract(engine), name="note") + eps = learn_probe.probe( + c, {"title": "Probe note", "body": "x"}, kind="add_note", actor=ACTOR, + send=first_once(engine), workdir=tmp_path / "probe", idle=lambda _s: None, + ) # fmt: skip + for e in eps: + if e.get("control"): + e.update(frame="not_checked", has_database=False, moves=[]) + proposal = learn_probe.propose(eps, users(engine)) + assert excuses_of(proposal) == [] + assert proposal["kinds"]["read_only_probe"]["needs_approval"] From 9117e38ef3aeda3a5093817205aa3ae243c62b44 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 17:34:11 -0500 Subject: [PATCH 13/14] test(flow): regenerate cli_surface.json for learn probe --- packages/flow/tests/fixtures/cli_surface.json | 249 +++++++++++++++++- 1 file changed, 248 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index bf392fb273..b8683ed00f 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -113,9 +113,10 @@ "openadapt-flow known-ids": "usage: openadapt-flow known-ids [-h] {confirm,status} ...\n\npositional arguments:\n {confirm,status}\n confirm Confirm the export's source and completeness (recorded)\n status Would replay accept this list now?\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow verify known-ids\n", "openadapt-flow known-ids confirm": "usage: openadapt-flow known-ids confirm [-h] [--column COLUMN] [--confirmation CONFIRMATION]\n --source SOURCE [--by BY] [--exported-at EXPORTED_AT]\n [--yes]\n export\n\npositional arguments:\n export Export file (CSV/TSV, JSON, or one ID per line)\n\noptions:\n -h, --help show this help message and exit\n --column COLUMN Identifier column (CSV/TSV)\n --confirmation CONFIRMATION\n Confirmation record (default: EXPORT.confirmation.json)\n --source SOURCE Which system and export this is\n --by BY Who confirms (default: your user name)\n --exported-at EXPORTED_AT\n When the export was taken (default: file time)\n --yes Skip the interactive prompt\n\nAlso available as: openadapt-flow verify known-ids confirm\n", "openadapt-flow known-ids status": "usage: openadapt-flow known-ids status [-h] [--column COLUMN] [--confirmation CONFIRMATION]\n [--max-age-hours MAX_AGE_HOURS]\n export\n\npositional arguments:\n export Export file (CSV/TSV, JSON, or one ID per line)\n\noptions:\n -h, --help show this help message and exit\n --column COLUMN Identifier column (CSV/TSV)\n --confirmation CONFIRMATION\n Confirmation record (default: EXPORT.confirmation.json)\n --max-age-hours MAX_AGE_HOURS\n\nAlso available as: openadapt-flow verify known-ids status\n", - "openadapt-flow learn": "usage: openadapt-flow learn [-h] {collect,propose,approve} ...\n\npositional arguments:\n {collect,propose,approve}\n collect run a shadow and record each check\n propose write a proposal a person can read\n approve write the approved excuses into contracts\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow teach --learn\n", + "openadapt-flow learn": "usage: openadapt-flow learn [-h] {collect,propose,approve,probe} ...\n\npositional arguments:\n {collect,propose,approve,probe}\n collect run a shadow and record each check\n propose write a proposal a person can read\n approve write the approved excuses into contracts\n probe learn per-request bookkeeping from read-only requests (no approval)\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow teach --learn\n", "openadapt-flow learn approve": "usage: openadapt-flow learn approve [-h] --by BY [--config CONFIG] [--manifest MANIFEST]\n [--contract KIND=PATH] [--kind KIND] [--reject ID]\n proposal\n\npositional arguments:\n proposal\n\noptions:\n -h, --help show this help message and exit\n --by BY who approves (recorded)\n --config CONFIG the shadow config's routes\n --manifest MANIFEST a generator manifest.yaml\n --contract KIND=PATH a contract file for a kind (repeatable)\n --kind KIND approve only these\n --reject ID leave out E\n\nAlso available as: openadapt-flow teach --learn approve\n", "openadapt-flow learn collect": "usage: openadapt-flow learn collect [-h] --config CONFIG [--out OUT] [--actor ACTOR]\n [--listen LISTEN] [--until-idle SECONDS]\n\noptions:\n -h, --help show this help message and exit\n --config CONFIG openadapt.shadow/v1 YAML (sql)\n --out OUT folder for episodes.jsonl\n --actor ACTOR the agent's user id in the app\n --listen LISTEN\n --until-idle SECONDS\n\nAlso available as: openadapt-flow teach --learn collect\n", + "openadapt-flow learn probe": "usage: openadapt-flow learn probe [-h] --manifest MANIFEST --kind KIND --values VALUES\n [--extra EXTRA] --actor ACTOR --base-url BASE_URL\n [--headers-env HEADERS_ENV] [--get PATH] [--head PATH]\n [--rounds ROUNDS] [--users USERS] [--user-column TABLE.COLUMN]\n [--schema SCHEMA] [--read READ] [--out OUT] [--apply]\n\noptions:\n -h, --help show this help message and exit\n --manifest MANIFEST the generator's manifest.yaml\n --kind KIND the kind whose contract frames the probe\n --values VALUES YAML: one task's values for that kind\n --extra EXTRA YAML: extra parameters (actor ids)\n --actor ACTOR the agent's user id in the app\n --base-url BASE_URL\n --headers-env HEADERS_ENV\n environment variable holding the agent's request headers as JSON\n --get PATH\n --head PATH\n --rounds ROUNDS\n --users USERS TABLE or TABLE.KEY (default: derived)\n --user-column TABLE.COLUMN\n --schema SCHEMA\n --read READ\n --out OUT\n --apply write the excuses into every contract the manifest lists\n\nAlso available as: openadapt-flow teach --learn probe\n", "openadapt-flow learn propose": "usage: openadapt-flow learn propose [-h] --episodes EPISODES [--users USERS]\n [--user-column TABLE.COLUMN] [--schema SCHEMA] [--read READ]\n [--k K] [--n N] [--out OUT]\n\noptions:\n -h, --help show this help message and exit\n --episodes EPISODES episodes.jsonl\n --users USERS the users table, as TABLE or TABLE.KEY (without it only the write's own\n rows can be excused)\n --user-column TABLE.COLUMN\n a column holding a user id, confirmed by you (repeatable)\n --schema SCHEMA schema.json from `generate schema`\n --read READ read.yaml: read the schema's foreign keys live\n --k K\n --n N\n --out OUT\n\nAlso available as: openadapt-flow teach --learn propose\n", "openadapt-flow ledger": "usage: openadapt-flow ledger [-h] [--home HOME] {add,list,show,summary,export,push} ...\n\npositional arguments:\n {add,list,show,summary,export,push}\n add Read a run's files and append its row\n list List rows\n show Show one row\n summary Counts per outcome, minutes, cost, duration\n export Write value-free rows as JSONL\n push Send value-free run summaries to OpenAdapt Cloud (OPENADAPT_API_KEY)\n\noptions:\n -h, --help show this help message and exit\n --home HOME OpenAdapt home (default: $OPENADAPT_HOME, else ~/.openadapt)\n\nAlso available as: openadapt-flow inspect ledger\n", "openadapt-flow ledger add": "usage: openadapt-flow ledger add [-h] [--task-type TASK_TYPE] [--task-id TASK_ID]\n [--run-ref RUN_REF] [--approvals APPROVALS] [--config CONFIG]\n run\n\npositional arguments:\n run Run directory (or one run record file)\n\noptions:\n -h, --help show this help message and exit\n --task-type TASK_TYPE\n Operator label, e.g. intake\n --task-id TASK_ID Override the task id\n --run-ref RUN_REF The run's exception-queue reference (exceptions serve --run-ref); its\n cards and answers are read from $OPENADAPT_HOME/exceptions/REF\n --approvals APPROVALS\n A P7 fallback's item-approval folder root (wrap-dispatch --fallback-\n approvals); each gate's request and answer times are read from\n DIR//item-approval\n --config CONFIG The run's guard task JSON or verify.yaml, when not in RUN_DIR; its field\n names may leave in export and push (repeatable)\n\nAlso available as: openadapt-flow inspect ledger add\n", @@ -10482,6 +10483,7 @@ "commands": { "approve": [], "collect": [], + "probe": [], "propose": [] }, "exclusive": [] @@ -10694,6 +10696,251 @@ "commands": {}, "exclusive": [] }, + "openadapt-flow learn probe": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "manifest", + "help": "the generator's manifest.yaml", + "metavar": null, + "nargs": null, + "options": [ + "--manifest" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "kind", + "help": "the kind whose contract frames the probe", + "metavar": null, + "nargs": null, + "options": [ + "--kind" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "values", + "help": "YAML: one task's values for that kind", + "metavar": null, + "nargs": null, + "options": [ + "--values" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "extra", + "help": "YAML: extra parameters (actor ids)", + "metavar": null, + "nargs": null, + "options": [ + "--extra" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "actor", + "help": "the agent's user id in the app", + "metavar": null, + "nargs": null, + "options": [ + "--actor" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "base_url", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--base-url" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "headers_env", + "help": "environment variable holding the agent's request headers as JSON", + "metavar": null, + "nargs": null, + "options": [ + "--headers-env" + ], + "required": false, + "type": null + }, + { + "action": "_AppendAction", + "choices": null, + "default": [], + "dest": "get", + "help": null, + "metavar": "PATH", + "nargs": null, + "options": [ + "--get" + ], + "required": false, + "type": null + }, + { + "action": "_AppendAction", + "choices": null, + "default": [], + "dest": "head", + "help": null, + "metavar": "PATH", + "nargs": null, + "options": [ + "--head" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": 3, + "dest": "rounds", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--rounds" + ], + "required": false, + "type": "int" + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "users", + "help": "TABLE or TABLE.KEY (default: derived)", + "metavar": null, + "nargs": null, + "options": [ + "--users" + ], + "required": false, + "type": null + }, + { + "action": "_AppendAction", + "choices": null, + "default": [], + "dest": "user_column", + "help": null, + "metavar": "TABLE.COLUMN", + "nargs": null, + "options": [ + "--user-column" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "schema", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--schema" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "read", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--read" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": "learn", + "dest": "out", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--out" + ], + "required": false, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "apply", + "help": "write the excuses into every contract the manifest lists", + "metavar": null, + "nargs": 0, + "options": [ + "--apply" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, "openadapt-flow learn propose": { "arguments": [ { From 2144dc5f4da9d07b09ec082228a4a10f0c7f8741 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 19:33:10 -0500 Subject: [PATCH 14/14] docs: refresh command map and llms-full.txt for learn probe --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index f781c4e9a9..1229095270 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -511,7 +511,7 @@ A test fails when a command has no file or this list is out of date. - `flight`: Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its text and PNG/JPEG/GIF/BMP/TIFF/WEBP screenshots before they leave the machine, block other egress on macOS, log its actions, and hold each click that is not known to be safe for a person. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). -- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), 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. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `proxy`: Holds the database credentials, and with `--api` the API credentials, and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof; each API write is sent once under a task-derived key, read back, and checked against the system's own event or audit log. - `readiness`: Shadow a candidate agent or compiled program on tasks a person did, stopped before every save, and write a one-page Readiness Scorecard (matched N of M, risks, field errors, time and cost). diff --git a/llms-full.txt b/llms-full.txt index 0de976f442..1664ff6eec 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -971,7 +971,7 @@ A test fails when a command has no file or this list is out of date. - `flight`: Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its text and PNG/JPEG/GIF/BMP/TIFF/WEBP screenshots before they leave the machine, block other egress on macOS, log its actions, and hold each click that is not known to be safe for a person. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). -- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), 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. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `proxy`: Holds the database credentials, and with `--api` the API credentials, and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof; each API write is sent once under a task-derived key, read back, and checked against the system's own event or audit log. - `readiness`: Shadow a candidate agent or compiled program on tasks a person did, stopped before every save, and write a one-page Readiness Scorecard (matched N of M, risks, field errors, time and cost).