From ad5ecbc8cccece02cbd809dbee4d4d467f1bb6c2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:30:38 -0500 Subject: [PATCH 01/14] feat(verify): draft a write contract with a model, admit it only by qualification openadapt_flow.verify_draft: the pinned model drafts an openadapt.verify/v1 contract from the system description, one trace and the task; the sandbox qualifies it (planted faults, five clean writes, a two-actor by two-payload attribution probe) and feeds failures back, at most three rounds. Prompt frozen here before the untuned app (verify-draft-prompt/1). --- .../flow/benchmark/verify_draft/__init__.py | 0 packages/flow/benchmark/verify_draft/apps.py | 315 ++++++ packages/flow/benchmark/verify_draft/har.py | 48 + packages/flow/benchmark/verify_draft/run.py | 154 +++ .../openadapt_flow/verify_draft/__init__.py | 7 + .../openadapt_flow/verify_draft/__main__.py | 3 + .../flow/openadapt_flow/verify_draft/admit.py | 910 ++++++++++++++++++ .../flow/openadapt_flow/verify_draft/draft.py | 366 +++++++ .../openadapt_flow/verify_draft/inputs.py | 260 +++++ .../flow/openadapt_flow/verify_draft/model.py | 313 ++++++ .../openadapt_flow/verify_draft/sandbox.py | 702 ++++++++++++++ packages/flow/openadapt_flow/verify_run.py | 2 + packages/flow/tests/test_verify_draft.py | 255 +++++ 13 files changed, 3335 insertions(+) create mode 100644 packages/flow/benchmark/verify_draft/__init__.py create mode 100644 packages/flow/benchmark/verify_draft/apps.py create mode 100644 packages/flow/benchmark/verify_draft/har.py create mode 100644 packages/flow/benchmark/verify_draft/run.py create mode 100644 packages/flow/openadapt_flow/verify_draft/__init__.py create mode 100644 packages/flow/openadapt_flow/verify_draft/__main__.py create mode 100644 packages/flow/openadapt_flow/verify_draft/admit.py create mode 100644 packages/flow/openadapt_flow/verify_draft/draft.py create mode 100644 packages/flow/openadapt_flow/verify_draft/inputs.py create mode 100644 packages/flow/openadapt_flow/verify_draft/model.py create mode 100644 packages/flow/openadapt_flow/verify_draft/sandbox.py create mode 100644 packages/flow/tests/test_verify_draft.py diff --git a/packages/flow/benchmark/verify_draft/__init__.py b/packages/flow/benchmark/verify_draft/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/benchmark/verify_draft/apps.py b/packages/flow/benchmark/verify_draft/apps.py new file mode 100644 index 0000000000..d2230c8ece --- /dev/null +++ b/packages/flow/benchmark/verify_draft/apps.py @@ -0,0 +1,315 @@ +"""The three apps the verify-draft benchmark sets up (fixture code, not engine). + +Each ``setup_*`` plays the operator: it brings the app to a seeded state, +records one demonstration as a HAR file, and writes ``task.yaml`` and +``sandbox.yaml``. Everything it writes is a fact a person would supply +(where the app is, how two users sign in, two database connections), never +a judgment about the check. All data is synthetic. + +- **mockloan**: OpenAdapt's MockLoan fault server (SQLite), create a + disbursement. Tuned on before (zero-config benchmark). +- **workbench**: the task-generation workbench's MockMed profile + (PostgreSQL), update a patient's phone and email through HTML forms. + Ours, tuned on before. +- **mealie**: Mealie v2.8.0 (PostgreSQL) on the lab, update a recipe through + its REST API. Nobody had set it up or tuned on it before this benchmark. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Optional + +import requests +import yaml + +from benchmark.verify_draft.har import Recorder + + +@dataclass +class AppRun: + name: str + untuned: bool + describe: str + trace: Path + task: Path + sandbox: Path + #: Held-out probes, chosen by the harness (not the model): other values + #: for clean writes, and another record for an app-level sibling write. + heldout_payloads: list[dict[str, Any]] + other_record: dict[str, Any] + #: Operator inputs the sandbox file holds (facts, not decisions). + operator_inputs: list[str] + teardown: Callable[[], None] = lambda: None + setup_seconds: float = 0.0 + notes: list[str] = field(default_factory=list) + + +def _write(path: Path, data: Any) -> Path: + path.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8") + return path + + +# -- MockLoan ------------------------------------------------------------------- + + +def setup_mockloan(work: Path) -> AppRun: + from openadapt_flow.mockloan import fault_server + + started = time.monotonic() + work.mkdir(parents=True, exist_ok=True) + url, db, stop = fault_server.serve(0) + base = url.rstrip("/") + for loan, prod, amt, memo in [ + ("LN-1001", "Personal", "2500.00", "Seed one"), + ("LN-1002", "Auto", "9100.00", "Seed two"), + ("LN-1003", "Home", "120000.00", "Seed three"), + ]: + requests.post(base + "/api/disbursement", json={"loan_id": loan, "product": prod, "amount": amt, "memo": memo}, timeout=10) + # The demonstration, recorded; then undone so the sandbox starts seeded only. + snapshot = shutil.copy(db.database_path, work / "seeded.sqlite3") + rec = Recorder() + rec.session.get(base + "/api/disbursements", timeout=10) + params = {"loan_id": "LN-2040", "product": "Personal", "amount": "3150.00", "memo": "Kitchen repair advance"} + rec.session.post(base + "/api/disbursement", json=params, timeout=10) + rec.save(work / "trace.har") + shutil.copy(snapshot, db.database_path) + task = _write(work / "task.yaml", { + "instruction": "Authorize a disbursement of 3150.00 on loan LN-2040 (Personal) with the memo 'Kitchen repair advance'.", + "params": params, + }) + sandbox = _write(work / "sandbox.yaml", { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": base}, + "actors": {"agent": {"id": "officer-a"}, "other": {"id": "officer-b"}}, + "store": { + "dialect": "sqlite", + "read": {"sqlite_database": str(db.database_path)}, + "admin": {"sqlite_database": str(db.database_path)}, + }, + }) + return AppRun( + "mockloan", False, "db", work / "trace.har", task, sandbox, + heldout_payloads=[ + {"product": "Auto", "amount": "4420.50", "memo": "Held-out memo A"}, + {"product": "Home", "amount": "77000.00", "memo": "Held-out memo B"}, + {"product": "Personal", "amount": "15.00", "memo": "Held-out memo C"}, + {"product": "Auto", "amount": "999.99", "memo": "Held-out memo D"}, + {"product": "Home", "amount": "5000.00", "memo": "Held-out memo E"}, + ], + other_record={"loan_id": "LN-1002"}, + operator_inputs=["app base URL", "SQLite file path (read and admin)"], + teardown=stop, + setup_seconds=round(time.monotonic() - started, 1), + notes=["MockLoan has no sign-in: the two actors send identical requests"], + ) + + +# -- the workbench (MockMed profile, PostgreSQL) -------------------------------- + + +def _pg_cluster(work: Path, port: int) -> Callable[[], None]: + data = work / "pgdata" + if data.exists(): + shutil.rmtree(data) + subprocess.run(["initdb", "-D", str(data), "-U", "wb_admin", "--auth=trust", "-E", "UTF8", "--locale=C"], check=True, capture_output=True, env={**os.environ, "LC_ALL": "C"}) + subprocess.run( + ["pg_ctl", "-D", str(data), "-o", f"-p {port} -k '' -c listen_addresses=127.0.0.1", "-l", str(work / "pg.log"), "-w", "start"], + check=True, capture_output=True, env={**os.environ, "LC_ALL": "C"}, + ) + for sql in ("CREATE ROLE wb_reader LOGIN", "CREATE DATABASE wb_mockmed"): + subprocess.run(["psql", "-h", "127.0.0.1", "-p", str(port), "-U", "wb_admin", "-d", "postgres", "-c", sql], check=True, capture_output=True) + + def stop() -> None: + subprocess.run(["pg_ctl", "-D", str(data), "-m", "fast", "stop"], capture_output=True) + + return stop + + +WB_SEED = { + "patient": [ + {"mrn": "MRN-1001", "first_name": "Ana", "last_name": "Silva", "dob": "1980-02-11", "phone": "555-0101", "email": "ana.silva@example.org", "_as": "p1"}, + {"mrn": "MRN-1002", "first_name": "Ben", "last_name": "Okafor", "dob": "1975-07-30", "phone": "555-0102", "email": "ben.okafor@example.org", "_as": "p2"}, + {"mrn": "MRN-1003", "first_name": "Chen", "last_name": "Wu", "dob": "1990-12-01", "phone": "555-0103", "email": "chen.wu@example.org", "_as": "p3"}, + ], + "encounter": [ + {"patient_id": "$p1", "type": "Triage", "note": "Seed visit one"}, + {"patient_id": "$p2", "type": "Consult", "note": "Seed visit two"}, + ], +} + + +def setup_workbench(work: Path, port: int = 9796) -> AppRun: + from openadapt_flow.taskgen import workbench as W + from openadapt_flow.taskgen.profile import load_profile + + started = time.monotonic() + work.mkdir(parents=True, exist_ok=True) + stop_pg = _pg_cluster(work, port) + dsn = f"host=127.0.0.1 port={port} user=wb_admin dbname=wb_mockmed" + try: + return _workbench(work, port, dsn, stop_pg, started) + except BaseException: + stop_pg() + raise + + +def _workbench(work: Path, port: int, dsn: str, stop_pg: Callable[[], None], started: float) -> AppRun: + from openadapt_flow.taskgen import workbench as W + from openadapt_flow.taskgen.profile import load_profile + + url, wb, stop_app = W.serve(load_profile("mockmed"), dsn, reader="wb_reader") + wb.store.reset(WB_SEED) + seeded = wb.store.dump() + rec = Recorder() + rec.session.post(url + "/login", data={"username": "clinician", "password": "synthetic"}, allow_redirects=False, timeout=10) + pid = next(r["id"] for r in seeded["patient"] if r["mrn"] == "MRN-1002") + rec.session.get(f"{url}/e/patient/{pid}/edit", timeout=10) + form = {"__version": "1", "first_name": "Ben", "last_name": "Okafor", "dob": "1975-07-30", + "phone": "555-0177", "email": "b.okafor@clinic.example.org"} + rec.session.post(f"{url}/e/patient/{pid}/edit", data=form, allow_redirects=False, timeout=10) + rec.save(work / "trace.har") + wb.store.reset(WB_SEED) # back to the seeded state + task = _write(work / "task.yaml", { + "instruction": "Update patient MRN-1002's phone to 555-0177 and email to b.okafor@clinic.example.org.", + "params": {"mrn": "MRN-1002", "phone": "555-0177", "email": "b.okafor@clinic.example.org"}, + }) + conn = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "127.0.0.1", "port": port, "dbname": "wb_mockmed"}} + sandbox = _write(work / "sandbox.yaml", { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": url}, + "actors": {"agent": {"id": "clinician", "login": {"method": "POST", "path": "/login", + "form": {"username": "clinician", "password": "synthetic"}}}}, + "store": { + "dialect": "postgresql", + "read": {**conn, "sql_connect_args": {**conn["sql_connect_args"], "user": "wb_reader"}}, + "admin": {**conn, "sql_connect_args": {**conn["sql_connect_args"], "user": "wb_admin"}}, + }, + }) + + def teardown() -> None: + stop_app() + wb.store.conn.close() + stop_pg() + + return AppRun( + "workbench", False, "db", work / "trace.har", task, sandbox, + heldout_payloads=[ + {"phone": "555-0901", "email": "heldout.a@example.org"}, + {"phone": "555-0902", "email": "heldout.b@example.org"}, + {"phone": "555-0903", "email": "heldout.c@example.org"}, + {"phone": "555-0904", "email": "heldout.d@example.org"}, + {"phone": "555-0905", "email": "heldout.e@example.org"}, + ], + other_record={}, + operator_inputs=["app base URL", "agent sign-in (user, password)", "read-only DB connection", "admin DB connection"], + teardown=teardown, + setup_seconds=round(time.monotonic() - started, 1), + notes=["the workbench signs in one user only: no second actor, so no lost-update case and no actor axis"], + ) + + +# -- Mealie (untuned, on the lab) ------------------------------------------------ + + +MEALIE = os.environ.get("VD_MEALIE_URL", "http://127.0.0.1:9664") +MEALIE_PG_PORT = int(os.environ.get("VD_MEALIE_PG_PORT", "9665")) + + +def setup_mealie(work: Path) -> AppRun: + """Mealie must be up (fresh volume) at VD_MEALIE_URL with its PostgreSQL + at VD_MEALIE_PG_PORT (the lab stack, tunnelled to loopback).""" + + import psycopg2 + + started = time.monotonic() + work.mkdir(parents=True, exist_ok=True) + os.environ.setdefault("VD_MEALIE_PG_PW", "vd-synthetic-pg") + os.environ.setdefault("VD_MEALIE_READER_PW", "vd-synthetic-reader") + os.environ.setdefault("VD_MEALIE_ADMIN_PW", "MyPassword") + os.environ.setdefault("VD_MEALIE_COOK_PW", "vd-synthetic-cook") + con = psycopg2.connect(host="127.0.0.1", port=MEALIE_PG_PORT, user="mealie", password=os.environ["VD_MEALIE_PG_PW"], dbname="mealie") + con.autocommit = True + cur = con.cursor() + cur.execute("SELECT 1 FROM pg_roles WHERE rolname='vd_reader'") + if not cur.fetchone(): + cur.execute("CREATE ROLE vd_reader LOGIN PASSWORD %s", (os.environ["VD_MEALIE_READER_PW"],)) + cur.execute("GRANT USAGE ON SCHEMA public TO vd_reader") + cur.execute("GRANT SELECT ON ALL TABLES IN SCHEMA public TO vd_reader") + con.close() + + def token(user: str, pw: str) -> dict[str, str]: + r = requests.post(MEALIE + "/api/auth/token", data={"username": user, "password": pw}, timeout=30) + r.raise_for_status() + return {"Authorization": "Bearer " + r.json()["access_token"]} + + admin = token("changeme@example.com", os.environ["VD_MEALIE_ADMIN_PW"]) + me = requests.get(MEALIE + "/api/users/self", headers=admin, timeout=30).json() + users = requests.get(MEALIE + "/api/admin/users?perPage=50", headers=admin, timeout=30).json().get("items", []) + cook = next((u for u in users if u.get("username") == "cook2"), None) + if cook is None: + r = requests.post(MEALIE + "/api/admin/users", headers=admin, timeout=30, json={ + "username": "cook2", "fullName": "Second Cook", "email": "cook2@example.org", + "password": os.environ["VD_MEALIE_COOK_PW"], "group": me["group"], "household": me["household"], + "admin": False, "canInvite": False, "canManage": True, "canOrganize": True, + }) + r.raise_for_status() + cook = r.json() + for name, desc in [("Lentil soup", "Seed recipe one"), ("Rye bread", "Seed recipe two"), ("Plum cake", "Seed recipe three")]: + r = requests.post(MEALIE + "/api/recipes", headers=admin, json={"name": name}, timeout=30) + if r.status_code < 300: + requests.patch(MEALIE + f"/api/recipes/{r.json()}", headers=admin, json={"description": desc, "recipeYield": "4 servings"}, timeout=30) + # The demonstration: one PATCH on lentil-soup, recorded, then undone. + before = requests.get(MEALIE + "/api/recipes/lentil-soup", headers=admin, timeout=30).json() + rec = Recorder(admin) + rec.session.get(MEALIE + "/api/recipes/lentil-soup", timeout=30) + params = {"slug": "lentil-soup", "description": "Red lentils, cumin and lemon. Ready in 40 minutes.", "recipe_yield": "6 bowls"} + rec.session.patch(MEALIE + "/api/recipes/lentil-soup", json={"description": params["description"], "recipeYield": params["recipe_yield"]}, timeout=30) + rec.save(work / "trace.har") + requests.patch(MEALIE + "/api/recipes/lentil-soup", headers=admin, json={"description": before.get("description"), "recipeYield": before.get("recipeYield")}, timeout=30) + (work / "openapi.json").write_text(requests.get(MEALIE + "/openapi.json", timeout=30).text, encoding="utf-8") + task = _write(work / "task.yaml", { + "instruction": "Update the recipe lentil-soup: set its description to 'Red lentils, cumin and lemon. Ready in 40 minutes.' and its yield to '6 bowls'.", + "params": params, + }) + pg = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "127.0.0.1", "port": MEALIE_PG_PORT, "dbname": "mealie"}} + sandbox = _write(work / "sandbox.yaml", { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": MEALIE}, + "actors": { + "agent": {"id": me["id"], "login": {"method": "POST", "path": "/api/auth/token", "token_field": "access_token", + "form": {"username": "changeme@example.com", "password": "${VD_MEALIE_ADMIN_PW}"}}}, + "other": {"id": cook["id"], "login": {"method": "POST", "path": "/api/auth/token", "token_field": "access_token", + "form": {"username": "cook2", "password": "${VD_MEALIE_COOK_PW}"}}}, + }, + "store": { + "dialect": "postgresql", + "read": {**pg, "sql_connect_args": {**pg["sql_connect_args"], "user": "vd_reader"}, "sql_password_env": "VD_MEALIE_READER_PW"}, + "admin": {**pg, "sql_connect_args": {**pg["sql_connect_args"], "user": "mealie"}, "sql_password_env": "VD_MEALIE_PG_PW"}, + }, + }) + return AppRun( + "mealie", True, str(work / "openapi.json"), work / "trace.har", task, sandbox, + heldout_payloads=[ + {"description": "Held-out description A.", "recipe_yield": "2 bowls"}, + {"description": "Held-out description B, with a comma.", "recipe_yield": "8 servings"}, + {"description": "Held-out description C.", "recipe_yield": "1 pot"}, + {"description": "Held-out description D.", "recipe_yield": "3 bowls"}, + {"description": "Held-out description E.", "recipe_yield": "10 servings"}, + ], + other_record={"slug": "rye-bread"}, + operator_inputs=["app base URL", "two users' sign-in (user, password env)", "read-only DB connection", "admin DB connection"], + setup_seconds=round(time.monotonic() - started, 1), + ) + + +SETUPS: dict[str, Callable[[Path], AppRun]] = { + "mockloan": setup_mockloan, + "workbench": setup_workbench, + "mealie": setup_mealie, +} diff --git a/packages/flow/benchmark/verify_draft/har.py b/packages/flow/benchmark/verify_draft/har.py new file mode 100644 index 0000000000..095124f06b --- /dev/null +++ b/packages/flow/benchmark/verify_draft/har.py @@ -0,0 +1,48 @@ +"""Record a scripted HTTP demonstration as a HAR file (the trace input).""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import requests + + +class Recorder: + """A requests.Session whose every exchange becomes a HAR entry.""" + + def __init__(self, headers: dict[str, str] | None = None) -> None: + self.session = requests.Session() + self.session.headers.update(headers or {}) + self.entries: list[dict[str, Any]] = [] + self.session.hooks["response"].append(self._hook) + + def _hook(self, r: requests.Response, *args: Any, **kwargs: Any) -> None: + req = r.request + body = req.body.decode() if isinstance(req.body, bytes) else req.body + mime = req.headers.get("Content-Type", "") + entry: dict[str, Any] = { + "request": { + "method": req.method, + "url": req.url, + # Sign-in material is never kept in the trace file. + "headers": [ + {"name": k, "value": "REDACTED" if k.lower() in ("authorization", "cookie") else v} + for k, v in req.headers.items() + ], + }, + "response": { + "status": r.status_code, + "content": {"mimeType": r.headers.get("Content-Type", ""), "text": r.text[:20000]}, + }, + } + if body is not None: + entry["request"]["postData"] = {"mimeType": mime, "text": body} + self.entries.append(entry) + + def save(self, path: Path) -> None: + path.write_text( + json.dumps({"log": {"version": "1.2", "creator": {"name": "verify-draft-bench"}, "entries": self.entries}}, indent=1), + encoding="utf-8", + ) diff --git a/packages/flow/benchmark/verify_draft/run.py b/packages/flow/benchmark/verify_draft/run.py new file mode 100644 index 0000000000..cbc7473fa4 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/run.py @@ -0,0 +1,154 @@ +"""Run the verify-draft benchmark on one app: set up, draft, hold out. + + cd packages/flow + ANTHROPIC_API_KEY=... python -m benchmark.verify_draft.run mockloan --out benchmark/verify_draft/results/mockloan + +1. The operator setup (``apps.py``), timed on its own. +2. ``openadapt verify draft`` (``openadapt_flow.verify_draft.draft.run``) + with the pinned model: setup minutes, rounds, person decisions, cost. +3. If a contract is admitted, a held-out check with no model: a second + qualification run on harness-chosen values (other clean writes, the + faults planted on other rows with other values), plus app-level faults + the admission suite never plants (the same write sent to another record + through the app; for a create, the write sent twice). + +Person decisions are counted as the draft command counts them (answers to +its one question). The sandbox file's facts are listed as operator inputs, +not decisions, as in the Vikunja setup log the brief compares against. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time +from pathlib import Path +from typing import Any + +import yaml + +from benchmark.verify_draft.apps import SETUPS, AppRun +from openadapt_flow.verify_draft import admit as A +from openadapt_flow.verify_draft import draft as D +from openadapt_flow.verify_draft import model as M +from openadapt_flow.verify_draft.sandbox import App, Store, load_sandbox, swap_map + + +def heldout(run: AppRun, contract_path: Path, work: Path) -> dict[str, Any]: + sandbox = load_sandbox(str(run.sandbox)) + store, app = Store(sandbox.store), App(sandbox) + from openadapt_flow.verify_draft.inputs import load_task, load_trace, writes + + task = load_task(run.task) + base = store.read() + demo = A.record_demo(store, app, writes(load_trace(run.trace), skip_paths=app.login_paths()), task.params, base) + q = A.Qualifier(sandbox, store, app, demo, seed=1, workdir=work) + contract = yaml.safe_load(contract_path.read_text(encoding="utf-8")) + contract.pop("provenance", None) + values = {**task.params, **run.heldout_payloads[-1]} + adm = q.qualify(contract, run.heldout_payloads, base_values=values, attribute=False) + extra: list[A.Case] = [] + if run.other_record: + case = A.Case("fault", "app_sibling", f"the same write also sent to {run.other_record} through the app", "refuted") + + def both(pre: Any, post: Any) -> None: + app.send(demo.writes, "agent", swap_map(demo.params, {**values, **run.other_record})) + + q.run(contract, case, values=values, fault=both) + q._judge(case) + extra.append(case) + if demo.change == "added": + case = A.Case("fault", "app_duplicate", "the write sent twice through the app", "refuted") + + def twice(pre: Any, post: Any) -> None: + app.send(demo.writes, "agent", swap_map(demo.params, values)) + + q.run(contract, case, values=values, fault=twice) + q._judge(case) + extra.append(case) + cases = adm.cases + extra + return { + "cases": [c.as_dict() for c in cases], + "faults_applicable": sum(1 for c in cases if c.group == "fault" and c.applicable), + "faults_caught": sum(1 for c in cases if c.group == "fault" and c.applicable and c.passed), + "faults_missed": [c.name for c in cases if c.group == "fault" and c.applicable and not c.passed], + "clean": sum(1 for c in cases if c.group == "clean"), + "false_stops": [c.name for c in cases if c.group == "clean" and not c.passed], + "problems": adm.problems, + } + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser() + ap.add_argument("app", choices=sorted(SETUPS)) + ap.add_argument("--out", required=True) + ap.add_argument("--spend-ledger", default="benchmark/verify_draft/results/spend.jsonl") + ap.add_argument("--spend-cap-usd", type=float, default=30.0) + args = ap.parse_args(argv) + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + os.environ.setdefault("OPENADAPT_LOCAL_SEAL", "off") + run = SETUPS[args.app](out / "setup") + try: + ledger = M.SpendLedger(Path(args.spend_ledger), args.spend_cap_usd) + drafter = M.ClaudeDrafter(ledger, label=args.app) + started = time.monotonic() + outcome = D.run( + describe=run.describe, + trace_path=str(run.trace), + task_path=str(run.task), + sandbox_path=str(run.sandbox), + out=out / "draft", + drafter=drafter, + ask=None, # the benchmark never answers for a person: a question refuses + log=lambda s: print(f"[{args.app}] {s}", file=sys.stderr, flush=True), + ) + minutes = (time.monotonic() - started) / 60 + rounds = [ + { + "admitted": a.admitted, + "faults_applicable": sum(1 for c in a.cases if c.group == "fault" and c.applicable), + "faults_caught": sum(1 for c in a.cases if c.group == "fault" and c.applicable and c.passed), + "clean": sum(1 for c in a.cases if c.group == "clean"), + "false_stops": [c.name for c in a.cases if c.group == "clean" and not c.passed], + "probe_writes_confirmed": sum(1 for c in a.cases if c.group == "probe" and c.passed), + "attribution_problems": [f"{x.table}.{x.column}: {x.problem}" for x in a.attribution if x.problem], + "not_applicable": {c.name: c.note for c in a.cases if not c.applicable}, + "seconds": a.seconds, + } + for a in outcome.admissions + ] + result: dict[str, Any] = { + "app": run.name, + "untuned": run.untuned, + "describe": "openapi" if run.describe.endswith(".json") else run.describe, + "operator_setup_seconds": run.setup_seconds, + "operator_inputs": run.operator_inputs, + "setup_minutes": round(minutes, 2), + "person_decisions": outcome.decisions, + "questions": outcome.questions, + "drafts": len(outcome.admissions) or outcome.rounds, + "drafts_admitted": sum(1 for a in outcome.admissions if a.admitted), + "drafts_rejected": (len(outcome.admissions) or outcome.rounds) - sum(1 for a in outcome.admissions if a.admitted), + "admitted": outcome.admitted, + "reason": outcome.reason[:2000], + "model": M.MODEL, + "prompt_sha256": M.prompt_sha256(), + "model_usd": round(outcome.usd, 4), + "model_calls": [e for e in ledger.entries], + "rounds": rounds, + "notes": run.notes, + } + if outcome.admitted and outcome.contract_path is not None: + result["heldout"] = heldout(run, outcome.contract_path, out / "heldout-work") + (out / "result.json").write_text(json.dumps(result, indent=1, default=str), encoding="utf-8") + print(json.dumps({k: v for k, v in result.items() if k not in ("model_calls",)}, indent=1, default=str)) + return 0 + finally: + run.teardown() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/openadapt_flow/verify_draft/__init__.py b/packages/flow/openadapt_flow/verify_draft/__init__.py new file mode 100644 index 0000000000..59488121a9 --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/__init__.py @@ -0,0 +1,7 @@ +"""Draft a write contract with a model; admit it only after qualification. + +See :mod:`openadapt_flow.verify_draft.draft` (the command), +:mod:`~openadapt_flow.verify_draft.admit` (the admission suite) and +:mod:`~openadapt_flow.verify_draft.sandbox` (``sandbox.yaml``). The model is +used at setup only; an admitted contract runs with no model calls. +""" diff --git a/packages/flow/openadapt_flow/verify_draft/__main__.py b/packages/flow/openadapt_flow/verify_draft/__main__.py new file mode 100644 index 0000000000..018b116aff --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/__main__.py @@ -0,0 +1,3 @@ +from openadapt_flow.verify_draft.draft import main + +raise SystemExit(main()) diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py new file mode 100644 index 0000000000..0862d13485 --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -0,0 +1,910 @@ +"""Admission by qualification: a drafted contract earns trust or is refused. + +A draft is admitted only when, on the sandbox: + +1. **It refutes every planted fault.** Each case restores the store, takes + the contract's baseline, replays the demonstrated write through the app, + then plants one fault with the privileged connection: + + ================= =================================================== + ``wrong_value`` one written column of the record holds another value + ``wrong_row`` the write landed on another record (an update moved + to a sibling, a create under another parent) + ``duplicate`` a second copy of the record + ``sibling_edit`` another business record edited beside the write + ``late_revert`` the write undone after the check confirmed it; the + recheck must refute + ``lost_update`` (updates) the other user saves the record first and + the agent's save overwrites it, through the app + ================= =================================================== + +2. **It shows no false stop on 5 clean writes** with other values (and the + recheck of each confirms too). + +3. **The causal-attribution probe agrees with its bookkeeping exclusions.** + The write is made by two actors with two payloads (2 x 2, each from a + restored store). Every column that moved is attributed: to the payload + (its value follows the values written), to the actor (it follows who + wrote), or to the clock (it moves every time, to a new value). The + contract must confirm all four writes, must not exclude any column the + payload moves (that would hide the write itself), and must not exclude a + column that never moved (an exclusion with nothing to excuse can only + hide a fault). + +Admission tests run with the contract's recheck window shortened to a few +seconds; the check is otherwise the same, and the admitted contract keeps +its own window. Nothing here calls a model. +""" + +from __future__ import annotations + +import copy +import datetime as _dt +import decimal +import hashlib +import json +import os +import re +import tempfile +import time +import uuid +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Mapping, Optional, Sequence + +from openadapt_flow.verify_draft.sandbox import ( + App, + Move, + Request, + Rows, + SandboxConfig, + Store, + moves, + swap_map, + text, +) + +FAULTS: tuple[str, ...] = ( + "wrong_value", + "wrong_row", + "duplicate", + "sibling_edit", + "late_revert", + "lost_update", +) +CLEAN_PROBES = 5 +#: The recheck window admission cases use. +ADMISSION_RECHECK_S = 2.0 +_FORBIDDEN_KEYS = frozenset( + {"session", "reset", "command", "python", "hook", "hooks", "sql_driver", + "sql_connect_args", "sql_password_env", "sqlite_database", "admission", + "owned_sqlite_insert", "profile", "profile_sha256"} +) +_IDENTIFIER = re.compile(r"(^|_)(id|key|no|number|code|slug|mrn|ref|uuid)$", re.I) + + +class DraftProblem(ValueError): + """The draft can't be run at all (unparseable, unsafe, invalid).""" + + +# -- the contract -------------------------------------------------------------- + + +def _walk(value: Any, path: str = "") -> list[str]: + bad = [] + if isinstance(value, dict): + for k, v in value.items(): + if k in _FORBIDDEN_KEYS: + bad.append(f"{path}{k}") + if isinstance(v, str) and re.fullmatch(r"[\w.]+:[\w]+", v) and k not in ("probe",): + if k in ("driver", "module", "function"): + bad.append(f"{path}{k}") + bad += _walk(v, f"{path}{k}.") + elif isinstance(value, list): + for i, v in enumerate(value): + bad += _walk(v, f"{path}{i}.") + return bad + + +def _reads(value: Any) -> list[dict[str, Any]]: + """Every read section of a contract: dicts that hold a ``sql_query``.""" + + out = [] + if isinstance(value, dict): + if "sql_query" in value: + out.append(value) + for v in value.values(): + out += _reads(v) + elif isinstance(value, list): + for v in value: + out += _reads(v) + return out + + +def prepare(contract_yaml: str, sandbox: SandboxConfig) -> dict[str, Any]: + """Parse a draft, refuse anything unsafe, and point its reads at the + sandbox's read-only connection.""" + + import yaml + + from openadapt_flow.generate.verify_contract import guard_problem + from openadapt_flow.verifier import Contract, VerifierError + + try: + data = yaml.safe_load(contract_yaml) + except yaml.YAMLError as exc: + raise DraftProblem(f"the contract is not valid YAML: {exc}") from exc + if not isinstance(data, dict): + raise DraftProblem("the contract must be a YAML mapping") + data.pop("provenance", None) + bad = _walk(data) + if bad: + raise DraftProblem("the contract may not set " + ", ".join(sorted(set(bad)))) + frame = data.get("frame") or {} + database = frame.get("database") if isinstance(frame, dict) else None + if not isinstance(database, dict): + raise DraftProblem("the contract must diff the whole database (frame.database)") + if database.get("dialect") != sandbox.store.dialect: + raise DraftProblem(f"frame.database.dialect must be {sandbox.store.dialect}") + location = connection(sandbox) + for read in _reads(data): + problem = guard_problem(str(read.get("sql_query") or "")) + if problem: + raise DraftProblem(f"a read is not a plain SELECT: {problem}") + read.update(location) + database["read"] = dict(location) + try: + Contract.from_dict(copy.deepcopy(data), name="draft") + except (VerifierError, ValueError) as exc: + raise DraftProblem(f"the contract does not load: {exc}") from exc + return data + + +def connection(sandbox: SandboxConfig) -> dict[str, Any]: + read = dict(sandbox.store.read) + keys = ("sqlite_database", "sql_driver", "sql_connect_args", "sql_password_env") + return {k: read[k] for k in keys if k in read} + + +def excluded(contract: Mapping[str, Any]) -> dict[str, set[str]]: + """Table -> the columns the contract excuses as bookkeeping (``*`` for a + skipped table).""" + + database = (contract.get("frame") or {}).get("database") or {} + out: dict[str, set[str]] = {} + for entry in database.get("allow_tables") or []: + table = entry if isinstance(entry, str) else entry.get("table") + mode = "append_only" if isinstance(entry, str) else entry.get("mode", "append_only") + out.setdefault(str(table), set()).add("*" if mode == "skip" else "+") + for table, cols in (database.get("ignore_columns") or {}).items(): + out.setdefault(str(table), set()).update(str(c) for c in cols) + return out + + +def check_sha256(contract: Mapping[str, Any]) -> str: + """The fault gate's check digest: effects, read and frame, not where + the store is.""" + + from openadapt_flow.fault_gate import check_digest + from openadapt_flow.verifier import Contract + + data = {k: v for k, v in contract.items() if k != "provenance"} + return check_digest(Contract.from_dict(copy.deepcopy(data), name="draft").config) + + +# -- the demonstration --------------------------------------------------------- + + +@dataclass +class Demo: + """The demonstrated write as the sandbox replays it.""" + + writes: list[Request] + params: dict[str, Any] + base: Rows + after: Rows + main: Optional[Move] + param_columns: dict[str, str] # column -> param + statuses: list[int] = field(default_factory=list) + + @property + def change(self) -> str: + return self.main.change if self.main else "" + + def moved_text(self) -> str: + """What the demonstration moved, for the model: tables, rows and + columns with their values (synthetic sandbox data).""" + + lines = [] + for m in moves(self.base, self.after): + row = m.after if m.after is not None else m.before + cols = m.columns if m.change == "changed" else sorted(row or {}) + vals = { + c: ( + f"{text((m.before or {}).get(c))!r} -> {text((m.after or {}).get(c))!r}" + if m.change == "changed" + else text((row or {}).get(c)) + ) + for c in cols + } + lines.append(f"{m.change} {m.table} key={_keytext(m.key)}: {json.dumps(vals)[:1500]}") + return "\n".join(lines) or "(nothing moved)" + + +def _keytext(key: Any) -> str: + return ",".join(text(k) for k in key) if isinstance(key, tuple) else str(key) + + +def _matches(stored: Any, value: Any) -> bool: + a, b = text(stored).strip(), text(value).strip() + if not b: + return False + if a == b or a.casefold() == b.casefold(): + return True + try: + return decimal.Decimal(a) == decimal.Decimal(b) + except (decimal.InvalidOperation, ValueError): + pass + return len(b) >= 10 and a.startswith(b) # a date read back as a date-time + + +def main_move(found: Sequence[Move], params: Mapping[str, Any]) -> tuple[Optional[Move], dict[str, str]]: + """The added or changed row holding the most task values, and which of + its columns holds which value.""" + + best: tuple[int, Optional[Move], dict[str, str]] = (0, None, {}) + for m in found: + if m.after is None: + continue + cols = {} + for col, stored in m.after.items(): + for name, value in params.items(): + if name == "actor_id": + continue + if _matches(stored, value) and ( + m.change == "added" or col in m.columns + ): + cols[col] = name + break + score = len(set(cols.values())) + if score > best[0]: + best = (score, m, cols) + return best[1], best[2] + + +def record_demo( + store: Store, app: App, writes: list[Request], params: dict[str, Any], base: Rows +) -> Demo: + store.restore(base) + statuses = app.send(writes, "agent", {}) + after = store.read() + found = moves(base, after) + main, cols = main_move(found, params) + store.restore(base) + return Demo(writes, dict(params), base, after, main, cols, statuses) + + +# -- cases --------------------------------------------------------------------- + + +@dataclass +class Case: + group: str # fault | clean | probe + name: str + detail: str + expect: str # confirmed | refuted + outcome: str = "" + recheck: str = "" + passed: bool = False + applicable: bool = True + note: str = "" + reasons: list[str] = field(default_factory=list) + moved: list[dict[str, Any]] = field(default_factory=list) + seconds: float = 0.0 + + def as_dict(self) -> dict[str, Any]: + return dict(self.__dict__) + + def line(self) -> str: + verdict = "ok" if self.passed else ("n/a" if not self.applicable else "FAILED") + got = self.outcome + (f", recheck {self.recheck}" if self.recheck else "") + why = "; ".join(self.reasons[:3]) + if self.moved and not self.passed: + why += ". Moved: " + "; ".join( + f"{m.get('table')} {m.get('change')} {m.get('columns')}" + + (f" ({m.get('attribution')})" if m.get("attribution") else "") + for m in self.moved[:5] + ) + return ( + f"[{verdict}] {self.group} {self.name}: {self.detail}. Expected {self.expect}, got {got or '-'}" + + (f". {self.note}" if self.note else "") + + (f". Reasons: {why}" if why and not self.passed else "") + ) + + +@dataclass +class Attribution: + table: str + column: str + cause: str # payload | actor | clock | constant + excluded: bool + problem: str = "" + + def as_dict(self) -> dict[str, Any]: + return dict(self.__dict__) + + +@dataclass +class Admission: + admitted: bool + check_sha256: str + cases: list[Case] + attribution: list[Attribution] + problems: list[str] + masked: list[dict[str, str]] = field(default_factory=list) + seconds: float = 0.0 + + def as_dict(self) -> dict[str, Any]: + return { + "admitted": self.admitted, + "check_sha256": self.check_sha256, + "problems": self.problems, + "masked": self.masked, + "seconds": self.seconds, + "cases": [c.as_dict() for c in self.cases], + "attribution": [a.as_dict() for a in self.attribution], + } + + def feedback(self) -> str: + lines = [c.line() for c in self.cases if not c.passed and c.applicable] + lines += [ + f"[FAILED] attribution {a.table}.{a.column} ({a.cause}): {a.problem}" + for a in self.attribution + if a.problem + ] + lines += [f"[FAILED] {p}" for p in self.problems] + return "\n".join(lines) + + +def _perturb(value: Any) -> Any: + if isinstance(value, bool): + return not value + if isinstance(value, int): + return value + 7 + if isinstance(value, float): + return value + 1.5 + if isinstance(value, decimal.Decimal): + return value + 1 + if isinstance(value, _dt.datetime): + return value + _dt.timedelta(days=1, hours=1) + if isinstance(value, _dt.date): + return value + _dt.timedelta(days=1) + if isinstance(value, uuid.UUID): + return uuid.uuid4() + if value is None: + return "X" + s = str(value) + if re.fullmatch(r"-?\d+", s): + return str(int(s) + 7) + return s + " X" + + +class Qualifier: + """Runs one draft through the admission suite on the sandbox.""" + + def __init__( + self, + sandbox: SandboxConfig, + store: Store, + app: App, + demo: Demo, + *, + recheck_s: float = ADMISSION_RECHECK_S, + workdir: Optional[Path] = None, + seed: int = 0, + bookkeeping: Sequence[str] = (), + ) -> None: + self.sandbox = sandbox + self.store = store + self.app = app + self.demo = demo + self.recheck_s = recheck_s + self.workdir = workdir or Path(tempfile.mkdtemp(prefix="verify-draft-")) + self.seed = seed + #: ``table.column`` a person said is bookkeeping (the one question). + self.bookkeeping = set(bookkeeping) + self.masked: list[dict[str, str]] = [] + os.environ.setdefault("OPENADAPT_LOCAL_SEAL", "off") + + # -- one write under the contract + + def _params(self, values: Mapping[str, Any], actor: str) -> dict[str, Any]: + out = {k: (None if v is None else text(v)) for k, v in values.items()} + out["actor_id"] = self.sandbox.actor(actor).id + return out + + def _fast(self, contract: Mapping[str, Any]) -> dict[str, Any]: + data = copy.deepcopy(dict(contract)) + data.pop("provenance", None) + db = data["frame"]["database"] + if db.get("recheck_after_s") is not None: + db["recheck_after_s"] = min(float(db["recheck_after_s"]), self.recheck_s) + return data + + def run( + self, + contract: Mapping[str, Any], + case: Case, + *, + values: Mapping[str, Any], + actor: str = "agent", + before: Optional[Callable[[], Optional[str]]] = None, + fault: Optional[Callable[[Rows, Rows], None]] = None, + revert: Optional[Callable[[Rows, Rows], None]] = None, + rechecks: bool = False, + ) -> Optional[tuple[Rows, Rows]]: + """Restore, baseline, write, plant, verify (and recheck). Fills + ``case``; returns (before, after) store reads, or None when the + write itself could not be made.""" + + from openadapt_flow.verifier import ( + Actor, + Contract, + Ledger, + MemoryLedger, + VerifierError, + WriteBlocked, + begin_write, + recheck, + verify_write, + ) + + started = time.monotonic() + try: + data = self._fast(contract) + c = Contract.from_dict(data, name="draft") + params = self._params(values, actor) + self.store.restore(self.demo.base) + ledger = Ledger(MemoryLedger()) + try: + pending = begin_write( + c, + params, + actor=Actor("agent", f"verify-draft-{actor}"), + ledger=ledger, + write_key=uuid.uuid4().hex, + workdir=self.workdir, + ) + except (WriteBlocked, VerifierError) as exc: + case.outcome = "NO_BASELINE" + case.reasons = [str(exc)] + return None + if before is not None: + note = before() + if note: + case.applicable = False + case.note = note + case.passed = True + return None + statuses = self.app.send( + self.demo.writes, actor, swap_map(self.demo.params, values) + ) + if any(s >= 400 for s in statuses): + case.applicable = False + case.note = f"the app refused the write (HTTP {max(statuses)})" + return None + pre = self.demo.base + post = self.store.read() + if fault is not None: + fault(pre, post) + post = self.store.read() + result = verify_write(pending, seal=False) + case.outcome = result.outcome.value + case.reasons = list(result.reasons) + case.moved = list(((result.evidence or {}).get("frame") or {}).get("moves") or [])[:20] + if rechecks and result.outcome.value == "CONFIRMED": + if result.recheck is None: + case.recheck = "NONE" + case.reasons.append( + "no recheck was scheduled: set frame.database.recheck_after_s" + ) + else: + if revert is not None: + revert(pre, post) + rr = recheck(c, result, params=params, actor=Actor("agent", f"verify-draft-{actor}"), wait=True, ledger=ledger) + case.recheck = str(getattr(rr.outcome, "value", rr.outcome)) + case.reasons += list(rr.reasons) + return pre, post + except DraftProblem: + raise + except Exception as exc: # noqa: BLE001 - a broken case is reported, not admitted + case.outcome = case.outcome or "ERROR" + case.reasons.append(f"{type(exc).__name__}: {exc}") + return None + finally: + case.seconds = round(time.monotonic() - started, 2) + + @staticmethod + def _judge(case: Case) -> None: + if not case.applicable: + case.passed = True + return + if case.expect == "confirmed": + case.passed = case.outcome == "CONFIRMED" and case.recheck in ("", "CONFIRMED") + else: + final = case.recheck or case.outcome + case.passed = case.outcome not in ("", "ERROR", "NO_BASELINE") and final != "CONFIRMED" and final != "NONE" + + # -- the suite + + def qualify( + self, + contract: Mapping[str, Any], + payloads: Sequence[Mapping[str, Any]], + *, + faults: Sequence[str] = FAULTS, + clean: int = CLEAN_PROBES, + base_values: Optional[Mapping[str, Any]] = None, + attribute: bool = True, + ) -> Admission: + started = time.monotonic() + self.masked = [] + cases: list[Case] = [] + problems: list[str] = [] + demo = self.demo + if demo.main is None: + problems.append("the demonstration moved no row holding a task value") + return Admission(False, check_sha256(contract), cases, [], problems) + problems += self._pins(contract) + values = [self._values(p) for p in payloads] + values = [v for v in values if v] + + # 1. clean writes, with rechecks + accepted: list[dict[str, Any]] = [] + for i, v in enumerate(values): + if len(accepted) >= clean: + break + case = Case("clean", f"clean-{len(accepted) + 1}", f"the write with payload {i + 1}", "confirmed") + self.run(contract, case, values=v, rechecks=True) + if not case.applicable: + continue # the app refused these values: not a probe + self._judge(case) + cases.append(case) + accepted.append(v) + if len(accepted) < clean: + problems.append( + f"only {len(accepted)} of the payloads were accepted by the app; {clean} clean writes are needed" + ) + + # 2. planted faults + base_values = dict(base_values or demo.params) + for name in faults: + cases += self._fault(contract, name, base_values, accepted) + + # 3. causal attribution (two actors by two payloads) + attribution: list[Attribution] = [] + probe_cases: list[Case] = [] + if attribute: + attribution, probe_cases = self._attribute(contract, [base_values] + accepted[:1]) + cases += probe_cases + self.store.restore(demo.base) # leave the sandbox as it was found + for c in cases: + if c.group != "clean": + self._judge(c) + admitted = ( + not problems + and all(c.passed for c in cases) + and not any(a.problem for a in attribution) + and not self.masked + ) + return Admission( + admitted, + check_sha256(contract), + cases, + attribution, + problems, + list(self.masked), + round(time.monotonic() - started, 2), + ) + + def _pins(self, contract: Mapping[str, Any]) -> list[str]: + """Literals in the effects that pin the demonstrated record: a value + of its row that other rows of its table don't share. Such a check + holds for that one record only.""" + + m = self.demo.main + if m is None: + return [] + rows = list(self.demo.base.get(m.table, {}).values()) + list(self.demo.after.get(m.table, {}).values()) + own = {text(v) for v in (m.before or {}).values()} | {text(v) for v in (m.after or {}).values()} + common = set() + for col in (m.after or {}): + values = {text(r.get(col)) for r in rows} + if len(values) == 1: + common |= values + out = [] + for effect in contract.get("effects") or []: + selectors = [effect.get("match") or {}] + list(effect.get("new_records") or []) + for sel in selectors: + for field_name, expr in sel.items(): + if isinstance(expr, dict) and "literal" in expr: + val = text(expr["literal"]) + if val and val in own and val not in common: + out.append( + f"the effect pins {field_name}={val!r}, a value of the demonstrated " + "record: bind it to a task parameter (or derive it in the read) so the " + "check holds for any record the task names" + ) + return out + + def _values(self, payload: Mapping[str, Any]) -> dict[str, Any]: + out = dict(self.demo.params) + changed = False + for k, v in payload.items(): + if k in out and v is not None and text(v) != text(out[k]): + out[k] = v + changed = True + return out if changed else {} + + # -- fault operators + + def _target(self, pre: Rows, post: Rows, values: Mapping[str, Any]) -> tuple[Optional[Move], dict[str, str]]: + return main_move(moves(pre, post), values) + + def _fault( + self, + contract: Mapping[str, Any], + name: str, + values: dict[str, Any], + accepted: Sequence[Mapping[str, Any]], + ) -> list[Case]: + demo = self.demo + table = demo.main.table if demo.main else "" + out: list[Case] = [] + mask = excluded(contract) + + if name == "wrong_value": + cols = sorted(demo.param_columns)[: 4] or [] + if not cols: + c = Case("fault", "wrong_value", "no written column holds a task value", "refuted", applicable=False) + return [c] + for col in cols: + case = Case("fault", f"wrong_value:{col}", f"{table}.{col} holds another value", "refuted") + + def plant(pre: Rows, post: Rows, col: str = col) -> None: + m, _ = self._target(pre, post, values) + if m is None: + raise RuntimeError("the write moved no row holding a task value") + self.store.update(m.table, m.key, {col: _perturb(m.after[col])}) + + self.run(contract, case, values=values, fault=plant) + out.append(case) + return out + + if name == "wrong_row": + case = Case("fault", "wrong_row", "", "refuted") + + def plant_row(pre: Rows, post: Rows) -> None: + m, cols = self._target(pre, post, values) + if m is None: + raise RuntimeError("the write moved no row holding a task value") + t = self.store.tables[m.table] + if m.change == "changed": + others = [k for k in post[m.table] if k != m.key] + if not others: + raise _NotApplicable("the table holds no other record") + other = others[self.seed % len(others)] + moved = {c: m.after[c] for c in m.columns} + self.store.update(m.table, other, moved) + self.store.update(m.table, m.key, {c: m.before[c] for c in m.columns}) + case.detail = f"the update landed on another {m.table} row" + return + fk = [c for c in m.columns if c in t.fks and m.after.get(c) is not None] + if fk: + col = fk[0] + ref = self.store.tables[t.fks[col]] + choices = [k for k in post.get(ref.name, {}) if len(ref.pk) == 1 and text(k[0]) != text(m.after[col])] + if choices: + self.store.update(m.table, m.key, {col: choices[self.seed % len(choices)][0]}) + case.detail = f"the new {m.table} row points at another {ref.name} ({col})" + return + ids = [c for c, p in cols.items() if _IDENTIFIER.search(c) or _IDENTIFIER.search(p)] + if not ids: + raise _NotApplicable("the new row names no parent record") + self.store.update(m.table, m.key, {ids[0]: _perturb(m.after[ids[0]])}) + case.detail = f"the new {m.table} row is filed under another {ids[0]}" + + self._planted(contract, case, values, plant_row) + return [case] + + if name == "duplicate": + case = Case("fault", "duplicate", f"a second copy of the {table} record", "refuted") + + def plant_dup(pre: Rows, post: Rows) -> None: + m, _ = self._target(pre, post, values) + if m is None: + raise RuntimeError("the write moved no row holding a task value") + self.store.insert(m.table, self.store.new_key_row(m.table, m.after, post)) + + self._planted(contract, case, values, plant_dup) + return [case] + + if name == "sibling_edit": + case = Case("fault", "sibling_edit", "", "refuted") + + def plant_sib(pre: Rows, post: Rows) -> None: + m, _ = self._target(pre, post, values) + order = [m.table] + [t for t in self.store.tables if t != m.table] if m else list(self.store.tables) + hidden: list[str] = [] + for tname in order: + rows = [(k, r) for k, r in post.get(tname, {}).items() if not (m and tname == m.table and k == m.key)] + t = self.store.tables[tname] + for key, row in rows: + for col in t.columns: + if col in t.pk or col in t.fks or row.get(col) is None: + continue + if isinstance(row[col], (bytes, memoryview, dict, list)): + continue + ex = mask.get(tname, set()) + if "*" in ex or col in ex: + if f"{tname}.{col}" not in self.bookkeeping: + hidden.append(f"{tname}.{col}") + continue + if not t.pk: + continue + self.store.update(tname, key, {col: _perturb(row[col])}) + case.detail = f"another {tname} row's {col} edited beside the write" + return + if hidden: + for h in hidden[:3]: + self.masked.append({"fault": "sibling_edit", "column": h}) + raise _NotApplicable( + "every editable column of the other records is excluded: " + ", ".join(hidden[:3]) + ) + raise _NotApplicable("the store holds no other record to edit") + + self._planted(contract, case, values, plant_sib) + return [case] + + if name == "late_revert": + case = Case("fault", "late_revert", f"the {table} write undone after the check", "refuted") + + def undo(pre: Rows, post: Rows) -> None: + m, _ = self._target(pre, post, values) + if m is None: + raise RuntimeError("the write moved no row holding a task value") + if m.change == "added": + self.store.delete(m.table, m.key) + else: + self.store.update(m.table, m.key, {c: m.before[c] for c in m.columns}) + + self.run(contract, case, values=values, revert=undo, rechecks=True) + if case.outcome == "CONFIRMED" and not case.recheck: + case.recheck = "NONE" + return [case] + + if name == "lost_update": + case = Case("fault", "lost_update", "", "refuted") + if demo.change != "changed": + case.applicable, case.note = False, "the write creates a record; nothing can be overwritten" + return [case] + if "other" not in self.sandbox.actors: + case.applicable, case.note = False, "the sandbox has no second user" + return [case] + other_values = accepted[0] if accepted else None + if other_values is None: + case.applicable, case.note = False, "no accepted payload for the other user" + return [case] + + def first_save() -> Optional[str]: + st = self.app.send(demo.writes, "other", swap_map(demo.params, other_values)) + if any(s >= 400 for s in st): + return f"the other user's save was refused (HTTP {max(st)})" + return None + + case.detail = "the other user saves the record, then the agent's save overwrites it" + self.run(contract, case, values=values, before=first_save) + if case.note.startswith("the app refused"): + case.note = "the app refused the stale save: it prevents lost updates itself" + return [case] + raise ValueError(f"unknown fault {name}") + + def _planted(self, contract: Mapping[str, Any], case: Case, values: Mapping[str, Any], plant: Callable[[Rows, Rows], None]) -> None: + def guarded(pre: Rows, post: Rows) -> None: + try: + plant(pre, post) + except _NotApplicable as exc: + case.applicable = False + case.note = str(exc) + raise + + try: + self.run(contract, case, values=values, fault=guarded) + finally: + if not case.applicable: + case.outcome = case.outcome if case.outcome not in ("ERROR",) else "" + case.reasons = [r for r in case.reasons if "_NotApplicable" not in r] + + # -- causal attribution + + def _attribute( + self, contract: Mapping[str, Any], payloads: Sequence[Mapping[str, Any]] + ) -> tuple[list[Attribution], list[Case]]: + actors = ["agent"] + (["other"] if "other" in self.sandbox.actors else []) + if len(payloads) < 2: + return [], [] + runs: dict[tuple[str, int], list[Move]] = {} + cases = [] + for actor in actors: + for i, values in enumerate(payloads[:2]): + case = Case("probe", f"attribution:{actor}:p{i + 1}", f"the write by {actor} with payload {i + 1}", "confirmed") + got = self.run(contract, case, values=values, actor=actor) + cases.append(case) + if got is not None: + runs[(actor, i)] = moves(*got) + # Every (table, column) that moved, with its new value per run. + cells: dict[tuple[str, str], dict[tuple[str, int], str]] = {} + for run, found in runs.items(): + for m in found: + if m.change == "removed": + cells.setdefault((m.table, "-"), {})[run] = "removed" + continue + cols = m.columns if m.change == "changed" else sorted(m.after or {}) + for col in cols: + cells.setdefault((m.table, col), {})[run] = text((m.after or {}).get(col)) + if m.change == "added": + cells.setdefault((m.table, "+"), {})[run] = "added" + mask = excluded(contract) + out: list[Attribution] = [] + for (table, col), seen in sorted(cells.items()): + cause = _cause(seen, actors) + ex = mask.get(table, set()) + is_ex = "*" in ex or col in ex or (col == "+" and "+" in ex) + a = Attribution(table, col, cause, is_ex) + if is_ex and cause == "payload": + a.problem = "excluded, but it moves with the values written: the exclusion hides the write" + out.append(a) + moved = {(a.table, a.column) for a in out} + for table, cols in mask.items(): + for col in cols: + if col == "*" and any(t == table for t, _ in moved): + continue + if col == "+" and (table, "+") in moved: + continue + if (table, col) not in moved and col not in ("*", "+"): + out.append(Attribution(table, col, "never moved", True, "excluded, but it never moved in any probe write: nothing to excuse")) + return out, cases + + +def _cause(seen: Mapping[tuple[str, int], str], actors: Sequence[str]) -> str: + """payload, actor, clock or constant, from the 2 x 2 runs.""" + + by_payload = any( + seen.get((a, 0)) != seen.get((a, 1)) for a in actors if (a, 0) in seen or (a, 1) in seen + ) + by_actor = len(actors) > 1 and any( + seen.get((actors[0], i)) != seen.get((actors[1], i)) for i in (0, 1) + ) + values = [v for v in seen.values()] + if len(set(values)) == len(values) and len(values) == 2 * len(actors) and _clockish(values): + return "clock" + if by_payload and not by_actor: + return "payload" + if by_actor and not by_payload: + return "actor" + if by_payload and by_actor: + # both: a clock or counter, unless the values follow the payload + return "clock" if _clockish(values) else "payload" + return "constant" + + +def _clockish(values: Sequence[str]) -> bool: + return all(re.match(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}", v or "") or re.fullmatch(r"\d{9,}(\.\d+)?", v or "") for v in values) + + +class _NotApplicable(Exception): + pass + + +def digest(value: Any) -> str: + return "sha256:" + hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest() diff --git a/packages/flow/openadapt_flow/verify_draft/draft.py b/packages/flow/openadapt_flow/verify_draft/draft.py new file mode 100644 index 0000000000..77b79862f8 --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/draft.py @@ -0,0 +1,366 @@ +"""``openadapt verify draft``: a model drafts the check, OpenAdapt qualifies it. + + openadapt verify draft --describe openapi.json --trace demo.har \\ + --task task.yaml --sandbox sandbox.yaml --out contracts/update_recipe + +1. The sandbox replays the trace's write once, between two reads of the + store, to see which rows it moves. +2. The pinned model drafts an ``openadapt.verify/v1`` contract from the + system's description, the trace (masked), what the write moved and the + task, plus other valid values to test it with. +3. :mod:`openadapt_flow.verify_draft.admit` qualifies the draft. A failure + goes back to the model with the failing cases, at most 3 rounds in all; + then the command gives up and says why. +4. A person is asked at most once, and only when a column the draft + excludes is the only place a planted fault could go (is it bookkeeping + or business data?). With no answer available the draft is refused. + +Only an admitted contract is written as ``contract.yaml``. Its +``provenance`` section names the model, the prompt digest, the inputs' +digests and the admission's check digest; an edit to the check after +admission no longer matches (:func:`admission_problem`). Running the +contract makes no model calls. +""" + +from __future__ import annotations + +import argparse +import copy +import datetime as _dt +import hashlib +import json +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Mapping, Optional, Sequence + +import yaml + +from openadapt_flow.verify_draft import admit as A +from openadapt_flow.verify_draft import inputs as I +from openadapt_flow.verify_draft import model as M +from openadapt_flow.verify_draft.sandbox import App, SandboxConfig, Store, load_sandbox + +MAX_ROUNDS = 3 +SUITE = "openadapt.verify-draft-admission/v1" + + +def _sha(data: bytes) -> str: + return "sha256:" + hashlib.sha256(data).hexdigest() + + +@dataclass +class Outcome: + admitted: bool + rounds: int + decisions: int + seconds: float + usd: float + reason: str + contract_path: Optional[Path] = None + admissions: list[A.Admission] = field(default_factory=list) + questions: list[str] = field(default_factory=list) + + def as_dict(self) -> dict[str, Any]: + return { + "admitted": self.admitted, + "rounds": self.rounds, + "person_decisions": self.decisions, + "seconds": self.seconds, + "model_usd": round(self.usd, 4), + "reason": self.reason, + "contract": str(self.contract_path) if self.contract_path else None, + "questions": self.questions, + } + + +Asker = Callable[[str, Sequence[str]], Optional[Mapping[str, str]]] + + +def first_message(task: I.Task, desc: I.Description, trace: list[Any], demo: A.Demo, dialect: str) -> str: + writes = [I.masked(r) for r in demo.writes] + return "\n\n".join( + [ + f"Task: {task.instruction}", + "Task parameters (the values the demonstration used):\n" + + json.dumps(task.params, indent=1, default=str), + f"Store dialect: {dialect}", + f"System description ({desc.kind}):\n{desc.text or '(none given)'}", + "The demonstration's write requests (sign-in and secrets masked):\n" + + json.dumps(writes, indent=1)[:20000], + "What the write moved in the database (replayed once in the sandbox; " + "synthetic data):\n" + demo.moved_text()[:20000], + "Write the contract for this task.", + ] + ) + + +def run( + *, + describe: Optional[str], + trace_path: str, + task_path: str, + sandbox_path: str, + out: Path, + drafter: M.Drafter, + rounds: int = MAX_ROUNDS, + ask: Optional[Asker] = None, + log: Callable[[str], None] = lambda s: None, +) -> Outcome: + started = time.monotonic() + out.mkdir(parents=True, exist_ok=True) + sandbox = load_sandbox(sandbox_path) + task = I.load_task(task_path) + trace = I.load_trace(trace_path) + store = Store(sandbox.store) + app = App(sandbox) + desc = I.load_description(describe, schema_text=store.schema_text()) + writes = I.writes(trace, skip_paths=app.login_paths()) + if not writes: + raise I.InputError("the trace holds no write request") + base = store.read() + log(f"store: {len(store.tables)} tables; trace: {len(writes)} write request(s)") + demo = A.record_demo(store, app, writes, task.params, base) + if demo.main is None or any(s >= 400 for s in demo.statuses): + return _finish( + out, started, Outcome(False, 0, 0, 0.0, 0.0, + f"replaying the trace moved no row holding a task value (HTTP {demo.statuses})"), + [], + ) + log(f"demonstration: {demo.change} {demo.main.table}, columns {sorted(demo.param_columns)}") + qualifier = A.Qualifier(sandbox, store, app, demo, workdir=out / "work") + messages: list[dict[str, Any]] = [ + {"role": "user", "content": first_message(task, desc, trace, demo, sandbox.store.dialect)} + ] + usd = 0.0 + decisions = 0 + asked = False + questions: list[str] = [] + admissions: list[A.Admission] = [] + reason = "" + contract: Optional[dict[str, Any]] = None + draft: Optional[M.Draft] = None + used = 0 + while used < rounds: + used += 1 + draft = drafter.draft(messages) + usd += draft.call.usd if draft.call else 0.0 + messages.append({"role": "assistant", "content": draft.raw or json.dumps( + {"contract_yaml": draft.contract_yaml, "payloads": draft.payloads, "notes": draft.notes})}) + (out / "rounds").mkdir(exist_ok=True) + (out / "rounds" / f"round-{used}.yaml").write_text(draft.contract_yaml or "", encoding="utf-8") + try: + contract = A.prepare(draft.contract_yaml, sandbox) + except A.DraftProblem as exc: + reason = str(exc) + log(f"round {used}: draft refused before testing: {reason}") + messages.append({"role": "user", "content": f"The contract could not be tested: {reason}\nFix it and answer with the same JSON object."}) + continue + adm = qualifier.qualify(contract, draft.payloads) + if adm.masked and not asked and ask is not None: + columns = sorted({m["column"] for m in adm.masked}) + question = ( + "The draft excludes these columns, and a planted fault could only go there: " + + ", ".join(columns) + + ". Are they bookkeeping the app sets on its own (bookkeeping), or data people edit (business)?" + ) + questions.append(question) + asked = True + answers = ask(question, columns) + if answers is not None: + decisions += 1 + keep = [c for c, a in answers.items() if str(a).lower().startswith("book")] + qualifier.bookkeeping.update(keep) + if set(keep) >= set(columns): + adm = qualifier.qualify(contract, draft.payloads) + admissions.append(adm) + (out / "rounds" / f"round-{used}.admission.json").write_text( + json.dumps(adm.as_dict(), indent=1, default=str), encoding="utf-8" + ) + passed = sum(c.passed for c in adm.cases) + log(f"round {used}: {'ADMITTED' if adm.admitted else 'rejected'} ({passed}/{len(adm.cases)} cases, {adm.seconds:.0f}s)") + if adm.admitted: + break + reason = adm.feedback() + messages.append( + { + "role": "user", + "content": "Admission failed. These cases did not behave as required:\n" + + reason + + "\nFix the contract (and the payloads if the app refused them). Answer with the same JSON object.", + } + ) + admitted = bool(admissions and admissions[-1].admitted) + outcome = Outcome( + admitted, used, decisions, 0.0, usd, + "admitted" if admitted else f"refused after {used} round(s): {reason}", + admissions=admissions, questions=questions, + ) + if admitted and contract is not None and draft is not None: + adm = admissions[-1] + contract = dict(contract) + contract["provenance"] = provenance( + draft, adm, used, describe, desc, trace_path, task_path, qualifier + ) + path = out / "contract.yaml" + path.write_text( + "# Drafted by a model and admitted by OpenAdapt qualification " + "(openadapt verify draft). Runs make no model calls.\n" + + yaml.safe_dump(contract, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + outcome.contract_path = path + return _finish(out, started, outcome, admissions) + + +def _finish(out: Path, started: float, outcome: Outcome, admissions: list[A.Admission]) -> Outcome: + outcome.seconds = round(time.monotonic() - started, 1) + (out / "report.json").write_text( + json.dumps( + { + **outcome.as_dict(), + "rounds_detail": [ + { + "admitted": a.admitted, + "cases": len(a.cases), + "passed": sum(c.passed for c in a.cases), + "failed": [c.name for c in a.cases if not c.passed], + "problems": a.problems, + "attribution_problems": [f"{x.table}.{x.column}" for x in a.attribution if x.problem], + } + for a in admissions + ], + }, + indent=1, + ), + encoding="utf-8", + ) + return outcome + + +def provenance( + draft: M.Draft, + adm: A.Admission, + rounds: int, + describe: Optional[str], + desc: I.Description, + trace_path: str, + task_path: str, + qualifier: A.Qualifier, +) -> dict[str, Any]: + faults = [c for c in adm.cases if c.group == "fault"] + return { + "drafted_by": { + "model": M.MODEL, + "response_model": draft.call.response_model if draft.call else "", + "effort": M.EFFORT, + "prompt_version": M.PROMPT_VERSION, + "prompt_sha256": M.prompt_sha256(), + }, + "inputs": { + "description": { + "kind": desc.kind, + "file_sha256": _sha(Path(describe).read_bytes()) if describe and Path(describe).is_file() else None, + "text_sha256": _sha(desc.text.encode("utf-8")), + }, + "trace_sha256": _sha(Path(trace_path).read_bytes()), + "task_sha256": _sha(Path(task_path).read_bytes()), + }, + "admission": { + "suite": SUITE, + "check_sha256": adm.check_sha256, + "rounds": rounds, + "admitted_at": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "recheck_window_tested_s": qualifier.recheck_s, + "faults": { + c.name: ("refuted" if c.passed else "missed") if c.applicable else f"not applicable: {c.note}" + for c in faults + }, + "clean_writes_confirmed": sum(c.passed for c in adm.cases if c.group == "clean"), + "attribution_probe_writes": sum(c.passed for c in adm.cases if c.group == "probe"), + "bookkeeping_confirmed_by_person": sorted(qualifier.bookkeeping), + }, + } + + +def admission_problem(path: str | Path) -> Optional[str]: + """None when the contract at ``path`` is still the check that was + admitted; else why not.""" + + data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {} + prov = (data.get("provenance") or {}).get("admission") or {} + if prov.get("suite") != SUITE: + return "no admission record" + if A.check_sha256(data) != prov.get("check_sha256"): + return "the check changed after admission" + return None + + +# -- the command --------------------------------------------------------------- + + +def _ask_from(answers_path: Optional[str], interactive: bool) -> Optional[Asker]: + if answers_path: + given = yaml.safe_load(Path(answers_path).read_text(encoding="utf-8")) or {} + + def from_file(question: str, columns: Sequence[str]) -> Optional[Mapping[str, str]]: + got = {c: str(given[c]) for c in columns if c in given} + return got if len(got) == len(columns) else None + + return from_file + if interactive and sys.stdin.isatty(): + + def from_tty(question: str, columns: Sequence[str]) -> Optional[Mapping[str, str]]: + print(question, file=sys.stderr) + out = {} + for c in columns: + out[c] = input(f"{c} [bookkeeping/business]: ").strip() or "business" + return out + + return from_tty + return None + + +def main(argv: Optional[list[str]] = None) -> int: + ap = argparse.ArgumentParser( + prog="openadapt verify draft", + description="Draft a write contract with a model and admit it only if OpenAdapt qualifies it.", + allow_abbrev=False, + ) + ap.add_argument("--describe", default="none", + help="OpenAPI, GraphQL or FHIR CapabilityStatement file; 'db' for the sandbox's database schema; or 'none'") + ap.add_argument("--trace", required=True, help="HAR file of one correct demonstration") + ap.add_argument("--task", required=True, help="task.yaml: instruction and the demonstration's params") + ap.add_argument("--sandbox", required=True, help="sandbox.yaml (openadapt.verify-sandbox/v1)") + ap.add_argument("--out", required=True, help="output folder") + ap.add_argument("--rounds", type=int, default=MAX_ROUNDS, choices=range(1, MAX_ROUNDS + 1)) + ap.add_argument("--answers", help="answers to the one question (table.column: bookkeeping|business)") + ap.add_argument("--no-input", action="store_true", help="never ask; refuse instead") + ap.add_argument("--spend-ledger", default=str(Path.home() / ".openadapt" / "verify-draft" / "spend.jsonl")) + ap.add_argument("--spend-cap-usd", type=float, default=30.0) + ap.add_argument("--check", metavar="CONTRACT", help="only check that CONTRACT is still the admitted check") + args = ap.parse_args(argv) + if args.check: + problem = admission_problem(args.check) + print(problem or "admitted check, unchanged") + return 1 if problem else 0 + ledger = M.SpendLedger(Path(args.spend_ledger), args.spend_cap_usd) + drafter = M.ClaudeDrafter(ledger, label=Path(args.out).name) + outcome = run( + describe=args.describe, + trace_path=args.trace, + task_path=args.task, + sandbox_path=args.sandbox, + out=Path(args.out), + drafter=drafter, + rounds=args.rounds, + ask=_ask_from(args.answers, not args.no_input), + log=lambda s: print(s, file=sys.stderr), + ) + print(json.dumps(outcome.as_dict(), indent=1)) + return 0 if outcome.admitted else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/openadapt_flow/verify_draft/inputs.py b/packages/flow/openadapt_flow/verify_draft/inputs.py new file mode 100644 index 0000000000..160c26a041 --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/inputs.py @@ -0,0 +1,260 @@ +"""What the model drafts from: the system's description, one trace, the task. + +- **Description**: an OpenAPI (or Swagger) document, a GraphQL schema (SDL + text or an introspection result), a FHIR CapabilityStatement, the + database schema read from the sandbox (``db``), or none. Each is cut down + to the parts a check needs (paths and bodies, types and fields, + resources and interactions, tables and keys). +- **Trace**: a HAR file of one correct demonstration. The writes in it are + what the sandbox replays; sign-in headers and secret-looking fields are + masked before anything is sent to the model. +- **Task**: ``task.yaml`` with the instruction and the values the + demonstration used (``params``). +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.verify_draft.sandbox import Request + +#: Longest description text sent to the model. +MAX_DESCRIPTION_CHARS = 40_000 +_SECRET = re.compile(r"pass(word)?|secret|token|api[-_]?key|session|csrf|auth", re.I) +_SECRET_HEADERS = frozenset( + {"authorization", "cookie", "set-cookie", "x-api-key", "x-csrf-token", "proxy-authorization"} +) +_READS = frozenset({"GET", "HEAD", "OPTIONS"}) + + +class InputError(ValueError): + """An input can't be read; the message says why.""" + + +@dataclass +class Description: + kind: str # openapi | graphql | fhir | database | none + text: str + source: str = "" + + +@dataclass +class Task: + instruction: str + params: dict[str, Any] + + +def load_task(path: str | Path) -> Task: + import yaml + + data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {} + if not isinstance(data, dict) or not isinstance(data.get("params"), dict): + raise InputError("task.yaml needs instruction and params") + params = dict(data["params"]) + if "actor_id" in params: + raise InputError("actor_id is reserved: the sandbox binds it") + return Task(str(data.get("instruction") or ""), params) + + +# -- description --------------------------------------------------------------- + + +def _load_doc(path: Path) -> Any: + raw = path.read_text(encoding="utf-8") + try: + return json.loads(raw) + except ValueError: + pass + try: + import yaml + + doc = yaml.safe_load(raw) + if isinstance(doc, (dict, list)): + return doc + except Exception: # noqa: BLE001 - SDL is neither + pass + return raw + + +def load_description(source: Optional[str], *, schema_text: str = "") -> Description: + """``source``: a file, ``db`` (the sandbox's introspected schema), or + None / ``none``.""" + + if source in (None, "", "none"): + return Description("none", "", "none") + if source == "db": + return Description("database", schema_text[:MAX_DESCRIPTION_CHARS], "db") + path = Path(source) + if not path.is_file(): + raise InputError(f"description {source} is not a file") + doc = _load_doc(path) + if isinstance(doc, dict) and ("openapi" in doc or "swagger" in doc): + return Description("openapi", _openapi(doc), path.name) + if isinstance(doc, dict) and doc.get("resourceType") == "CapabilityStatement": + return Description("fhir", _fhir(doc), path.name) + if isinstance(doc, dict) and ("__schema" in doc or "__schema" in (doc.get("data") or {})): + return Description("graphql", _graphql(doc.get("data", doc)["__schema"]), path.name) + if isinstance(doc, str) and re.search(r"\b(type|schema|input)\s+\w+\s*\{", doc): + return Description("graphql", doc[:MAX_DESCRIPTION_CHARS], path.name) + raise InputError( + f"{source}: not an OpenAPI document, a GraphQL schema or a FHIR CapabilityStatement" + ) + + +def _ref(schema: Any) -> str: + if not isinstance(schema, dict): + return "" + if "$ref" in schema: + return schema["$ref"].rsplit("/", 1)[-1] + if schema.get("type") == "array": + return f"[{_ref(schema.get('items'))}]" + for key in ("allOf", "anyOf", "oneOf"): + if key in schema: + return "|".join(_ref(s) for s in schema[key] if _ref(s)) + return str(schema.get("type", "")) + + +def _openapi(doc: dict) -> str: + lines = [f"# {doc.get('info', {}).get('title', 'API')} {doc.get('info', {}).get('version', '')}"] + for path, ops in (doc.get("paths") or {}).items(): + for method, op in (ops or {}).items(): + if not isinstance(op, dict) or method.startswith("x-") or method == "parameters": + continue + body = "" + content = ((op.get("requestBody") or {}).get("content") or {}) + for mime, media in content.items(): + body = f" body={_ref(media.get('schema'))} ({mime})" + break + params = ",".join(p.get("name", "") for p in op.get("parameters") or [] if isinstance(p, dict)) + lines.append( + f"{method.upper()} {path}{body}" + + (f" params={params}" if params else "") + + (f" -- {op.get('summary')}" if op.get("summary") else "") + ) + schemas = (doc.get("components") or {}).get("schemas") or doc.get("definitions") or {} + lines.append("# schemas") + for name, schema in schemas.items(): + props = (schema or {}).get("properties") or {} + fields = ", ".join(f"{k}:{_ref(v)}" for k, v in props.items()) + lines.append(f"{name}{{{fields}}}") + return "\n".join(lines)[:MAX_DESCRIPTION_CHARS] + + +def _fhir(doc: dict) -> str: + lines = [f"# FHIR {doc.get('fhirVersion', '')}"] + for rest in doc.get("rest") or []: + for res in rest.get("resource") or []: + inter = ",".join(i.get("code", "") for i in res.get("interaction") or []) + search = ",".join(s.get("name", "") for s in res.get("searchParam") or []) + lines.append(f"{res.get('type')}: {inter}" + (f" search={search}" if search else "")) + return "\n".join(lines)[:MAX_DESCRIPTION_CHARS] + + +def _graphql(schema: dict) -> str: + lines = [] + for t in schema.get("types") or []: + if str(t.get("name", "")).startswith("__"): + continue + fields = ", ".join(f.get("name", "") for f in t.get("fields") or [] if isinstance(f, dict)) + if fields: + lines.append(f"{t.get('kind', '').lower()} {t['name']} {{{fields}}}") + return "\n".join(lines)[:MAX_DESCRIPTION_CHARS] + + +# -- trace --------------------------------------------------------------------- + + +def load_trace(path: str | Path) -> list[Request]: + try: + doc = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise InputError(f"trace {path}: {exc}") from exc + entries = ((doc or {}).get("log") or {}).get("entries") + if not isinstance(entries, list): + raise InputError("the trace is a HAR file (log.entries)") + out = [] + for e in entries: + req = e.get("request") or {} + post = req.get("postData") or {} + body = post.get("text") + if body is None and post.get("params"): + from urllib.parse import urlencode + + body = urlencode([(p["name"], p.get("value", "")) for p in post["params"]]) + res = e.get("response") or {} + out.append( + Request( + method=str(req.get("method", "GET")).upper(), + url=str(req.get("url", "")), + headers={h["name"]: h.get("value", "") for h in req.get("headers") or []}, + body=body, + mime=str(post.get("mimeType") or ""), + status=res.get("status"), + response=((res.get("content") or {}).get("text")), + ) + ) + return out + + +def writes(trace: list[Request], *, skip_paths: set[str] = frozenset()) -> list[Request]: # type: ignore[assignment] + """The trace's write requests (anything but GET, HEAD and OPTIONS), + without sign-in requests.""" + + return [r for r in trace if r.method not in _READS and r.path not in skip_paths] + + +def _mask_json(value: Any) -> Any: + if isinstance(value, dict): + return { + k: ("***" if _SECRET.search(str(k)) and not isinstance(v, (dict, list)) else _mask_json(v)) + for k, v in value.items() + } + if isinstance(value, list): + return [_mask_json(v) for v in value] + return value + + +def _mask_body(body: Optional[str], mime: str) -> Optional[str]: + if body is None: + return None + if "json" in mime: + try: + return json.dumps(_mask_json(json.loads(body))) + except ValueError: + return "***" + if "x-www-form-urlencoded" in mime: + from urllib.parse import parse_qsl, urlencode + + return urlencode( + [(k, "***" if _SECRET.search(k) else v) for k, v in parse_qsl(body, keep_blank_values=True)] + ) + return body[:2000] + + +def masked(req: Request, *, response_chars: int = 1500) -> dict[str, Any]: + """One request as the model sees it: no sign-in headers, no secret + fields, a short response.""" + + from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + + parts = urlsplit(req.url) + query = urlencode( + [(k, "***" if _SECRET.search(k) else v) for k, v in parse_qsl(parts.query, keep_blank_values=True)] + ) + response = req.response + if response is not None: + response = _mask_body(response, "json" if response.lstrip()[:1] in "{[" else "text") + return { + "method": req.method, + "url": urlunsplit(("", "", parts.path, query, "")), + "headers": { + k: v for k, v in req.headers.items() if k.lower() not in _SECRET_HEADERS and not _SECRET.search(k) + }, + "body": _mask_body(req.body, req.mime), + "status": req.status, + "response": (response or "")[:response_chars] or None, + } diff --git a/packages/flow/openadapt_flow/verify_draft/model.py b/packages/flow/openadapt_flow/verify_draft/model.py new file mode 100644 index 0000000000..f34cd57353 --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/model.py @@ -0,0 +1,313 @@ +"""The model that drafts a contract: pinned model, pinned prompt, spend ledger. + +This module is the only place in the draft path that talks to a model, and +nothing on the run path imports it: an admitted contract is plain +``openadapt.verify/v1`` data, judged by the deterministic verifier. + +The model and the prompt are pinned. Each draft records the model id the +request named, the model id the response reports, the prompt's version and +SHA-256, the token counts and the estimated cost, in the contract's +``provenance`` section. The key comes from ``ANTHROPIC_API_KEY`` in the +environment only and is never written or printed. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Optional, Protocol + +#: The pinned model. A change here is a new prompt version too. +MODEL = "claude-opus-5-5" +EFFORT = "medium" +MAX_TOKENS = 32_000 +#: USD per million tokens for MODEL (input, output, cache read, cache write). +PRICE_PER_MTOK = {"input": 4.0, "output": 20.0, "cache_read": 0.2, "cache_write": 5.0} +PROMPT_VERSION = "verify-draft-prompt/1" + +SYSTEM_PROMPT = """\ +You write record checks for OpenAdapt. A record check is an `openadapt.verify/v1` +contract: after an agent writes to a system of record, OpenAdapt reads the +system's own database and decides whether exactly the intended write landed. +Your check will be tested before anyone trusts it: OpenAdapt plants faults in a +sandbox copy (a wrong value in a written field, the write on the wrong record, +a duplicate record, an edit to a sibling business record, the write reverted +after the check, another user's save lost under the agent's save) and replays +clean writes as two different users with different values. It is admitted only +if it refutes every fault and confirms every clean write. At run time it makes +no model calls, so everything it needs must be in the contract. + +Write the contract in YAML with this shape. Leave out every connection key +(sql_driver, sql_connect_args, sql_password_env, sqlite_database): OpenAdapt +fills them in. Never write session, reset, command, python or hook keys. + +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: # one read per surface; plain SELECTs only + kind: sql + sql_query: SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."name" AS TEXT) AS "name", ... FROM "table" t +effects: +- kind: record_written # a record matching `match` must exist expected_count times + probe: surface=record|what this checks, in a few words + match: + name: {param: name} # a task value; or {literal: "x"} for a fixed value + expected_count: 1 + count_new_only: true # only for a write that CREATES the record +frame: + identity_field: id # how rows of the surfaces are told apart + target_fields_by_surface: # columns a pre-existing declared row may change + record: [name, ...] + database: # the whole database is diffed before and after + dialect: postgresql # or sqlite, mysql + allow_tables: # tables the app writes on its own on every request + - {table: audit_log, mode: append_only, reason: why} # or mode: skip + ignore_columns: # columns that change on their own (bookkeeping) + users: [last_login] + views: {table: surface} # the surface reads this table's own columns, no join + judged_by: {table: surface} # the surface may join; its id is the table's primary key + new_row_fields: # for created rows: columns set beyond the matched ones + table: [id, created_at] + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 # read the whole database again this long after + versions: # only when the store keeps one row per saved version + read: {kind: sql, sql_query: SELECT ... AS id, ... AS ver, ... AS author FROM ...} + record_field: id + target_field: id + target_surface: record + version_field: ver + author_field: author # optional: who saved each version + self: [{param: actor_id}] + +Rules: +- Read every column as text: CAST(col AS TEXT) AS "col". Match values are + compared as text. Use the task's parameter names in {param: ...}; the + acting user's id is always available as {param: actor_id}. +- Every row the write adds or changes anywhere in the database must be + explained: by a declared effect (its surface, `views`/`judged_by`, + `target_fields_by_surface`, `new_row_fields`), or as bookkeeping + (`allow_tables`, `ignore_columns`). Anything else refutes the write, which + is what catches a sibling edit. Exclude a column only when it changes on + every request regardless of the values written (a clock, a counter, the + acting user's last-seen time). Never exclude a column that holds a value + the task writes. +- How a table's moved row counts as declared: with `views`, the effect's + match fields must all be columns of that table. When the match needs a + value from another table (an audit row tied to the record's business key), + read it with a join, select the table's primary key as the surface's + identity field, and use `judged_by` for that table instead of `views`. +- Choose match columns so a write on the wrong record, a wrong value or a + second copy changes the count. +- The check must hold for any record the task names, not only the + demonstrated one: never write a value of the demonstrated record (its id, + its name, its other fields) as a literal. Bind it to a task parameter, or + join to it in the read (for example an audit row's record id joined to the + record's own key). +- Always set recheck_after_s so a write reverted after the check is caught. +- For an update of an existing record, catch a lost update: if the store + keeps an audit or version row per save, declare frame.versions (with the + author when the store records it), or count the save's own audit row as an + effect and let the frame refute any other. + +Answer with one JSON object: +{"contract_yaml": "", + "payloads": [ [{"param": "", "value": ""}, ...], ... ], + "notes": ""} +`payloads` are 8 other valid sets of the task's VALUE parameters (not the +parameters that pick the record), each different from the demonstration and +from each other, in the formats the app accepts. OpenAdapt replays the +demonstrated write with them. +""" + +#: The JSON object the model must return. +OUTPUT_SCHEMA = { + "type": "object", + "properties": { + "contract_yaml": {"type": "string"}, + "payloads": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "object", + "properties": {"param": {"type": "string"}, "value": {"type": "string"}}, + "required": ["param", "value"], + "additionalProperties": False, + }, + }, + }, + "notes": {"type": "string"}, + }, + "required": ["contract_yaml", "payloads", "notes"], + "additionalProperties": False, +} + + +def prompt_sha256() -> str: + payload = json.dumps( + { + "version": PROMPT_VERSION, + "system": SYSTEM_PROMPT, + "schema": OUTPUT_SCHEMA, + "model": MODEL, + "effort": EFFORT, + }, + sort_keys=True, + ) + return "sha256:" + hashlib.sha256(payload.encode()).hexdigest() + + +class BudgetExceeded(RuntimeError): + """The spend ledger's cap would be passed; no request was sent.""" + + +@dataclass +class Call: + request_model: str + response_model: str + input_tokens: int + output_tokens: int + cache_read_tokens: int + cache_write_tokens: int + usd: float + seconds: float + request_id: str = "" + stop_reason: str = "" + + def as_dict(self) -> dict[str, Any]: + return dict(self.__dict__) + + +@dataclass +class Draft: + contract_yaml: str + payloads: list[dict[str, Any]] + notes: str + call: Optional[Call] = None + raw: str = "" + + +class Drafter(Protocol): + def draft(self, messages: list[dict[str, Any]]) -> Draft: ... + + +def cost(usage: Any) -> float: + def n(name: str) -> int: + return int(getattr(usage, name, 0) or 0) + + return ( + n("input_tokens") * PRICE_PER_MTOK["input"] + + n("output_tokens") * PRICE_PER_MTOK["output"] + + n("cache_read_input_tokens") * PRICE_PER_MTOK["cache_read"] + + n("cache_creation_input_tokens") * PRICE_PER_MTOK["cache_write"] + ) / 1_000_000 + + +@dataclass +class SpendLedger: + """Every model call's cost, appended to a JSONL file. Refuses a call + when the total has reached ``cap_usd`` minus the worst case of one call.""" + + path: Path + cap_usd: float + #: The most one call can cost: MAX_TOKENS of output plus a long prompt. + worst_call_usd: float = MAX_TOKENS * PRICE_PER_MTOK["output"] / 1e6 + 0.5 + entries: list[dict[str, Any]] = field(default_factory=list) + + def total(self) -> float: + if not self.path.is_file(): + return 0.0 + return sum( + float(json.loads(line).get("usd", 0)) + for line in self.path.read_text(encoding="utf-8").splitlines() + if line.strip() + ) + + def check(self) -> None: + spent = self.total() + if spent + self.worst_call_usd > self.cap_usd: + raise BudgetExceeded( + f"model spend {spent:.2f} USD plus one more call could pass the " + f"{self.cap_usd:.2f} USD cap" + ) + + def add(self, call: Call, label: str) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + entry = {"at": time.time(), "label": label, **call.as_dict()} + with self.path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(entry) + "\n") + self.entries.append(entry) + + +class ClaudeDrafter: + """The pinned model through the Anthropic SDK.""" + + def __init__(self, ledger: SpendLedger, label: str = "") -> None: + if not os.environ.get("ANTHROPIC_API_KEY", "").strip(): + raise RuntimeError("set ANTHROPIC_API_KEY to draft a contract") + try: + import anthropic + except ImportError as exc: # pragma: no cover - optional dependency + raise RuntimeError( + "drafting needs the Anthropic SDK: pip install anthropic" + ) from exc + self._anthropic = anthropic + self.client = anthropic.Anthropic(max_retries=3) + self.ledger = ledger + self.label = label + + def draft(self, messages: list[dict[str, Any]]) -> Draft: + self.ledger.check() + started = time.monotonic() + with self.client.messages.stream( + model=MODEL, + max_tokens=MAX_TOKENS, + system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}], + messages=messages, + output_config={ + "effort": EFFORT, + "format": {"type": "json_schema", "schema": OUTPUT_SCHEMA}, + }, + ) as stream: + response = stream.get_final_message() + call = Call( + request_model=MODEL, + response_model=str(getattr(response, "model", "")), + input_tokens=int(response.usage.input_tokens or 0), + output_tokens=int(response.usage.output_tokens or 0), + cache_read_tokens=int(getattr(response.usage, "cache_read_input_tokens", 0) or 0), + cache_write_tokens=int(getattr(response.usage, "cache_creation_input_tokens", 0) or 0), + usd=round(cost(response.usage), 6), + seconds=round(time.monotonic() - started, 2), + request_id=str(getattr(response, "_request_id", "") or ""), + stop_reason=str(response.stop_reason or ""), + ) + self.ledger.add(call, self.label) + if response.stop_reason == "refusal": + return Draft("", [], "the model declined to draft", call) + raw = "".join(b.text for b in response.content if getattr(b, "type", "") == "text") + return parse_answer(raw, call) + + +def parse_answer(raw: str, call: Optional[Call] = None) -> Draft: + text = raw.strip() + if text.startswith("```"): + text = text.strip("`") + text = text[text.find("{") :] + try: + data = json.loads(text[text.find("{") : text.rfind("}") + 1]) + except ValueError: + return Draft("", [], "the answer was not the JSON object asked for", call, raw) + payloads = [] + for p in data.get("payloads") or []: + if isinstance(p, dict): + payloads.append(p) + elif isinstance(p, list): + payloads.append({str(i.get("param")): i.get("value") for i in p if isinstance(i, dict)}) + return Draft(str(data.get("contract_yaml") or ""), payloads, str(data.get("notes") or ""), call, raw) diff --git a/packages/flow/openadapt_flow/verify_draft/sandbox.py b/packages/flow/openadapt_flow/verify_draft/sandbox.py new file mode 100644 index 0000000000..4c35808866 --- /dev/null +++ b/packages/flow/openadapt_flow/verify_draft/sandbox.py @@ -0,0 +1,702 @@ +"""The sandbox a draft is qualified on: the app, its two actors, its store. + +``sandbox.yaml`` (``openadapt.verify-sandbox/v1``) is what a person gives +once per system. It holds facts, not judgments: where the app answers, how +each of two users signs in, and two connections to the app's database (the +read-only one the contract will read with, and a privileged one that plants +faults and puts the store back between cases):: + + schema_version: openadapt.verify-sandbox/v1 + app: + base_url: http://127.0.0.1:9000 + actors: + agent: # the user the agent writes as + id: "2" # that user's id as the store holds it + headers: {Authorization: "Bearer ${AGENT_TOKEN}"} + other: # a second, ordinary user + id: "3" + login: {method: POST, path: /login, form: {username: lee, password: ${LEE_PW}}} + store: + dialect: postgresql # or sqlite, mysql + read: {sql_driver: psycopg2, sql_connect_args: {...}, sql_password_env: APP_RO_PW} + admin: {sql_driver: psycopg2, sql_connect_args: {...}, sql_password_env: APP_PW} + +Nothing here names an app. The store is reset between cases by restoring +the rows read at the start (no reset hook to write), and faults are planted +with the privileged connection, as the fault gate does: a fault is what the +app should never do. +""" + +from __future__ import annotations + +import base64 +import copy +import datetime as _dt +import decimal +import json +import os +import re +import uuid +from dataclasses import dataclass, field +from typing import Any, Iterable, Mapping, Optional, Sequence +from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit + +from pydantic import BaseModel, ConfigDict, Field + +SANDBOX_SCHEMA = "openadapt.verify-sandbox/v1" + +#: Request headers a replay never copies from the trace: the actor's own +#: sign-in replaces them, and the transport sets the rest. +_DROP_HEADERS = frozenset( + { + "authorization", + "cookie", + "host", + "content-length", + "connection", + "accept-encoding", + "x-csrf-token", + "x-xsrf-token", + } +) +_ENV = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}") + + +class SandboxError(RuntimeError): + """The sandbox can't be used; the message says why.""" + + +def _expand(value: Any) -> Any: + """``${NAME}`` from the environment, recursively. A missing name is an + error, never an empty string.""" + + if isinstance(value, str): + + def sub(m: re.Match[str]) -> str: + name = m.group(1) + if name not in os.environ: + raise SandboxError(f"environment variable {name} is not set") + return os.environ[name] + + return _ENV.sub(sub, value) + if isinstance(value, list): + return [_expand(v) for v in value] + if isinstance(value, dict): + return {k: _expand(v) for k, v in value.items()} + return value + + +class Login(BaseModel): + model_config = ConfigDict(extra="forbid") + method: str = "POST" + path: str + form: Optional[dict[str, str]] = None + json_body: Optional[dict[str, Any]] = Field(default=None, alias="json") + #: A JSON response field holding a bearer token (``access_token``). + token_field: Optional[str] = None + + +class ActorConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + #: The user's id as the store holds it (bound as the ``actor_id`` param). + id: str + headers: dict[str, str] = Field(default_factory=dict) + login: Optional[Login] = None + + +class StoreConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + dialect: str + read: dict[str, Any] + admin: dict[str, Any] + #: Schemas to read on PostgreSQL (default ``public``). + schemas: list[str] = Field(default_factory=lambda: ["public"]) + + +class AppConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + base_url: str + timeout_s: float = 30.0 + + +class SandboxConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_version: str = SANDBOX_SCHEMA + app: AppConfig + actors: dict[str, ActorConfig] + store: StoreConfig + + def actor(self, name: str) -> ActorConfig: + if name not in self.actors: + raise SandboxError(f"sandbox.actors has no {name!r}") + return self.actors[name] + + +def load_sandbox(path: str) -> SandboxConfig: + import yaml + + with open(path, encoding="utf-8") as fh: + data = yaml.safe_load(fh) or {} + cfg = SandboxConfig.model_validate(data) + if cfg.schema_version != SANDBOX_SCHEMA: + raise SandboxError(f"sandbox schema_version must be {SANDBOX_SCHEMA}") + if "agent" not in cfg.actors: + raise SandboxError("sandbox.actors needs an agent") + if cfg.store.dialect not in ("sqlite", "postgresql", "mysql"): + raise SandboxError("store.dialect is sqlite, postgresql or mysql") + return cfg + + +# -- the store ----------------------------------------------------------------- + + +Row = dict[str, Any] +#: table -> primary key (a tuple of values, or the row's position) -> row +Rows = dict[str, dict[Any, Row]] + + +@dataclass +class Table: + name: str + columns: list[str] + types: dict[str, str] + pk: list[str] + fks: dict[str, str] = field(default_factory=dict) # column -> table + #: Column sets the store holds unique (besides the primary key). + unique: list[list[str]] = field(default_factory=list) + + +def _connect(spec: Mapping[str, Any], dialect: str) -> Any: + spec = _expand(dict(spec)) + if dialect == "sqlite" or spec.get("sqlite_database"): + import sqlite3 + + con = sqlite3.connect(spec["sqlite_database"], timeout=30) + con.row_factory = None + return con + driver = spec.get("sql_driver") + args = dict(spec.get("sql_connect_args") or {}) + env = spec.get("sql_password_env") + if env: + if env not in os.environ: + raise SandboxError(f"environment variable {env} is not set") + args["password"] = os.environ[env] + if driver == "psycopg2": + import psycopg2 + import psycopg2.extras + + psycopg2.extras.register_uuid() + con = psycopg2.connect(**args) + return con + if driver == "pymysql": + import pymysql + + args.setdefault("charset", "utf8mb4") + return pymysql.connect(**args) + raise SandboxError(f"unsupported sql_driver {driver!r}") + + +class Store: + """The app's database through the privileged connection. + + Reads every table with values (synthetic sandbox data only), puts the + store back to a snapshot, and plants faults. + """ + + def __init__(self, cfg: StoreConfig) -> None: + self.cfg = cfg + self.dialect = cfg.dialect + self.tables = self._introspect() + + # -- plumbing + + def _con(self) -> Any: + return _connect(self.cfg.admin, self.dialect) + + def q(self, name: str) -> str: + if self.dialect == "mysql": + return "`" + name.replace("`", "``") + "`" + if "." in name and self.dialect == "postgresql": + schema, _, table = name.partition(".") + return f'"{schema}"."{table}"' + return '"' + name.replace('"', '""') + '"' + + @property + def mark(self) -> str: + return "?" if self.dialect == "sqlite" else "%s" + + def _introspect(self) -> dict[str, Table]: + con = self._con() + try: + cur = con.cursor() + out: dict[str, Table] = {} + if self.dialect == "sqlite": + cur.execute( + "SELECT name FROM sqlite_master WHERE type='table' " + "AND name NOT LIKE 'sqlite_%' ORDER BY name" + ) + for (name,) in cur.fetchall(): + cur.execute(f"PRAGMA table_info({self.q(name)})") + info = cur.fetchall() + cols = [r[1] for r in info] + types = {r[1]: (r[2] or "").lower() for r in info} + pk = [r[1] for r in sorted(info, key=lambda r: r[5]) if r[5]] + cur.execute(f"PRAGMA foreign_key_list({self.q(name)})") + fks = {r[3]: r[2] for r in cur.fetchall()} + unique = [] + cur.execute(f"PRAGMA index_list({self.q(name)})") + for idx in cur.fetchall(): + if idx[2]: + cur.execute(f"PRAGMA index_info({self.q(idx[1])})") + unique.append([r[2] for r in cur.fetchall()]) + out[name] = Table(name, cols, types, pk, fks, unique) + return out + if self.dialect == "postgresql": + schemas = tuple(self.cfg.schemas) + cur.execute( + "SELECT table_schema, table_name, column_name, data_type " + "FROM information_schema.columns WHERE table_schema = ANY(%s) " + "AND table_name IN (SELECT table_name FROM information_schema.tables " + "WHERE table_type='BASE TABLE' AND table_schema = ANY(%s)) " + "ORDER BY table_schema, table_name, ordinal_position", + (list(schemas), list(schemas)), + ) + rows = cur.fetchall() + cur.execute( + "SELECT tc.table_schema, tc.table_name, kcu.column_name, tc.constraint_type, " + "COALESCE(ccu.table_name, tc.constraint_name) FROM information_schema.table_constraints tc " + "JOIN information_schema.key_column_usage kcu " + "ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema " + "LEFT JOIN information_schema.constraint_column_usage ccu " + "ON tc.constraint_name = ccu.constraint_name AND tc.constraint_type='FOREIGN KEY' " + "WHERE tc.table_schema = ANY(%s) AND tc.constraint_type IN ('PRIMARY KEY','FOREIGN KEY','UNIQUE') " + "ORDER BY kcu.ordinal_position", + (list(schemas),), + ) + cons = cur.fetchall() + else: + cur.execute("SELECT DATABASE()") + db = cur.fetchone()[0] + cur.execute( + "SELECT table_schema, table_name, column_name, data_type FROM " + "information_schema.columns WHERE table_schema=%s AND table_name IN " + "(SELECT table_name FROM information_schema.tables WHERE " + "table_type='BASE TABLE' AND table_schema=%s) ORDER BY table_name, " + "ordinal_position", + (db, db), + ) + rows = cur.fetchall() + cur.execute( + "SELECT table_schema, table_name, column_name, IF(constraint_name=" + "'PRIMARY','PRIMARY KEY','FOREIGN KEY'), referenced_table_name FROM " + "information_schema.key_column_usage WHERE table_schema=%s AND " + "(constraint_name='PRIMARY' OR referenced_table_name IS NOT NULL) " + "ORDER BY ordinal_position", + (db,), + ) + cons = cur.fetchall() + for schema, table, col, dtype in rows: + name = self._name(schema, table) + t = out.setdefault(name, Table(name, [], {}, [])) + t.columns.append(col) + t.types[col] = str(dtype).lower() + for schema, table, col, kind, ref in cons: + t = out.get(self._name(schema, table)) + if t is None: + continue + if kind == "PRIMARY KEY" and col not in t.pk: + t.pk.append(col) + elif kind == "FOREIGN KEY" and ref: + t.fks[col] = self._name(schema, ref) + elif kind == "UNIQUE": + groups = getattr(t, "_ugroups", {}) + groups.setdefault(ref, []).append(col) + t._ugroups = groups # type: ignore[attr-defined] + for t in out.values(): + t.unique = [cols for cols in getattr(t, "_ugroups", {}).values()] + return out + finally: + con.close() + + def _name(self, schema: str, table: str) -> str: + if self.dialect == "postgresql" and schema != "public": + return f"{schema}.{table}" + return table + + def schema_text(self) -> str: + """Tables, columns, types, keys: the introspected description.""" + + lines = [] + for t in self.tables.values(): + cols = [] + for c in t.columns: + bits = [c, t.types.get(c, "")] + if c in t.pk: + bits.append("PK") + if c in t.fks: + bits.append(f"-> {t.fks[c]}") + cols.append(" ".join(b for b in bits if b)) + lines.append(f"{t.name}({', '.join(cols)})") + return "\n".join(lines) + + # -- reads + + def _key(self, t: Table, row: Row, pos: int) -> Any: + if t.pk: + return tuple(row[c] for c in t.pk) + return ("#", pos, _canon(row)) + + def read(self, tables: Optional[Iterable[str]] = None) -> Rows: + names = list(tables) if tables is not None else list(self.tables) + con = self._con() + try: + cur = con.cursor() + out: Rows = {} + for name in names: + t = self.tables[name] + cols = ", ".join(self.q(c) for c in t.columns) + cur.execute(f"SELECT {cols} FROM {self.q(name)}") + rows = {} + for i, values in enumerate(cur.fetchall()): + row = dict(zip(t.columns, values)) + rows[self._key(t, row, i)] = row + out[name] = rows + if self.dialect != "sqlite": + con.rollback() + return out + finally: + con.close() + + # -- writes (privileged) + + def _exec(self, statements: Sequence[tuple[str, Sequence[Any]]]) -> list[Any]: + con = self._con() + out = [] + try: + cur = con.cursor() + if self.dialect == "postgresql": + cur.execute("SET session_replication_role = replica") + elif self.dialect == "mysql": + cur.execute("SET FOREIGN_KEY_CHECKS=0") + else: + cur.execute("PRAGMA foreign_keys=OFF") + for sql, args in statements: + cur.execute(sql, [_adapt(a, self.dialect) for a in args]) + out.append(cur.lastrowid if self.dialect != "postgresql" else None) + con.commit() + return out + except Exception: + con.rollback() + raise + finally: + con.close() + + def restore(self, snapshot: Rows) -> int: + """Put every table that differs from ``snapshot`` back. Returns how + many tables were rewritten.""" + + now = self.read() + statements: list[tuple[str, Sequence[Any]]] = [] + changed = 0 + for name, rows in snapshot.items(): + if _digest_rows(now.get(name, {})) == _digest_rows(rows): + continue + changed += 1 + t = self.tables[name] + statements.append((f"DELETE FROM {self.q(name)}", ())) + cols = ", ".join(self.q(c) for c in t.columns) + marks = ", ".join([self.mark] * len(t.columns)) + for row in rows.values(): + statements.append( + ( + f"INSERT INTO {self.q(name)} ({cols}) VALUES ({marks})", + [row[c] for c in t.columns], + ) + ) + if statements: + self._exec(statements) + return changed + + def update(self, table: str, key: tuple, changes: Mapping[str, Any]) -> None: + t = self.tables[table] + sets = ", ".join(f"{self.q(c)} = {self.mark}" for c in changes) + where = " AND ".join(f"{self.q(c)} = {self.mark}" for c in t.pk) + self._exec( + [ + ( + f"UPDATE {self.q(table)} SET {sets} WHERE {where}", + list(changes.values()) + list(key), + ) + ] + ) + + def insert(self, table: str, row: Mapping[str, Any]) -> None: + cols = ", ".join(self.q(c) for c in row) + marks = ", ".join([self.mark] * len(row)) + self._exec( + [(f"INSERT INTO {self.q(table)} ({cols}) VALUES ({marks})", list(row.values()))] + ) + + def delete(self, table: str, key: tuple) -> None: + t = self.tables[table] + where = " AND ".join(f"{self.q(c)} = {self.mark}" for c in t.pk) + self._exec([(f"DELETE FROM {self.q(table)} WHERE {where}", list(key))]) + + def new_key_row(self, table: str, row: Row, existing: Rows) -> Row: + """``row`` with a primary key no row of ``table`` holds, and with + any other unique column the store would refuse to repeat changed + (a second chart under a near-identical number).""" + + t = self.tables[table] + out = dict(row) + taken = existing.get(table, {}) + for c in t.pk: + out[c] = _fresh(row[c], [k[t.pk.index(c)] for k in taken if isinstance(k, tuple) and len(k) == len(t.pk)]) + for cols in t.unique: + if any(out.get(c) is None for c in cols): + continue + for c in cols: + if c not in t.pk: + out[c] = _fresh(row[c], [r.get(c) for r in taken.values()]) + return out + + +def _fresh(value: Any, taken: Sequence[Any]) -> Any: + if isinstance(value, bool): + return value + if isinstance(value, int): + return max([v for v in taken if isinstance(v, int)] + [value]) + 1000 + if isinstance(value, uuid.UUID): + return uuid.uuid4() + if isinstance(value, str): + try: + uuid.UUID(value) + return str(uuid.uuid4()) if "-" in value else uuid.uuid4().hex + except ValueError: + pass + if value.isdigit(): + return str(max([int(v) for v in taken if str(v).isdigit()] + [int(value)]) + 1000) + return value + "-copy" + return value + + +def _adapt(value: Any, dialect: str) -> Any: + if dialect == "postgresql" and isinstance(value, (dict, list)): + import psycopg2.extras + + return psycopg2.extras.Json(value) + if dialect == "mysql" and isinstance(value, (dict, list)): + return json.dumps(value) + return value + + +def _canon(value: Any) -> Any: + if isinstance(value, dict): + return json.dumps({k: _canon(v) for k, v in value.items()}, sort_keys=True) + if isinstance(value, (list, tuple)): + return json.dumps([_canon(v) for v in value]) + if isinstance(value, (bytes, memoryview)): + return base64.b64encode(bytes(value)).decode() + if isinstance(value, (_dt.date, _dt.datetime, _dt.time, decimal.Decimal, uuid.UUID)): + return str(value) + return value + + +def _digest_rows(rows: Mapping[Any, Row]) -> str: + import hashlib + + items = sorted( + json.dumps({k: _canon(v) for k, v in r.items()}, sort_keys=True, default=str) + for r in rows.values() + ) + return hashlib.sha256("\n".join(items).encode()).hexdigest() + + +def text(value: Any) -> str: + """A stored value as comparable text.""" + + v = _canon(value) + return "" if v is None else str(v) + + +# -- moves between two reads --------------------------------------------------- + + +@dataclass +class Move: + table: str + key: Any + change: str # added | removed | changed + columns: list[str] + before: Optional[Row] + after: Optional[Row] + + +def moves(before: Rows, after: Rows) -> list[Move]: + out: list[Move] = [] + for table in sorted(set(before) | set(after)): + b, a = before.get(table, {}), after.get(table, {}) + for key in a.keys() - b.keys(): + out.append(Move(table, key, "added", sorted(a[key]), None, a[key])) + for key in b.keys() - a.keys(): + out.append(Move(table, key, "removed", sorted(b[key]), b[key], None)) + for key in a.keys() & b.keys(): + cols = sorted(c for c in a[key] if text(a[key][c]) != text(b[key].get(c))) + if cols: + out.append(Move(table, key, "changed", cols, b[key], a[key])) + return out + + +# -- the app ------------------------------------------------------------------- + + +@dataclass +class Request: + """One request from the trace.""" + + method: str + url: str + headers: dict[str, str] + body: Optional[str] + mime: str + status: Optional[int] = None + response: Optional[str] = None + + @property + def path(self) -> str: + return urlsplit(self.url).path + + +class App: + """The app over HTTP, as one of the sandbox's actors.""" + + def __init__(self, cfg: SandboxConfig) -> None: + self.cfg = cfg + self._sessions: dict[str, Any] = {} + + def login_paths(self) -> set[str]: + return {a.login.path for a in self.cfg.actors.values() if a.login} + + def session(self, actor: str) -> Any: + import requests + + if actor in self._sessions: + return self._sessions[actor] + spec = self.cfg.actor(actor) + s = requests.Session() + s.headers.update(_expand(dict(spec.headers))) + if spec.login is not None: + login = spec.login + url = self.cfg.app.base_url.rstrip("/") + login.path + r = s.request( + login.method, + url, + data=_expand(login.form) if login.form else None, + json=_expand(login.json_body) if login.json_body else None, + allow_redirects=False, + timeout=self.cfg.app.timeout_s, + ) + if r.status_code >= 400: + raise SandboxError(f"actor {actor} could not sign in ({r.status_code})") + if login.token_field: + token = (r.json() or {}).get(login.token_field) + if not token: + raise SandboxError(f"sign-in for {actor} returned no {login.token_field}") + s.headers["Authorization"] = f"Bearer {token}" + self._sessions[actor] = s + return s + + def send( + self, + writes: Sequence[Request], + actor: str, + swap: Mapping[str, Any], + *, + repeat: int = 1, + ) -> list[int]: + """Replay the trace's writes as ``actor``, with each demonstrated + value in ``swap`` replaced by its new value. Returns the statuses.""" + + s = self.session(actor) + base = urlsplit(self.cfg.app.base_url) + statuses = [] + for _ in range(repeat): + for req in writes: + parts = urlsplit(req.url) + path = _swap_path(parts.path, swap) + query = urlencode( + [(k, _swap_text(v, swap)) for k, v in parse_qsl(parts.query, keep_blank_values=True)] + ) + url = urlunsplit((base.scheme, base.netloc, path, query, "")) + headers = { + k: v for k, v in req.headers.items() if k.lower() not in _DROP_HEADERS + } + body = _swap_body(req.body, req.mime, swap) + r = s.request( + req.method, + url, + data=body.encode("utf-8") if isinstance(body, str) else body, + headers=headers, + allow_redirects=False, + timeout=self.cfg.app.timeout_s, + ) + statuses.append(r.status_code) + return statuses + + +def _swap_text(value: str, swap: Mapping[str, Any]) -> str: + return str(swap[value]) if value in swap else value + + +def _swap_path(path: str, swap: Mapping[str, Any]) -> str: + return "/".join( + quote(str(swap[seg]), safe="") if seg in swap else seg for seg in path.split("/") + ) + + +def _swap_json(value: Any, swap: Mapping[str, Any]) -> Any: + if isinstance(value, dict): + return {k: _swap_json(v, swap) for k, v in value.items()} + if isinstance(value, list): + return [_swap_json(v, swap) for v in value] + if value is None or isinstance(value, bool): + return value + key = str(value) + if key in swap: + new = swap[key] + if isinstance(value, (int, float)) and not isinstance(new, (int, float)): + try: + return type(value)(new) + except (TypeError, ValueError): + return new + return new + return value + + +def _swap_body(body: Optional[str], mime: str, swap: Mapping[str, Any]) -> Optional[str]: + if body is None or not swap: + return body + if "json" in mime: + try: + return json.dumps(_swap_json(json.loads(body), swap)) + except ValueError: + return body + if "x-www-form-urlencoded" in mime: + return urlencode( + [(k, _swap_text(v, swap)) for k, v in parse_qsl(body, keep_blank_values=True)] + ) + return body + + +def swap_map(old: Mapping[str, Any], new: Mapping[str, Any]) -> dict[str, Any]: + """Demonstrated value (as text) -> new value, for each param that changes.""" + + out: dict[str, Any] = {} + for name, value in new.items(): + if name in old and old[name] is not None and text(old[name]) != text(value): + out[text(old[name])] = value + return out + + +def deep(value: Any) -> Any: + return copy.deepcopy(value) diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index cabfb87834..9b8feb1e17 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -335,6 +335,8 @@ def load_verify_config(path: str | Path) -> VerifyConfig: "inputs", "campaign", "business_rules", + # Who drafted the check and how it was admitted (openadapt verify draft). + "provenance", ) diff --git a/packages/flow/tests/test_verify_draft.py b/packages/flow/tests/test_verify_draft.py new file mode 100644 index 0000000000..f16274b83c --- /dev/null +++ b/packages/flow/tests/test_verify_draft.py @@ -0,0 +1,255 @@ +"""``openadapt verify draft``: drafting is a model's job, admission is ours. + +The model is replaced by a fixed drafter, so nothing here calls a model. +The sandbox is MockLoan's fault server (SQLite, in-process). +""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +import textwrap +from pathlib import Path +from typing import Any + +import pytest +import requests +import yaml + +from openadapt_flow.verify_draft import admit as A +from openadapt_flow.verify_draft import draft as D +from openadapt_flow.verify_draft import inputs as I +from openadapt_flow.verify_draft import model as M +from openadapt_flow.verify_draft.sandbox import load_sandbox + +GOOD = textwrap.dedent( + """\ + schema_version: openadapt.verify/v1 + verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(id AS TEXT) AS id, loan_id, product, amount, memo, source, record_key, surface FROM records + effects: + - kind: record_written + probe: surface=record|one new disbursement with the task's values + match: + loan_id: {param: loan_id} + product: {param: product} + amount: {param: amount} + memo: {param: memo} + surface: {literal: disbursements} + expected_count: 1 + count_new_only: true + frame: + identity_field: id + database: + dialect: sqlite + views: {records: record} + new_row_fields: {records: [id, source, record_key, surface]} + settle_s: 0.2 + recheck_after_s: 300 + """ +) +#: Matches the loan only (the other columns are waved through as fields a +#: new row may set), and schedules no recheck. +WEAK = ( + GOOD.replace(" product: {param: product}\n amount: {param: amount}\n memo: {param: memo}\n", "") + .replace(" recheck_after_s: 300\n", "") + .replace("[id, source, record_key, surface]", "[id, source, record_key, surface, product, amount, memo]") +) +PAYLOADS = [ + {"amount": f"{1000 + i * 111}.00", "memo": f"Probe memo {i}", "product": ["Auto", "Home", "Personal"][i % 3]} + for i in range(8) +] + + +class Fixed: + """A drafter that answers with given contracts, in order.""" + + def __init__(self, *contracts: str) -> None: + self.contracts = list(contracts) + self.seen: list[list[dict[str, Any]]] = [] + + def draft(self, messages: list[dict[str, Any]]) -> M.Draft: + self.seen.append(list(messages)) + text = self.contracts[min(len(self.seen) - 1, len(self.contracts) - 1)] + return M.Draft(text, PAYLOADS, "fixed", None) + + +@pytest.fixture() +def mockloan(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: + from openadapt_flow.mockloan import fault_server + + monkeypatch.setenv("OPENADAPT_LOCAL_SEAL", "off") + url, db, stop = fault_server.serve(0) + base = url.rstrip("/") + for loan, prod, amt in [("LN-1", "Auto", "10.00"), ("LN-2", "Home", "20.00")]: + requests.post(base + "/api/disbursement", json={"loan_id": loan, "product": prod, "amount": amt, "memo": "seed"}, timeout=10) + seeded = tmp_path / "seeded.sqlite3" + shutil.copy(db.database_path, seeded) + params = {"loan_id": "LN-9", "product": "Personal", "amount": "31.50", "memo": "Kitchen"} + trace = { + "log": { + "entries": [ + { + "request": { + "method": "POST", + "url": base + "/api/disbursement", + "headers": [{"name": "Content-Type", "value": "application/json"}, + {"name": "Authorization", "value": "Bearer secret-demo-token"}], + "postData": {"mimeType": "application/json", "text": json.dumps({**params, "password": "hunter2"})}, + }, + "response": {"status": 200, "content": {"text": "{}"}}, + } + ] + } + } + (tmp_path / "trace.har").write_text(json.dumps(trace)) + (tmp_path / "task.yaml").write_text(yaml.safe_dump({"instruction": "Book it.", "params": params})) + (tmp_path / "sandbox.yaml").write_text( + yaml.safe_dump( + { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": base}, + "actors": {"agent": {"id": "a1"}, "other": {"id": "b2"}}, + "store": {"dialect": "sqlite", "read": {"sqlite_database": str(db.database_path)}, + "admin": {"sqlite_database": str(db.database_path)}}, + } + ) + ) + yield tmp_path + stop() + + +def _run(root: Path, drafter: Any, **kw: Any) -> D.Outcome: + return D.run( + describe="db", + trace_path=str(root / "trace.har"), + task_path=str(root / "task.yaml"), + sandbox_path=str(root / "sandbox.yaml"), + out=root / "out", + drafter=drafter, + **kw, + ) + + +@pytest.mark.timeout(300) +def test_good_draft_is_admitted_and_bound(mockloan: Path) -> None: + drafter = Fixed(GOOD) + outcome = _run(mockloan, drafter, rounds=1) + assert outcome.admitted, outcome.reason + assert outcome.decisions == 0 + adm = outcome.admissions[-1] + names = {c.name for c in adm.cases if c.group == "fault" and c.applicable} + assert {"wrong_row", "duplicate", "sibling_edit", "late_revert"} <= names + assert any(n.startswith("wrong_value:") for n in names) + assert sum(c.passed for c in adm.cases if c.group == "clean") == A.CLEAN_PROBES + assert sum(c.passed for c in adm.cases if c.group == "probe") == 4 + path = outcome.contract_path + assert path is not None and D.admission_problem(path) is None + prov = yaml.safe_load(path.read_text())["provenance"] + assert prov["drafted_by"]["model"] == M.MODEL + assert prov["drafted_by"]["prompt_sha256"] == M.prompt_sha256() + # The model saw no sign-in header and no secret field. + sent = drafter.seen[0][0]["content"] + assert "secret-demo-token" not in sent and "hunter2" not in sent + # An edit to the check after admission voids it. + data = yaml.safe_load(path.read_text()) + data["effects"][0]["match"].pop("memo") + edited = mockloan / "edited.yaml" + edited.write_text(yaml.safe_dump(data)) + assert D.admission_problem(edited) == "the check changed after admission" + + +@pytest.mark.timeout(400) +def test_weak_draft_is_refused_with_reasons_fed_back(mockloan: Path) -> None: + drafter = Fixed(WEAK, WEAK) + outcome = _run(mockloan, drafter, rounds=2) + assert not outcome.admitted and outcome.contract_path is None + assert not (mockloan / "out" / "contract.yaml").exists() + failed = {c.name for c in outcome.admissions[0].cases if not c.passed} + assert "late_revert" in failed # no recheck window + assert any(n.startswith("wrong_value:amount") for n in failed) + feedback = drafter.seen[1][-1]["content"] + assert "late_revert" in feedback and "wrong_value:amount" in feedback + assert outcome.rounds == 2 + + +def test_rounds_stop_at_three_and_unsafe_drafts_never_run(mockloan: Path) -> None: + unsafe = GOOD.replace(" kind: surfaces\n", " kind: surfaces\n session: my.hooks:login\n") + drafter = Fixed(unsafe, "not: [valid", GOOD.replace("FROM records", "FROM records; DELETE FROM records")) + outcome = _run(mockloan, drafter, rounds=3) + assert not outcome.admitted + assert len(drafter.seen) == 3 and outcome.rounds == 3 + assert not outcome.admissions # nothing was run against the sandbox + assert "session" in drafter.seen[1][-1]["content"] + + +def test_rounds_are_capped() -> None: + with pytest.raises(SystemExit): + D.main(["--trace", "t", "--task", "t", "--sandbox", "s", "--out", "o", "--rounds", "4"]) + + +def test_attribution_flags_masks(tmp_path: Path) -> None: + seen = {("agent", 0): "a", ("agent", 1): "b", ("other", 0): "a", ("other", 1): "b"} + assert A._cause(seen, ["agent", "other"]) == "payload" + seen = {("agent", 0): "7", ("agent", 1): "7", ("other", 0): "9", ("other", 1): "9"} + assert A._cause(seen, ["agent", "other"]) == "actor" + clock = {k: f"2026-11-21 07:0{i}:00" for i, k in enumerate(seen)} + assert A._cause(clock, ["agent", "other"]) == "clock" + + +def test_spend_ledger_refuses_past_the_cap(tmp_path: Path) -> None: + ledger = M.SpendLedger(tmp_path / "spend.jsonl", cap_usd=1.0) + ledger.add(M.Call(M.MODEL, M.MODEL, 1, 1, 0, 0, 0.6, 1.0), "x") + with pytest.raises(M.BudgetExceeded): + ledger.check() + + +def test_descriptions_and_masking(tmp_path: Path) -> None: + api = {"openapi": "3.1.0", "info": {"title": "T", "version": "1"}, + "paths": {"/r/{slug}": {"patch": {"summary": "Update", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/R"}}}}}}}, + "components": {"schemas": {"R": {"properties": {"name": {"type": "string"}}}}}} + (tmp_path / "api.json").write_text(json.dumps(api)) + d = I.load_description(str(tmp_path / "api.json")) + assert d.kind == "openapi" and "PATCH /r/{slug} body=R" in d.text and "R{name:string}" in d.text + (tmp_path / "cap.json").write_text(json.dumps({"resourceType": "CapabilityStatement", "rest": [{"resource": [{"type": "Patient", "interaction": [{"code": "update"}]}]}]})) + assert I.load_description(str(tmp_path / "cap.json")).text.endswith("Patient: update") + (tmp_path / "s.graphql").write_text("type Query { a: Int }\ntype Task { id: ID title: String }") + assert I.load_description(str(tmp_path / "s.graphql")).kind == "graphql" + assert I.load_description("none").kind == "none" + req = I.Request("POST", "http://x/a?token=t1&q=1", {"Cookie": "c", "X-Api-Key": "k", "Accept": "*/*"}, + "username=u&password=p", "application/x-www-form-urlencoded") + m = I.masked(req) + assert "t1" not in m["url"] and "Cookie" not in m["headers"] and "X-Api-Key" not in m["headers"] + assert "password=%2A%2A%2A" in m["body"] and "username=u" in m["body"] + + +def test_run_path_makes_no_model_calls(mockloan: Path) -> None: + """An admitted contract is judged by the verifier alone: the model + module and the Anthropic SDK are never imported on the run path.""" + + contract = A.prepare(GOOD, load_sandbox(str(mockloan / "sandbox.yaml"))) + path = mockloan / "contract.yaml" + path.write_text(yaml.safe_dump(contract)) + code = textwrap.dedent( + f""" + import sys + sys.modules["anthropic"] = None # any import of the SDK fails + from openadapt_flow.verifier import Actor, Contract, Ledger, MemoryLedger, begin_write, verify_write + c = Contract.load({str(path)!r}) + p = begin_write(c, {{"loan_id": "LN-1", "product": "Auto", "amount": "10.00", "memo": "seed", "actor_id": "a1"}}, + actor=Actor("agent", "a1"), ledger=Ledger(MemoryLedger())) + r = verify_write(p, seal=False) + assert not any(m.startswith("openadapt_flow.verify_draft") for m in sys.modules), "draft code imported" + print(r.outcome.value) + """ + ) + out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120, + env={"OPENADAPT_LOCAL_SEAL": "off", "PATH": "/usr/bin:/bin", "HOME": str(mockloan)}) + assert out.returncode == 0, out.stderr + assert out.stdout.strip() in ("REFUTED", "UNCERTAIN") # no new record was written From 89c17803027aa16f660054322afebf7f00f7ad9f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:04:22 -0500 Subject: [PATCH 02/14] feat(verify): verify draft reads only moved tables, repeats a probe write, preflights the read account; launcher command; docs; benchmark runs on MockLoan, workbench and Mealie --- CAPABILITIES.md | 1 + openadapt/cli.py | 25 + openadapt/cli_tasks.py | 1 + .../flow/benchmark/verify_draft/PROTOCOL.md | 76 + packages/flow/benchmark/verify_draft/apps.py | 441 +++- packages/flow/benchmark/verify_draft/har.py | 23 +- .../flow/benchmark/verify_draft/report.py | 49 + .../benchmark/verify_draft/results/.gitignore | 10 + .../benchmark/verify_draft/results/mealie.log | 61 + .../results/mealie/draft/report.json | 34 + .../results/mealie/draft/rounds/round-1.yaml | 33 + .../draft/rounds/round-2.admission.json | 777 +++++++ .../results/mealie/draft/rounds/round-2.yaml | 33 + .../draft/rounds/round-3.admission.json | 28 + .../results/mealie/draft/rounds/round-3.yaml | 39 + .../verify_draft/results/mealie/result.json | 94 + .../results/mealie/setup/sandbox.yaml | 40 + .../results/mealie/setup/task.yaml | 6 + .../results/mealie/setup/trace.har | 92 + .../verify_draft/results/mockloan.log | 421 ++++ .../results/mockloan/draft/contract.yaml | 81 + .../results/mockloan/draft/report.json | 20 + .../draft/rounds/round-1.admission.json | 463 +++++ .../mockloan/draft/rounds/round-1.yaml | 31 + .../verify_draft/results/mockloan/result.json | 434 ++++ .../results/mockloan/setup/sandbox.yaml | 14 + .../results/mockloan/setup/task.yaml | 7 + .../results/mockloan/setup/trace.har | 84 + .../verify_draft/results/spend-dev.jsonl | 9 + .../verify_draft/results/spend.jsonl | 11 + .../draft/rounds/round-1.admission.json | 297 +++ .../mealie-run1/draft/rounds/round-1.yaml | 33 + .../mealie-run1/draft/rounds/round-2.yaml | 45 + .../mealie-run1/draft/rounds/round-3.yaml | 45 + .../results/void/mealie-run1/run.log | 7 + .../void/mealie-run1/setup/sandbox.yaml | 40 + .../results/void/mealie-run1/setup/task.yaml | 6 + .../results/void/mealie-run1/setup/trace.har | 92 + .../void/mealie-run2/draft/report.json | 46 + .../draft/rounds/round-1.admission.json | 777 +++++++ .../mealie-run2/draft/rounds/round-1.yaml | 33 + .../mealie-run2/draft/rounds/round-2.yaml | 81 + .../draft/rounds/round-3.admission.json | 1815 +++++++++++++++++ .../mealie-run2/draft/rounds/round-3.yaml | 80 + .../results/void/mealie-run2/result.json | 103 + .../results/void/mealie-run2/run.log | 67 + .../void/mealie-run2/setup/sandbox.yaml | 40 + .../results/void/mealie-run2/setup/task.yaml | 6 + .../results/void/mealie-run2/setup/trace.har | 92 + .../verify_draft/results/workbench.log | 315 +++ .../results/workbench/draft/contract.yaml | 104 + .../results/workbench/draft/report.json | 20 + .../draft/rounds/round-1.admission.json | 384 ++++ .../workbench/draft/rounds/round-1.yaml | 41 + .../results/workbench/result.json | 328 +++ .../results/workbench/setup/sandbox.yaml | 28 + .../results/workbench/setup/task.yaml | 5 + .../results/workbench/setup/trace.har | 135 ++ packages/flow/benchmark/verify_draft/run.py | 88 +- packages/flow/docs/VERIFY_DRAFT.md | 199 ++ .../flow/openadapt_flow/verify_draft/admit.py | 304 ++- .../flow/openadapt_flow/verify_draft/draft.py | 165 +- .../openadapt_flow/verify_draft/inputs.py | 79 +- .../flow/openadapt_flow/verify_draft/model.py | 37 +- .../openadapt_flow/verify_draft/sandbox.py | 107 +- packages/flow/tests/test_verify_draft.py | 165 +- 66 files changed, 9384 insertions(+), 263 deletions(-) create mode 100644 packages/flow/benchmark/verify_draft/PROTOCOL.md create mode 100644 packages/flow/benchmark/verify_draft/report.py create mode 100644 packages/flow/benchmark/verify_draft/results/.gitignore create mode 100644 packages/flow/benchmark/verify_draft/results/mealie.log create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mealie/setup/trace.har create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan.log create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har create mode 100644 packages/flow/benchmark/verify_draft/results/spend-dev.jsonl create mode 100644 packages/flow/benchmark/verify_draft/results/spend.jsonl create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-2.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-3.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/run.log create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/trace.har create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-2.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/trace.har create mode 100644 packages/flow/benchmark/verify_draft/results/workbench.log create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har create mode 100644 packages/flow/docs/VERIFY_DRAFT.md diff --git a/CAPABILITIES.md b/CAPABILITIES.md index b67780381a..0cc9847bd8 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -166,6 +166,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR (MEASURE_PLACEHOLDER) | MEASURE_EVIDENCE | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/openadapt/cli.py b/openadapt/cli.py index f5fb4e95f8..70840f99c8 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1646,6 +1646,31 @@ def verify_serve(contracts: str, state: Optional[str]) -> None: sys.exit(int(agent_main(argv) or 0)) +@verify.command( + "draft", + context_settings={"ignore_unknown_options": True, "allow_extra_args": True}, + add_help_option=False, +) +@click.pass_context +def verify_draft(ctx: click.Context) -> None: + """Draft a write contract with a model; admit it only if OpenAdapt + qualifies it on a sandbox. + + `openadapt verify draft --describe openapi.json --trace demo.har + --task task.yaml --sandbox sandbox.yaml --out DIR`. The model (key from + ANTHROPIC_API_KEY) works at setup only; an admitted contract runs with no + model calls. `--help` lists every option. + """ + _require_supported_python() + try: + from openadapt_flow.verify_draft.draft import main as draft_main + except ImportError: + click.echo("Error: the OpenAdapt engine is not installed.", err=True) + click.echo("Reinstall with: pip install --upgrade openadapt", err=True) + sys.exit(1) + sys.exit(int(draft_main(list(ctx.args)) or 0)) + + def _protected_ledger_requested() -> bool: name = "OPENADAPT_LEDGER_AUTHORITY_CONFIG" if name not in os.environ: diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 61bb8854d7..861f24701f 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -132,6 +132,7 @@ ("verify", "seal"): ("seal",), ("verify", "shadow"): ("shadow",), ("verify", "ledger"): ("verify", "ledger"), + ("verify", "draft"): ("verify", "draft"), ("research", "bench"): ("bench",), ("research", "eval"): ("eval",), ("research", "train"): ("train",), diff --git a/packages/flow/benchmark/verify_draft/PROTOCOL.md b/packages/flow/benchmark/verify_draft/PROTOCOL.md new file mode 100644 index 0000000000..9b643e23a5 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/PROTOCOL.md @@ -0,0 +1,76 @@ +# Protocol: model-drafted write contracts, admitted by qualification + +Written before the reported runs. Changes after a run go under +"Deviations" in [RESULTS.md](RESULTS.md), with the run they affect. + +## Question + +Can a model draft a system's write contract at setup time, from the system's +description and one trace, so that setup takes minutes instead of about an +hour? And does admission by qualification keep every admitted contract +honest: no planted fault missed, no false stop on a clean write? + +The baseline is the Vikunja setup in the second first-contact retest: 64.5 +minutes and 12 person decisions with the deterministic generator and hand +patches. + +## Apps + +| App | Store | Task | Description given | Tuned on before? | +|---|---|---|---|---| +| MockLoan (OpenAdapt's fault server) | SQLite | create a disbursement (JSON POST) | `db` | yes (zero-config benchmark) | +| Workbench, MockMed profile (OpenAdapt's task-generation app) | PostgreSQL | update a patient's phone and email (HTML form) | `db` | yes | +| Mealie v2.8.0 | PostgreSQL | update a recipe's description and yield (JSON PATCH) | OpenAPI (`/openapi.json`) | no: no agent had installed or probed it | + +Mealie runs on the lab's WSL host (PostgreSQL 16.4, both pinned images), +reached from the Mac through an SSH tunnel to loopback. All data is +synthetic. + +## Procedure per app + +1. **Operator setup** (`apps.py`, timed separately). Bring the app to a + seeded state, record one demonstration as a HAR file, and write + `task.yaml` and `sandbox.yaml`. These are facts: URLs, sign-ins and + connections. +2. **`openadapt verify draft`** with the pinned model (`claude-opus-5-5`, + effort `medium`, prompt `verify-draft-prompt/1`). The benchmark never + answers the one question; a question refuses the draft. +3. **Held out**, only for an admitted contract, with no model. A second + qualification run, in which the harness chooses: + - the values: 5 clean writes, and the faults written with other values; + - the rows: the faults planted on other rows (seed 1). + + Two app-level faults that the admission suite never plants are added: + - the same write also sent to another record through the app; + - for a create, the write sent twice through the app. + +## Measures + +- **Setup minutes**: wall time of step 2, from the command's start to the + admitted contract or the refusal. +- **Person decisions**: answers to the command's question. As in the + Vikunja log, the facts in `sandbox.yaml` are listed as operator inputs, + not decisions. +- **Admitted versus rejected drafts**: one draft per model round. +- **Planted-fault catches**: refuted faults over applicable faults, in the + admission and held out. +- **False stops**: clean writes not confirmed, or whose recheck didn't + confirm. +- **Model cost**: from each call's token counts at the model's list price, + in the spend ledger (`results/spend.jsonl`). + +## Kill criterion + +The approach is killed if any of these holds: + +- on the untuned app, setup takes more than 5 minutes; +- on the untuned app, setup takes more than 1 person decision; +- any admitted contract misses a planted fault. + +The admission suite catches its own faults by construction. So a miss is +scored on the held-out faults as well. + +## Spend cap + +USD 30 in all, enforced by the ledger. A call is refused when the total plus +the worst case of one call would pass it. diff --git a/packages/flow/benchmark/verify_draft/apps.py b/packages/flow/benchmark/verify_draft/apps.py index d2230c8ece..1d383759f4 100644 --- a/packages/flow/benchmark/verify_draft/apps.py +++ b/packages/flow/benchmark/verify_draft/apps.py @@ -23,7 +23,7 @@ import time from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Callable, Optional +from typing import Any, Callable import requests import yaml @@ -70,31 +70,51 @@ def setup_mockloan(work: Path) -> AppRun: ("LN-1002", "Auto", "9100.00", "Seed two"), ("LN-1003", "Home", "120000.00", "Seed three"), ]: - requests.post(base + "/api/disbursement", json={"loan_id": loan, "product": prod, "amount": amt, "memo": memo}, timeout=10) + requests.post( + base + "/api/disbursement", + json={"loan_id": loan, "product": prod, "amount": amt, "memo": memo}, + timeout=10, + ) # The demonstration, recorded; then undone so the sandbox starts seeded only. snapshot = shutil.copy(db.database_path, work / "seeded.sqlite3") rec = Recorder() rec.session.get(base + "/api/disbursements", timeout=10) - params = {"loan_id": "LN-2040", "product": "Personal", "amount": "3150.00", "memo": "Kitchen repair advance"} + params = { + "loan_id": "LN-2040", + "product": "Personal", + "amount": "3150.00", + "memo": "Kitchen repair advance", + } rec.session.post(base + "/api/disbursement", json=params, timeout=10) rec.save(work / "trace.har") shutil.copy(snapshot, db.database_path) - task = _write(work / "task.yaml", { - "instruction": "Authorize a disbursement of 3150.00 on loan LN-2040 (Personal) with the memo 'Kitchen repair advance'.", - "params": params, - }) - sandbox = _write(work / "sandbox.yaml", { - "schema_version": "openadapt.verify-sandbox/v1", - "app": {"base_url": base}, - "actors": {"agent": {"id": "officer-a"}, "other": {"id": "officer-b"}}, - "store": { - "dialect": "sqlite", - "read": {"sqlite_database": str(db.database_path)}, - "admin": {"sqlite_database": str(db.database_path)}, + task = _write( + work / "task.yaml", + { + "instruction": "Authorize a disbursement of 3150.00 on loan LN-2040 (Personal) with the memo 'Kitchen repair advance'.", + "params": params, }, - }) + ) + sandbox = _write( + work / "sandbox.yaml", + { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": base}, + "actors": {"agent": {"id": "officer-a"}, "other": {"id": "officer-b"}}, + "store": { + "dialect": "sqlite", + "read": {"sqlite_database": str(db.database_path)}, + "admin": {"sqlite_database": str(db.database_path)}, + }, + }, + ) return AppRun( - "mockloan", False, "db", work / "trace.har", task, sandbox, + "mockloan", + False, + "db", + work / "trace.har", + task, + sandbox, heldout_payloads=[ {"product": "Auto", "amount": "4420.50", "memo": "Held-out memo A"}, {"product": "Home", "amount": "77000.00", "memo": "Held-out memo B"}, @@ -117,25 +137,94 @@ def _pg_cluster(work: Path, port: int) -> Callable[[], None]: data = work / "pgdata" if data.exists(): shutil.rmtree(data) - subprocess.run(["initdb", "-D", str(data), "-U", "wb_admin", "--auth=trust", "-E", "UTF8", "--locale=C"], check=True, capture_output=True, env={**os.environ, "LC_ALL": "C"}) subprocess.run( - ["pg_ctl", "-D", str(data), "-o", f"-p {port} -k '' -c listen_addresses=127.0.0.1", "-l", str(work / "pg.log"), "-w", "start"], - check=True, capture_output=True, env={**os.environ, "LC_ALL": "C"}, + [ + "initdb", + "-D", + str(data), + "-U", + "wb_admin", + "--auth=trust", + "-E", + "UTF8", + "--locale=C", + ], + check=True, + capture_output=True, + env={**os.environ, "LC_ALL": "C"}, + ) + subprocess.run( + [ + "pg_ctl", + "-D", + str(data), + "-o", + f"-p {port} -k '' -c listen_addresses=127.0.0.1", + "-l", + str(work / "pg.log"), + "-w", + "start", + ], + check=True, + capture_output=True, + env={**os.environ, "LC_ALL": "C"}, ) for sql in ("CREATE ROLE wb_reader LOGIN", "CREATE DATABASE wb_mockmed"): - subprocess.run(["psql", "-h", "127.0.0.1", "-p", str(port), "-U", "wb_admin", "-d", "postgres", "-c", sql], check=True, capture_output=True) + subprocess.run( + [ + "psql", + "-h", + "127.0.0.1", + "-p", + str(port), + "-U", + "wb_admin", + "-d", + "postgres", + "-c", + sql, + ], + check=True, + capture_output=True, + ) def stop() -> None: - subprocess.run(["pg_ctl", "-D", str(data), "-m", "fast", "stop"], capture_output=True) + subprocess.run( + ["pg_ctl", "-D", str(data), "-m", "fast", "stop"], capture_output=True + ) return stop WB_SEED = { "patient": [ - {"mrn": "MRN-1001", "first_name": "Ana", "last_name": "Silva", "dob": "1980-02-11", "phone": "555-0101", "email": "ana.silva@example.org", "_as": "p1"}, - {"mrn": "MRN-1002", "first_name": "Ben", "last_name": "Okafor", "dob": "1975-07-30", "phone": "555-0102", "email": "ben.okafor@example.org", "_as": "p2"}, - {"mrn": "MRN-1003", "first_name": "Chen", "last_name": "Wu", "dob": "1990-12-01", "phone": "555-0103", "email": "chen.wu@example.org", "_as": "p3"}, + { + "mrn": "MRN-1001", + "first_name": "Ana", + "last_name": "Silva", + "dob": "1980-02-11", + "phone": "555-0101", + "email": "ana.silva@example.org", + "_as": "p1", + }, + { + "mrn": "MRN-1002", + "first_name": "Ben", + "last_name": "Okafor", + "dob": "1975-07-30", + "phone": "555-0102", + "email": "ben.okafor@example.org", + "_as": "p2", + }, + { + "mrn": "MRN-1003", + "first_name": "Chen", + "last_name": "Wu", + "dob": "1990-12-01", + "phone": "555-0103", + "email": "chen.wu@example.org", + "_as": "p3", + }, ], "encounter": [ {"patient_id": "$p1", "type": "Triage", "note": "Seed visit one"}, @@ -145,8 +234,6 @@ def stop() -> None: def setup_workbench(work: Path, port: int = 9796) -> AppRun: - from openadapt_flow.taskgen import workbench as W - from openadapt_flow.taskgen.profile import load_profile started = time.monotonic() work.mkdir(parents=True, exist_ok=True) @@ -159,7 +246,9 @@ def setup_workbench(work: Path, port: int = 9796) -> AppRun: raise -def _workbench(work: Path, port: int, dsn: str, stop_pg: Callable[[], None], started: float) -> AppRun: +def _workbench( + work: Path, port: int, dsn: str, stop_pg: Callable[[], None], started: float +) -> AppRun: from openadapt_flow.taskgen import workbench as W from openadapt_flow.taskgen.profile import load_profile @@ -167,30 +256,76 @@ def _workbench(work: Path, port: int, dsn: str, stop_pg: Callable[[], None], sta wb.store.reset(WB_SEED) seeded = wb.store.dump() rec = Recorder() - rec.session.post(url + "/login", data={"username": "clinician", "password": "synthetic"}, allow_redirects=False, timeout=10) + rec.session.post( + url + "/login", + data={"username": "clinician", "password": "synthetic"}, + allow_redirects=False, + timeout=10, + ) pid = next(r["id"] for r in seeded["patient"] if r["mrn"] == "MRN-1002") rec.session.get(f"{url}/e/patient/{pid}/edit", timeout=10) - form = {"__version": "1", "first_name": "Ben", "last_name": "Okafor", "dob": "1975-07-30", - "phone": "555-0177", "email": "b.okafor@clinic.example.org"} - rec.session.post(f"{url}/e/patient/{pid}/edit", data=form, allow_redirects=False, timeout=10) + form = { + "__version": "1", + "first_name": "Ben", + "last_name": "Okafor", + "dob": "1975-07-30", + "phone": "555-0177", + "email": "b.okafor@clinic.example.org", + } + rec.session.post( + f"{url}/e/patient/{pid}/edit", data=form, allow_redirects=False, timeout=10 + ) rec.save(work / "trace.har") wb.store.reset(WB_SEED) # back to the seeded state - task = _write(work / "task.yaml", { - "instruction": "Update patient MRN-1002's phone to 555-0177 and email to b.okafor@clinic.example.org.", - "params": {"mrn": "MRN-1002", "phone": "555-0177", "email": "b.okafor@clinic.example.org"}, - }) - conn = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "127.0.0.1", "port": port, "dbname": "wb_mockmed"}} - sandbox = _write(work / "sandbox.yaml", { - "schema_version": "openadapt.verify-sandbox/v1", - "app": {"base_url": url}, - "actors": {"agent": {"id": "clinician", "login": {"method": "POST", "path": "/login", - "form": {"username": "clinician", "password": "synthetic"}}}}, - "store": { - "dialect": "postgresql", - "read": {**conn, "sql_connect_args": {**conn["sql_connect_args"], "user": "wb_reader"}}, - "admin": {**conn, "sql_connect_args": {**conn["sql_connect_args"], "user": "wb_admin"}}, + task = _write( + work / "task.yaml", + { + "instruction": "Update patient MRN-1002's phone to 555-0177 and email to b.okafor@clinic.example.org.", + "params": { + "mrn": "MRN-1002", + "phone": "555-0177", + "email": "b.okafor@clinic.example.org", + }, + }, + ) + conn = { + "sql_driver": "psycopg2", + "sql_connect_args": {"host": "127.0.0.1", "port": port, "dbname": "wb_mockmed"}, + } + sandbox = _write( + work / "sandbox.yaml", + { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": url}, + "actors": { + "agent": { + "id": "clinician", + "login": { + "method": "POST", + "path": "/login", + "form": {"username": "clinician", "password": "synthetic"}, + }, + } + }, + "store": { + "dialect": "postgresql", + "read": { + **conn, + "sql_connect_args": { + **conn["sql_connect_args"], + "user": "wb_reader", + }, + }, + "admin": { + **conn, + "sql_connect_args": { + **conn["sql_connect_args"], + "user": "wb_admin", + }, + }, + }, }, - }) + ) def teardown() -> None: stop_app() @@ -198,7 +333,12 @@ def teardown() -> None: stop_pg() return AppRun( - "workbench", False, "db", work / "trace.har", task, sandbox, + "workbench", + False, + "db", + work / "trace.har", + task, + sandbox, heldout_payloads=[ {"phone": "555-0901", "email": "heldout.a@example.org"}, {"phone": "555-0902", "email": "heldout.b@example.org"}, @@ -207,10 +347,17 @@ def teardown() -> None: {"phone": "555-0905", "email": "heldout.e@example.org"}, ], other_record={}, - operator_inputs=["app base URL", "agent sign-in (user, password)", "read-only DB connection", "admin DB connection"], + operator_inputs=[ + "app base URL", + "agent sign-in (user, password)", + "read-only DB connection", + "admin DB connection", + ], teardown=teardown, setup_seconds=round(time.monotonic() - started, 1), - notes=["the workbench signs in one user only: no second actor, so no lost-update case and no actor axis"], + notes=[ + "the workbench signs in one user only: no second actor, so no lost-update case and no actor axis" + ], ) @@ -233,77 +380,195 @@ def setup_mealie(work: Path) -> AppRun: os.environ.setdefault("VD_MEALIE_READER_PW", "vd-synthetic-reader") os.environ.setdefault("VD_MEALIE_ADMIN_PW", "MyPassword") os.environ.setdefault("VD_MEALIE_COOK_PW", "vd-synthetic-cook") - con = psycopg2.connect(host="127.0.0.1", port=MEALIE_PG_PORT, user="mealie", password=os.environ["VD_MEALIE_PG_PW"], dbname="mealie") + con = psycopg2.connect( + host="127.0.0.1", + port=MEALIE_PG_PORT, + user="mealie", + password=os.environ["VD_MEALIE_PG_PW"], + dbname="mealie", + ) con.autocommit = True cur = con.cursor() cur.execute("SELECT 1 FROM pg_roles WHERE rolname='vd_reader'") if not cur.fetchone(): - cur.execute("CREATE ROLE vd_reader LOGIN PASSWORD %s", (os.environ["VD_MEALIE_READER_PW"],)) + cur.execute( + "CREATE ROLE vd_reader LOGIN PASSWORD %s", + (os.environ["VD_MEALIE_READER_PW"],), + ) cur.execute("GRANT USAGE ON SCHEMA public TO vd_reader") cur.execute("GRANT SELECT ON ALL TABLES IN SCHEMA public TO vd_reader") + cur.execute("GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO vd_reader") con.close() def token(user: str, pw: str) -> dict[str, str]: - r = requests.post(MEALIE + "/api/auth/token", data={"username": user, "password": pw}, timeout=30) + r = requests.post( + MEALIE + "/api/auth/token", + data={"username": user, "password": pw}, + timeout=30, + ) r.raise_for_status() return {"Authorization": "Bearer " + r.json()["access_token"]} admin = token("changeme@example.com", os.environ["VD_MEALIE_ADMIN_PW"]) me = requests.get(MEALIE + "/api/users/self", headers=admin, timeout=30).json() - users = requests.get(MEALIE + "/api/admin/users?perPage=50", headers=admin, timeout=30).json().get("items", []) + users = ( + requests.get(MEALIE + "/api/admin/users?perPage=50", headers=admin, timeout=30) + .json() + .get("items", []) + ) cook = next((u for u in users if u.get("username") == "cook2"), None) if cook is None: - r = requests.post(MEALIE + "/api/admin/users", headers=admin, timeout=30, json={ - "username": "cook2", "fullName": "Second Cook", "email": "cook2@example.org", - "password": os.environ["VD_MEALIE_COOK_PW"], "group": me["group"], "household": me["household"], - "admin": False, "canInvite": False, "canManage": True, "canOrganize": True, - }) + r = requests.post( + MEALIE + "/api/admin/users", + headers=admin, + timeout=30, + json={ + "username": "cook2", + "fullName": "Second Cook", + "email": "cook2@example.org", + "password": os.environ["VD_MEALIE_COOK_PW"], + "group": me["group"], + "household": me["household"], + "admin": False, + "canInvite": False, + "canManage": True, + "canOrganize": True, + }, + ) r.raise_for_status() cook = r.json() - for name, desc in [("Lentil soup", "Seed recipe one"), ("Rye bread", "Seed recipe two"), ("Plum cake", "Seed recipe three")]: - r = requests.post(MEALIE + "/api/recipes", headers=admin, json={"name": name}, timeout=30) + for name, desc in [ + ("Lentil soup", "Seed recipe one"), + ("Rye bread", "Seed recipe two"), + ("Plum cake", "Seed recipe three"), + ]: + r = requests.post( + MEALIE + "/api/recipes", headers=admin, json={"name": name}, timeout=30 + ) if r.status_code < 300: - requests.patch(MEALIE + f"/api/recipes/{r.json()}", headers=admin, json={"description": desc, "recipeYield": "4 servings"}, timeout=30) + requests.patch( + MEALIE + f"/api/recipes/{r.json()}", + headers=admin, + json={"description": desc, "recipeYield": "4 servings"}, + timeout=30, + ) # The demonstration: one PATCH on lentil-soup, recorded, then undone. - before = requests.get(MEALIE + "/api/recipes/lentil-soup", headers=admin, timeout=30).json() + before = requests.get( + MEALIE + "/api/recipes/lentil-soup", headers=admin, timeout=30 + ).json() rec = Recorder(admin) rec.session.get(MEALIE + "/api/recipes/lentil-soup", timeout=30) - params = {"slug": "lentil-soup", "description": "Red lentils, cumin and lemon. Ready in 40 minutes.", "recipe_yield": "6 bowls"} - rec.session.patch(MEALIE + "/api/recipes/lentil-soup", json={"description": params["description"], "recipeYield": params["recipe_yield"]}, timeout=30) + params = { + "slug": "lentil-soup", + "description": "Red lentils, cumin and lemon. Ready in 40 minutes.", + "recipe_yield": "6 bowls", + } + rec.session.patch( + MEALIE + "/api/recipes/lentil-soup", + json={ + "description": params["description"], + "recipeYield": params["recipe_yield"], + }, + timeout=30, + ) rec.save(work / "trace.har") - requests.patch(MEALIE + "/api/recipes/lentil-soup", headers=admin, json={"description": before.get("description"), "recipeYield": before.get("recipeYield")}, timeout=30) - (work / "openapi.json").write_text(requests.get(MEALIE + "/openapi.json", timeout=30).text, encoding="utf-8") - task = _write(work / "task.yaml", { - "instruction": "Update the recipe lentil-soup: set its description to 'Red lentils, cumin and lemon. Ready in 40 minutes.' and its yield to '6 bowls'.", - "params": params, - }) - pg = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "127.0.0.1", "port": MEALIE_PG_PORT, "dbname": "mealie"}} - sandbox = _write(work / "sandbox.yaml", { - "schema_version": "openadapt.verify-sandbox/v1", - "app": {"base_url": MEALIE}, - "actors": { - "agent": {"id": me["id"], "login": {"method": "POST", "path": "/api/auth/token", "token_field": "access_token", - "form": {"username": "changeme@example.com", "password": "${VD_MEALIE_ADMIN_PW}"}}}, - "other": {"id": cook["id"], "login": {"method": "POST", "path": "/api/auth/token", "token_field": "access_token", - "form": {"username": "cook2", "password": "${VD_MEALIE_COOK_PW}"}}}, + requests.patch( + MEALIE + "/api/recipes/lentil-soup", + headers=admin, + json={ + "description": before.get("description"), + "recipeYield": before.get("recipeYield"), }, - "store": { - "dialect": "postgresql", - "read": {**pg, "sql_connect_args": {**pg["sql_connect_args"], "user": "vd_reader"}, "sql_password_env": "VD_MEALIE_READER_PW"}, - "admin": {**pg, "sql_connect_args": {**pg["sql_connect_args"], "user": "mealie"}, "sql_password_env": "VD_MEALIE_PG_PW"}, + timeout=30, + ) + (work / "openapi.json").write_text( + requests.get(MEALIE + "/openapi.json", timeout=30).text, encoding="utf-8" + ) + task = _write( + work / "task.yaml", + { + "instruction": "Update the recipe lentil-soup: set its description to 'Red lentils, cumin and lemon. Ready in 40 minutes.' and its yield to '6 bowls'.", + "params": params, + }, + ) + pg = { + "sql_driver": "psycopg2", + "sql_connect_args": { + "host": "127.0.0.1", + "port": MEALIE_PG_PORT, + "dbname": "mealie", }, - }) + } + sandbox = _write( + work / "sandbox.yaml", + { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": MEALIE}, + "actors": { + "agent": { + "id": me["id"], + "login": { + "method": "POST", + "path": "/api/auth/token", + "token_field": "access_token", + "form": { + "username": "changeme@example.com", + "password": "${VD_MEALIE_ADMIN_PW}", + }, + }, + }, + "other": { + "id": cook["id"], + "login": { + "method": "POST", + "path": "/api/auth/token", + "token_field": "access_token", + "form": { + "username": "cook2", + "password": "${VD_MEALIE_COOK_PW}", + }, + }, + }, + }, + "store": { + "dialect": "postgresql", + "read": { + **pg, + "sql_connect_args": {**pg["sql_connect_args"], "user": "vd_reader"}, + "sql_password_env": "VD_MEALIE_READER_PW", + }, + "admin": { + **pg, + "sql_connect_args": {**pg["sql_connect_args"], "user": "mealie"}, + "sql_password_env": "VD_MEALIE_PG_PW", + }, + }, + }, + ) return AppRun( - "mealie", True, str(work / "openapi.json"), work / "trace.har", task, sandbox, + "mealie", + True, + str(work / "openapi.json"), + work / "trace.har", + task, + sandbox, heldout_payloads=[ {"description": "Held-out description A.", "recipe_yield": "2 bowls"}, - {"description": "Held-out description B, with a comma.", "recipe_yield": "8 servings"}, + { + "description": "Held-out description B, with a comma.", + "recipe_yield": "8 servings", + }, {"description": "Held-out description C.", "recipe_yield": "1 pot"}, {"description": "Held-out description D.", "recipe_yield": "3 bowls"}, {"description": "Held-out description E.", "recipe_yield": "10 servings"}, ], other_record={"slug": "rye-bread"}, - operator_inputs=["app base URL", "two users' sign-in (user, password env)", "read-only DB connection", "admin DB connection"], + operator_inputs=[ + "app base URL", + "two users' sign-in (user, password env)", + "read-only DB connection", + "admin DB connection", + ], setup_seconds=round(time.monotonic() - started, 1), ) diff --git a/packages/flow/benchmark/verify_draft/har.py b/packages/flow/benchmark/verify_draft/har.py index 095124f06b..200bf105b3 100644 --- a/packages/flow/benchmark/verify_draft/har.py +++ b/packages/flow/benchmark/verify_draft/har.py @@ -28,13 +28,21 @@ def _hook(self, r: requests.Response, *args: Any, **kwargs: Any) -> None: "url": req.url, # Sign-in material is never kept in the trace file. "headers": [ - {"name": k, "value": "REDACTED" if k.lower() in ("authorization", "cookie") else v} + { + "name": k, + "value": "REDACTED" + if k.lower() in ("authorization", "cookie") + else v, + } for k, v in req.headers.items() ], }, "response": { "status": r.status_code, - "content": {"mimeType": r.headers.get("Content-Type", ""), "text": r.text[:20000]}, + "content": { + "mimeType": r.headers.get("Content-Type", ""), + "text": r.text[:20000], + }, }, } if body is not None: @@ -43,6 +51,15 @@ def _hook(self, r: requests.Response, *args: Any, **kwargs: Any) -> None: def save(self, path: Path) -> None: path.write_text( - json.dumps({"log": {"version": "1.2", "creator": {"name": "verify-draft-bench"}, "entries": self.entries}}, indent=1), + json.dumps( + { + "log": { + "version": "1.2", + "creator": {"name": "verify-draft-bench"}, + "entries": self.entries, + } + }, + indent=1, + ), encoding="utf-8", ) diff --git a/packages/flow/benchmark/verify_draft/report.py b/packages/flow/benchmark/verify_draft/report.py new file mode 100644 index 0000000000..325d1190a2 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/report.py @@ -0,0 +1,49 @@ +"""Print the per-app table from results//result.json (Markdown).""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +RESULTS = Path(__file__).resolve().parent / "results" + + +def row(r: dict) -> str: + h = r.get("heldout") or {} + adm_faults = [x for x in r["rounds"] if x.get("admitted")] + caught = ( + f"{adm_faults[0]['faults_caught']}/{adm_faults[0]['faults_applicable']}" + if adm_faults + else "-" + ) + held = f"{h['faults_caught']}/{h['faults_applicable']}" if h else "-" + clean_adm = ( + f"{len(adm_faults[0]['false_stops'])}/{adm_faults[0]['clean']}" + if adm_faults + else "-" + ) + clean_held = f"{len(h['false_stops'])}/{h['clean']}" if h else "-" + return ( + f"| {r['app']}{' (untuned)' if r['untuned'] else ''} | {r['describe']} | {r['setup_minutes']:.1f} | " + f"{r['person_decisions']} | {r['drafts_admitted']} / {r['drafts_rejected']} | {caught} | {held} | " + f"{clean_adm} | {clean_held} | {r['model_usd']:.2f} |" + ) + + +def main(names: list[str]) -> int: + print( + "| App | Description | Setup minutes | Person decisions | Drafts admitted / rejected | " + "Planted faults caught (admission) | Planted faults caught (held out) | " + "False stops (admission clean writes) | False stops (held-out clean writes) | Model USD |" + ) + print("|---|---|---|---|---|---|---|---|---|---|") + for name in names or sorted( + p.name for p in RESULTS.iterdir() if (p / "result.json").is_file() + ): + print(row(json.loads((RESULTS / name / "result.json").read_text()))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/packages/flow/benchmark/verify_draft/results/.gitignore b/packages/flow/benchmark/verify_draft/results/.gitignore new file mode 100644 index 0000000000..172deabf51 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/.gitignore @@ -0,0 +1,10 @@ +# Per-case verifier state (baselines, receipts): large and regenerated by a run. +**/work/ +**/heldout-work/ +# The operator's local stores. +**/pgdata/ +**/*.sqlite3 +**/pg.log +# Mealie's OpenAPI document is generated from AGPL code: fetched at run time +# (GET /openapi.json), never committed. +**/openapi.json diff --git a/packages/flow/benchmark/verify_draft/results/mealie.log b/packages/flow/benchmark/verify_draft/results/mealie.log new file mode 100644 index 0000000000..5df9ad8be2 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie.log @@ -0,0 +1,61 @@ +[mealie] store: 62 tables; trace: 1 write request(s) +[mealie] demonstration: changed recipes, columns ['description', 'recipe_yield'] +[mealie] round 1: draft refused before testing: the contract does not load: invalid draft: 2 validation errors for VerifyConfig +frame.database.allow_tables.0.contents unchanged + Extra inputs are not permitted [type=extra_forbidden, input_value=None, input_type=NoneType] + For further information visit https://errors.pydantic.dev/2.14/v/extra_forbidden +frame.database.allow_tables.3.contents unchanged + Extra inputs are not permitted [type=extra_forbidden, input_value=None, input_type=NoneType] + For further information visit https://errors.pydantic.dev/2.14/v/extra_forbidden +[mealie] round 2: rejected (16/17 cases, 147s) +[mealie] round 3: rejected (0/1 cases, 7s) +{ + "app": "mealie", + "untuned": true, + "describe": "openapi", + "operator_setup_seconds": 3.4, + "operator_inputs": [ + "app base URL", + "two users' sign-in (user, password env)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 4.01, + "person_decisions": 0, + "questions": [], + "drafts": 3, + "drafts_admitted": 0, + "drafts_rejected": 3, + "admitted": false, + "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: lost update: the target moved more than one version in the window, and only one save is the agent's\n[FAILED] stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.4366, + "rounds": [ + { + "admitted": false, + "faults_applicable": 7, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 146.55 + }, + { + "admitted": false, + "faults_applicable": 0, + "faults_caught": 0, + "clean": 1, + "false_stops": [ + "clean-1" + ], + "probe_writes_confirmed": 0, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 6.7 + } + ], + "notes": [] +} diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/report.json b/packages/flow/benchmark/verify_draft/results/mealie/draft/report.json new file mode 100644 index 0000000000..30d9f1b6ff --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/draft/report.json @@ -0,0 +1,34 @@ +{ + "admitted": false, + "rounds": 3, + "person_decisions": 0, + "seconds": 240.9, + "model_usd": 0.4366, + "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: lost update: the target moved more than one version in the window, and only one save is the agent's\n[FAILED] stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)", + "contract": null, + "questions": [], + "rounds_detail": [ + { + "admitted": false, + "cases": 17, + "passed": 16, + "failed": [ + "lost_update" + ], + "problems": [], + "attribution_problems": [] + }, + { + "admitted": false, + "cases": 1, + "passed": 0, + "failed": [ + "clean-1" + ], + "problems": [ + "stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)" + ], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..f70a822c36 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-1.yaml @@ -0,0 +1,33 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield", CAST(r."group_id" AS TEXT) AS "group_id" FROM "recipes" r +effects: +- kind: record_written + probe: surface=record|recipe by slug has the new description and yield + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: Mealie deletes and re-inserts a recipe's instruction rows with new ids on every PATCH, contents unchanged} + - {table: recipe_nutrition, mode: skip, reason: Mealie deletes and re-inserts the recipe's nutrition row with a new id on every PATCH} + - {table: recipe_settings, mode: skip, reason: Mealie deletes and re-inserts the recipe's settings row with a new id on every PATCH} + - {table: recipes_ingredients, mode: skip, reason: Mealie deletes and re-inserts the recipe's ingredient rows with new ids on every PATCH, contents unchanged} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.admission.json b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.admission.json new file mode 100644 index 0000000000..3c4c74fb67 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.admission.json @@ -0,0 +1,777 @@ +{ + "admitted": false, + "check_sha256": "sha256:96ccbbe7abff640b70876249672b25ba61c10a3dddac8a7bde46e915ffbc998d", + "problems": [], + "masked": [], + "seconds": 146.55, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.41 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 10.25 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 10.16 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.81 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.1 + }, + { + "group": "fault", + "name": "wrong_value:description", + "detail": "recipes.description holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.79 + }, + { + "group": "fault", + "name": "wrong_value:recipe_yield", + "detail": "recipes.recipe_yield holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 10.69 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another recipes row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.91 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the recipes record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "added", + "columns": [ + "created_at", + "date_added", + "description", + "description_normalized", + "group_id", + "id", + "is_ocr_recipe", + "name", + "name_normalized", + "recipe_servings", + "recipe_yield", + "recipe_yield_quantity", + "slug", + "user_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.75 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another recipes row's created_at edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "created_at" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 7.69 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the recipes write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 9.38 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.4 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.42 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.06 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.5 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.04 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.29 + } + ], + "attribution": [ + { + "table": "recipe_instructions", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "id", + "cause": "fresh", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "position", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "summary", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "text", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "title", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "type", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "calories", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "carbohydrate_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "cholesterol_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "fiber_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "id", + "cause": "fresh", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "protein_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "saturated_fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "sodium_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "sugar_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "trans_fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "unsaturated_fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "disable_amount", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "disable_comments", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "id", + "cause": "fresh", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "landscape_view", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "locked", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "public", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "show_assets", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "show_nutrition", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes", + "column": "date_updated", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes", + "column": "description", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "description_normalized", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "recipe_yield", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "food_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "id", + "cause": "fresh", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "note", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "note_normalized", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "original_text", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "original_text_normalized", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "position", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "quantity", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "reference_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "title", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "unit_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.yaml b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.yaml new file mode 100644 index 0000000000..e7b1e1cb49 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.yaml @@ -0,0 +1,33 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield", CAST(r."group_id" AS TEXT) AS "group_id" FROM "recipes" r +effects: +- kind: record_written + probe: "surface=record|recipe by slug has the new description and yield" + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: "Mealie deletes and re-inserts the recipe instruction rows with new ids on every PATCH; contents are unchanged"} + - {table: recipe_nutrition, mode: skip, reason: "Mealie deletes and re-inserts the recipe nutrition row with a new id on every PATCH"} + - {table: recipe_settings, mode: skip, reason: "Mealie deletes and re-inserts the recipe settings row with a new id on every PATCH"} + - {table: recipes_ingredients, mode: skip, reason: "Mealie deletes and re-inserts the recipe ingredient rows with new ids on every PATCH; contents are unchanged"} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.admission.json b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.admission.json new file mode 100644 index 0000000000..20c984c291 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.admission.json @@ -0,0 +1,28 @@ +{ + "admitted": false, + "check_sha256": "sha256:907aa835521b6e12ab1a15031919b2ffec3bbaaf255cec6c0a5a2c4d4ac6fb8e", + "problems": [ + "stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)" + ], + "masked": [], + "seconds": 6.7, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "lost update: the target moved more than one version in the window, and only one save is the agent's" + ], + "moved": [], + "seconds": 5.73 + } + ], + "attribution": [] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.yaml b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.yaml new file mode 100644 index 0000000000..ec7f0bfc8a --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.yaml @@ -0,0 +1,39 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield", CAST(r."group_id" AS TEXT) AS "group_id" FROM "recipes" r +effects: +- kind: record_written + probe: "surface=record|recipe by slug has the new description and yield" + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: "Mealie deletes and re-inserts the recipe instruction rows with new ids on every PATCH; contents are unchanged"} + - {table: recipe_nutrition, mode: skip, reason: "Mealie deletes and re-inserts the recipe nutrition row with a new id on every PATCH; the save count is judged by frame.versions"} + - {table: recipe_settings, mode: skip, reason: "Mealie deletes and re-inserts the recipe settings row with a new id on every PATCH"} + - {table: recipes_ingredients, mode: skip, reason: "Mealie deletes and re-inserts the recipe ingredient rows with new ids on every PATCH; contents are unchanged"} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + versions: + read: {kind: sql, sql_query: "SELECT CAST(r.\"id\" AS TEXT) AS \"id\", CAST(n.\"id\" AS TEXT) AS \"ver\" FROM \"recipe_nutrition\" n JOIN \"recipes\" r ON r.\"id\" = n.\"recipe_id\""} + record_field: id + target_field: id + target_surface: record + version_field: ver diff --git a/packages/flow/benchmark/verify_draft/results/mealie/result.json b/packages/flow/benchmark/verify_draft/results/mealie/result.json new file mode 100644 index 0000000000..8687c5b23e --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/result.json @@ -0,0 +1,94 @@ +{ + "app": "mealie", + "untuned": true, + "describe": "openapi", + "operator_setup_seconds": 3.4, + "operator_inputs": [ + "app base URL", + "two users' sign-in (user, password env)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 4.01, + "person_decisions": 0, + "questions": [], + "drafts": 3, + "drafts_admitted": 0, + "drafts_rejected": 3, + "admitted": false, + "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: lost update: the target moved more than one version in the window, and only one save is the agent's\n[FAILED] stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.4366, + "model_calls": [ + { + "at": 1795247848.794942, + "label": "mealie", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 19909, + "output_tokens": 2429, + "cache_read_tokens": 2155, + "cache_write_tokens": 0, + "usd": 0.128647, + "seconds": 22.47, + "request_id": "", + "stop_reason": "end_turn" + }, + { + "at": 1795247862.9125051, + "label": "mealie", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 21727, + "output_tokens": 1766, + "cache_read_tokens": 2155, + "cache_write_tokens": 0, + "usd": 0.122659, + "seconds": 13.98, + "request_id": "", + "stop_reason": "end_turn" + }, + { + "at": 1795248054.955477, + "label": "mealie", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 23470, + "output_tokens": 4549, + "cache_read_tokens": 2155, + "cache_write_tokens": 0, + "usd": 0.185291, + "seconds": 45.48, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": false, + "faults_applicable": 7, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 146.55 + }, + { + "admitted": false, + "faults_applicable": 0, + "faults_caught": 0, + "clean": 1, + "false_stops": [ + "clean-1" + ], + "probe_writes_confirmed": 0, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 6.7 + } + ], + "notes": [] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mealie/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/mealie/setup/sandbox.yaml new file mode 100644 index 0000000000..5e3e99205f --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/setup/sandbox.yaml @@ -0,0 +1,40 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:9664 +actors: + agent: + id: 2c154b37-6a87-4f15-8e2a-40e67cf3f48a + login: + method: POST + path: /api/auth/token + token_field: access_token + form: + username: changeme@example.com + password: ${VD_MEALIE_ADMIN_PW} + other: + id: fba45ac9-e83c-43c7-b1d4-6681298112bd + login: + method: POST + path: /api/auth/token + token_field: access_token + form: + username: cook2 + password: ${VD_MEALIE_COOK_PW} +store: + dialect: postgresql + read: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: mealie + user: vd_reader + sql_password_env: VD_MEALIE_READER_PW + admin: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: mealie + user: mealie + sql_password_env: VD_MEALIE_PG_PW diff --git a/packages/flow/benchmark/verify_draft/results/mealie/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/mealie/setup/task.yaml new file mode 100644 index 0000000000..485fad004e --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/setup/task.yaml @@ -0,0 +1,6 @@ +instruction: 'Update the recipe lentil-soup: set its description to ''Red lentils, + cumin and lemon. Ready in 40 minutes.'' and its yield to ''6 bowls''.' +params: + slug: lentil-soup + description: Red lentils, cumin and lemon. Ready in 40 minutes. + recipe_yield: 6 bowls diff --git a/packages/flow/benchmark/verify_draft/results/mealie/setup/trace.har b/packages/flow/benchmark/verify_draft/results/mealie/setup/trace.har new file mode 100644 index 0000000000..8df4e4f341 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mealie/setup/trace.har @@ -0,0 +1,92 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:9664/api/recipes/lentil-soup", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"id\":\"1f5d6734-67f6-4a87-a3e6-acf53a925156\",\"userId\":\"2c154b37-6a87-4f15-8e2a-40e67cf3f48a\",\"householdId\":\"3c5f894e-16da-4ee0-afad-1ab5e8feed46\",\"groupId\":\"3fdfcd86-9230-44ab-a791-56c03e904514\",\"name\":\"Lentil soup\",\"slug\":\"lentil-soup\",\"image\":null,\"recipeServings\":0.0,\"recipeYieldQuantity\":0.0,\"recipeYield\":\"4 servings\",\"totalTime\":null,\"prepTime\":null,\"cookTime\":null,\"performTime\":null,\"description\":\"Seed recipe one\",\"recipeCategory\":[],\"tags\":[],\"tools\":[],\"rating\":null,\"orgURL\":null,\"dateAdded\":\"2026-11-21\",\"dateUpdated\":\"2026-11-21T07:56:58.154714Z\",\"createdAt\":\"2026-11-21T07:56:57.399114Z\",\"updatedAt\":\"2026-11-21T07:56:58.157615Z\",\"lastMade\":null,\"recipeIngredient\":[{\"quantity\":1.0,\"unit\":null,\"food\":null,\"note\":\"1 Cup Flour\",\"isFood\":false,\"disableAmount\":true,\"display\":\"1 Cup Flour\",\"title\":null,\"originalText\":null,\"referenceId\":\"5efea35b-b688-4e68-b39a-e52900fc9e68\"}],\"recipeInstructions\":[{\"id\":\"438ea665-2b42-4b05-9aa5-9fd5d3420bcf\",\"title\":\"\",\"summary\":\"\",\"text\":\"Recipe steps as well as other fields in the recipe page support markdown syntax.\\n\\n**Add a link**\\n\\n[My Link](https://demo.mealie.io)\\n\",\"ingredientReferences\":[]}],\"nutrition\":{\"calories\":null,\"carbohydrateContent\":null,\"cholesterolContent\":null,\"fatContent\":null,\"fiberContent\":null,\"proteinContent\":null,\"saturatedFatContent\":null,\"sodiumContent\":null,\"sugarContent\":null,\"transFatContent\":null,\"unsaturatedFatContent\":null},\"settings\":{\"public\":false,\"showNutrition\":false,\"showAssets\":false,\"landscapeView\":false,\"disableComments\":false,\"disableAmount\":true,\"locked\":false},\"assets\":[],\"notes\":[],\"extras\":{},\"comments\":[]}" + } + } + }, + { + "request": { + "method": "PATCH", + "url": "http://127.0.0.1:9664/api/recipes/lentil-soup", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + }, + { + "name": "Content-Length", + "value": "95" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ], + "postData": { + "mimeType": "application/json", + "text": "{\"description\": \"Red lentils, cumin and lemon. Ready in 40 minutes.\", \"recipeYield\": \"6 bowls\"}" + } + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"id\":\"1f5d6734-67f6-4a87-a3e6-acf53a925156\",\"userId\":\"2c154b37-6a87-4f15-8e2a-40e67cf3f48a\",\"householdId\":\"3c5f894e-16da-4ee0-afad-1ab5e8feed46\",\"groupId\":\"3fdfcd86-9230-44ab-a791-56c03e904514\",\"name\":\"Lentil soup\",\"slug\":\"lentil-soup\",\"image\":null,\"recipeServings\":0.0,\"recipeYieldQuantity\":0.0,\"recipeYield\":\"6 bowls\",\"totalTime\":null,\"prepTime\":null,\"cookTime\":null,\"performTime\":null,\"description\":\"Red lentils, cumin and lemon. Ready in 40 minutes.\",\"recipeCategory\":[],\"tags\":[],\"tools\":[],\"rating\":null,\"orgURL\":null,\"dateAdded\":\"2026-11-21\",\"dateUpdated\":\"2026-11-21T07:56:58.985598Z\",\"createdAt\":\"2026-11-21T07:56:57.399114Z\",\"updatedAt\":\"2026-11-21T07:56:58.987017Z\",\"lastMade\":null,\"recipeIngredient\":[{\"quantity\":1.0,\"unit\":null,\"food\":null,\"note\":\"1 Cup Flour\",\"isFood\":false,\"disableAmount\":true,\"display\":\"1 Cup Flour\",\"title\":null,\"originalText\":null,\"referenceId\":\"5efea35b-b688-4e68-b39a-e52900fc9e68\"}],\"recipeInstructions\":[{\"id\":\"15ede9c4-83d1-45ed-a6e9-872631703c03\",\"title\":\"\",\"summary\":\"\",\"text\":\"Recipe steps as well as other fields in the recipe page support markdown syntax.\\n\\n**Add a link**\\n\\n[My Link](https://demo.mealie.io)\\n\",\"ingredientReferences\":[]}],\"nutrition\":{\"calories\":null,\"carbohydrateContent\":null,\"cholesterolContent\":null,\"fatContent\":null,\"fiberContent\":null,\"proteinContent\":null,\"saturatedFatContent\":null,\"sodiumContent\":null,\"sugarContent\":null,\"transFatContent\":null,\"unsaturatedFatContent\":null},\"settings\":{\"public\":false,\"showNutrition\":false,\"showAssets\":false,\"landscapeView\":false,\"disableComments\":false,\"disableAmount\":true,\"locked\":false},\"assets\":[],\"notes\":[],\"extras\":{},\"comments\":[]}" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan.log b/packages/flow/benchmark/verify_draft/results/mockloan.log new file mode 100644 index 0000000000..edc9031477 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan.log @@ -0,0 +1,421 @@ +[mockloan] store: 2 tables; trace: 1 write request(s) +[mockloan] demonstration: added records, columns ['amount', 'loan_id', 'memo', 'product'] +[mockloan] round 1: ADMITTED (19/19 cases, 67s) +{ + "app": "mockloan", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 0.0, + "operator_inputs": [ + "app base URL", + "SQLite file path (read and admin)" + ], + "setup_minutes": 1.36, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.0446, + "rounds": [ + { + "admitted": true, + "faults_applicable": 8, + "faults_caught": 8, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the write creates a record; nothing can be overwritten" + }, + "seconds": 66.86 + } + ], + "notes": [ + "MockLoan has no sign-in: the two actors send identical requests" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.81 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.02 + }, + { + "group": "fault", + "name": "wrong_value:amount", + "detail": "records.amount holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.24 + }, + { + "group": "fault", + "name": "wrong_value:loan_id", + "detail": "records.loan_id holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "wrong_value:memo", + "detail": "records.memo holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.23 + }, + { + "group": "fault", + "name": "wrong_value:product", + "detail": "records.product holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the new records row is filed under another loan_id", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the records record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.24 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another records row's loan_id edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "changed", + "columns": [ + "loan_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.03 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the records write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (removed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.59 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "note": "the write creates a record; nothing can be overwritten", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "fault", + "name": "app_sibling", + "detail": "the same write also sent to {'loan_id': 'LN-1002'} through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.02 + }, + { + "group": "fault", + "name": "app_duplicate", + "detail": "the write sent twice through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.22 + } + ], + "faults_applicable": 10, + "faults_caught": 10, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml new file mode 100644 index 0000000000..6b0a203d0b --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml @@ -0,0 +1,81 @@ +# Drafted by a model and admitted by OpenAdapt qualification (openadapt verify draft). Runs make no model calls. +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."loan_id" AS TEXT) AS + "loan_id", CAST(t."product" AS TEXT) AS "product", CAST(t."amount" AS TEXT) + AS "amount", CAST(t."memo" AS TEXT) AS "memo", CAST(t."source" AS TEXT) AS + "source", CAST(t."record_key" AS TEXT) AS "record_key", CAST(t."surface" AS + TEXT) AS "surface" FROM "records" t + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-snz8cvz_/ledger.sqlite3 +effects: +- kind: record_written + probe: surface=record|one new disbursement on the named loan with the requested + amount and memo + match: + loan_id: + param: loan_id + product: + param: product + amount: + param: amount + memo: + param: memo + surface: + literal: disbursements + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: [] + database: + dialect: sqlite + views: + records: record + new_row_fields: + records: + - id + - source + - record_key + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + read: + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-snz8cvz_/ledger.sqlite3 +provenance: + drafted_by: + model: claude-opus-5-5 + response_model: claude-opus-5-5 + effort: medium + prompt_version: verify-draft-prompt/1 + prompt_sha256: sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840 + inputs: + description: + kind: database + file_sha256: null + text_sha256: sha256:c7f7799fc546b02f8effe2dcdbdb61cc87ab763ffbd609cb1fad04e215d670ac + trace_sha256: sha256:65c477b28f41af6b8bc2d380f412b5091179d329de8c25c9f9610faecf55b822 + task_sha256: sha256:5138e45fc7e532b1fb3abe9d915118eadf1e98e1e659cf6a7abb27bc179e01d9 + admission: + suite: openadapt.verify-draft-admission/v1 + check_sha256: sha256:be5df3f76f12199b68f6c0dfbaeb044d131940b11cb9fa13d08e7c5a242c9d47 + rounds: 1 + admitted_at: '2026-11-21T07:55:36Z' + recheck_window_tested_s: 2.0 + faults: + wrong_value:amount: refuted + wrong_value:loan_id: refuted + wrong_value:memo: refuted + wrong_value:product: refuted + wrong_row: refuted + duplicate: refuted + sibling_edit: refuted + late_revert: refuted + lost_update: 'not applicable: the write creates a record; nothing can be overwritten' + clean_writes_confirmed: 5 + attribution_probe_writes: 5 + bookkeeping_confirmed_by_person: [] diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json b/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json new file mode 100644 index 0000000000..07dd09fa52 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json @@ -0,0 +1,20 @@ +{ + "admitted": true, + "rounds": 1, + "person_decisions": 0, + "seconds": 81.9, + "model_usd": 0.0446, + "reason": "admitted", + "contract": "benchmark/verify_draft/results/mockloan/draft/contract.yaml", + "questions": [], + "rounds_detail": [ + { + "admitted": true, + "cases": 19, + "passed": 19, + "failed": [], + "problems": [], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..fd8974b3b7 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json @@ -0,0 +1,463 @@ +{ + "admitted": true, + "check_sha256": "sha256:be5df3f76f12199b68f6c0dfbaeb044d131940b11cb9fa13d08e7c5a242c9d47", + "problems": [], + "masked": [], + "seconds": 66.86, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.67 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.13 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.88 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "fault", + "name": "wrong_value:amount", + "detail": "records.amount holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.26 + }, + { + "group": "fault", + "name": "wrong_value:loan_id", + "detail": "records.loan_id holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.28 + }, + { + "group": "fault", + "name": "wrong_value:memo", + "detail": "records.memo holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.23 + }, + { + "group": "fault", + "name": "wrong_value:product", + "detail": "records.product holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the new records row is filed under another loan_id", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.24 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the records record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.23 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another records row's loan_id edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "changed", + "columns": [ + "loan_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.04 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the records write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (removed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.5 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "note": "the write creates a record; nothing can be overwritten", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.03 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.07 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.02 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.03 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.03 + } + ], + "attribution": [ + { + "table": "records", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "amount", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "loan_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "memo", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "product", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "record_key", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "source", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "surface", + "cause": "constant", + "excluded": false, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..3c743ec997 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml @@ -0,0 +1,31 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."loan_id" AS TEXT) AS "loan_id", CAST(t."product" AS TEXT) AS "product", CAST(t."amount" AS TEXT) AS "amount", CAST(t."memo" AS TEXT) AS "memo", CAST(t."source" AS TEXT) AS "source", CAST(t."record_key" AS TEXT) AS "record_key", CAST(t."surface" AS TEXT) AS "surface" FROM "records" t +effects: +- kind: record_written + probe: surface=record|one new disbursement on the named loan with the requested amount and memo + match: + loan_id: {param: loan_id} + product: {param: product} + amount: {param: amount} + memo: {param: memo} + surface: {literal: disbursements} + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: [] + database: + dialect: sqlite + views: + records: record + new_row_fields: + records: [id, source, record_key] + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/result.json b/packages/flow/benchmark/verify_draft/results/mockloan/result.json new file mode 100644 index 0000000000..705faaf021 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/result.json @@ -0,0 +1,434 @@ +{ + "app": "mockloan", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 0.0, + "operator_inputs": [ + "app base URL", + "SQLite file path (read and admin)" + ], + "setup_minutes": 1.36, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.0446, + "model_calls": [ + { + "at": 1795247669.287714, + "label": "mockloan", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 583, + "output_tokens": 1575, + "cache_read_tokens": 0, + "cache_write_tokens": 2155, + "usd": 0.044607, + "seconds": 14.8, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": true, + "faults_applicable": 8, + "faults_caught": 8, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the write creates a record; nothing can be overwritten" + }, + "seconds": 66.86 + } + ], + "notes": [ + "MockLoan has no sign-in: the two actors send identical requests" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.81 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.02 + }, + { + "group": "fault", + "name": "wrong_value:amount", + "detail": "records.amount holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.24 + }, + { + "group": "fault", + "name": "wrong_value:loan_id", + "detail": "records.loan_id holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "wrong_value:memo", + "detail": "records.memo holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.23 + }, + { + "group": "fault", + "name": "wrong_value:product", + "detail": "records.product holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the new records row is filed under another loan_id", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the records record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.24 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another records row's loan_id edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "changed", + "columns": [ + "loan_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.03 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the records write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (removed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.59 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "note": "the write creates a record; nothing can be overwritten", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "fault", + "name": "app_sibling", + "detail": "the same write also sent to {'loan_id': 'LN-1002'} through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.02 + }, + { + "group": "fault", + "name": "app_duplicate", + "detail": "the write sent twice through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.22 + } + ], + "faults_applicable": 10, + "faults_caught": 10, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml new file mode 100644 index 0000000000..89197c2c31 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml @@ -0,0 +1,14 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:58025 +actors: + agent: + id: officer-a + other: + id: officer-b +store: + dialect: sqlite + read: + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-snz8cvz_/ledger.sqlite3 + admin: + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-snz8cvz_/ledger.sqlite3 diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml new file mode 100644 index 0000000000..dacee2d591 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml @@ -0,0 +1,7 @@ +instruction: Authorize a disbursement of 3150.00 on loan LN-2040 (Personal) with the + memo 'Kitchen repair advance'. +params: + loan_id: LN-2040 + product: Personal + amount: '3150.00' + memo: Kitchen repair advance diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har b/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har new file mode 100644 index 0000000000..9b42bd8391 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har @@ -0,0 +1,84 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:58025/api/disbursements", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"records\": [{\"id\": 1, \"loan_id\": \"LN-1001\", \"product\": \"Personal\", \"amount\": \"2500.00\", \"memo\": \"Seed one\", \"source\": \"replay\", \"surface\": \"disbursements\", \"key\": null}, {\"id\": 2, \"loan_id\": \"LN-1002\", \"product\": \"Auto\", \"amount\": \"9100.00\", \"memo\": \"Seed two\", \"source\": \"replay\", \"surface\": \"disbursements\", \"key\": null}, {\"id\": 3, \"loan_id\": \"LN-1003\", \"product\": \"Home\", \"amount\": \"120000.00\", \"memo\": \"Seed three\", \"source\": \"replay\", \"surface\": \"disbursements\", \"key\": null}], \"rejected_writes\": 0}" + } + } + }, + { + "request": { + "method": "POST", + "url": "http://127.0.0.1:58025/api/disbursement", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Content-Length", + "value": "100" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ], + "postData": { + "mimeType": "application/json", + "text": "{\"loan_id\": \"LN-2040\", \"product\": \"Personal\", \"amount\": \"3150.00\", \"memo\": \"Kitchen repair advance\"}" + } + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"ok\": true, \"id\": 4}" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/spend-dev.jsonl b/packages/flow/benchmark/verify_draft/results/spend-dev.jsonl new file mode 100644 index 0000000000..266d826c32 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/spend-dev.jsonl @@ -0,0 +1,9 @@ +{"at": 1795244796.7490969, "label": "mockloan", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 583, "output_tokens": 1613, "cache_read_tokens": 0, "cache_write_tokens": 1944, "usd": 0.044312, "seconds": 16.32, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245057.916192, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 3275, "cache_read_tokens": 1944, "cache_write_tokens": 0, "usd": 0.068933, "seconds": 29.2, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245120.244375, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 3340, "output_tokens": 3541, "cache_read_tokens": 1944, "cache_write_tokens": 0, "usd": 0.084569, "seconds": 33.19, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245169.217639, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 5746, "output_tokens": 2399, "cache_read_tokens": 1944, "cache_write_tokens": 0, "usd": 0.071353, "seconds": 20.15, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245355.956809, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 3009, "cache_read_tokens": 0, "cache_write_tokens": 2042, "usd": 0.073434, "seconds": 27.06, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245403.5369248, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 3256, "output_tokens": 2025, "cache_read_tokens": 2042, "cache_write_tokens": 0, "usd": 0.053932, "seconds": 17.36, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245453.816083, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 5237, "output_tokens": 2468, "cache_read_tokens": 2042, "cache_write_tokens": 0, "usd": 0.070716, "seconds": 20.62, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245605.089545, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 2669, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.067199, "seconds": 24.05, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795245692.510769, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 2531, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.054095, "seconds": 22.76, "request_id": "", "stop_reason": "end_turn"} diff --git a/packages/flow/benchmark/verify_draft/results/spend.jsonl b/packages/flow/benchmark/verify_draft/results/spend.jsonl new file mode 100644 index 0000000000..61960e0960 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/spend.jsonl @@ -0,0 +1,11 @@ +{"at": 1795246327.806889, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19917, "output_tokens": 2673, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.143903, "seconds": 25.77, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795246389.4471989, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 30447, "output_tokens": 2925, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.180719, "seconds": 24.11, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795246409.924798, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 32873, "output_tokens": 2743, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.186783, "seconds": 20.47, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795246641.254219, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19914, "output_tokens": 2641, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.132907, "seconds": 25.64, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795246895.488529, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 21852, "output_tokens": 9619, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.280219, "seconds": 92.65, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795246918.697357, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 25057, "output_tokens": 3114, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.162939, "seconds": 23.2, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795247669.287714, "label": "mockloan", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 583, "output_tokens": 1575, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.044607, "seconds": 14.8, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795247675.958372, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 2382, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.061459, "seconds": 20.73, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795247848.794942, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19909, "output_tokens": 2429, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.128647, "seconds": 22.47, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795247862.9125051, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 21727, "output_tokens": 1766, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.122659, "seconds": 13.98, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795248054.955477, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 23470, "output_tokens": 4549, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.185291, "seconds": 45.48, "request_id": "", "stop_reason": "end_turn"} diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..55047a331f --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.admission.json @@ -0,0 +1,297 @@ +{ + "admitted": false, + "check_sha256": "sha256:be0c65193ee465669ec12b88935ea88a0b1157ec53cc8386eb2a177fb3b2c81d", + "problems": [], + "masked": [], + "seconds": 37.36, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.26 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.89 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.76 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.33 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.84 + }, + { + "group": "fault", + "name": "wrong_value:description", + "detail": "recipes.description holds another value", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.0 + }, + { + "group": "fault", + "name": "wrong_value:description_normalized", + "detail": "recipes.description_normalized holds another value", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.93 + }, + { + "group": "fault", + "name": "wrong_value:recipe_yield", + "detail": "recipes.recipe_yield holds another value", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.45 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.1 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the recipes record", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.83 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.86 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the recipes write undone after the check", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.75 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 1.73 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.17 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.03 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 3.0 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "NO_BASELINE", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the database could not be read for the frame (SnapshotError: can't read exactly: api_extras (the read account has no SELECT on its sequence api_extras_id_seq); group_meal_plans (the read account has no SELECT on its sequence group_meal_plans_id_seq); ingredient_food_extras (the read account has no SELECT on its sequence ingredient_food_extras_id_seq); invite_tokens (the read account has no SELECT on its sequence invite_tokens_id_seq); long_live_tokens (the read account has no SELECT on its sequence long_live_tokens_id_seq); notes (the read account has no SELECT on its sequence notes_id_seq); password_reset_tokens (the read account has no SELECT on its sequence password_reset_tokens_id_seq); recipe_assets (the read account has no SELECT on its sequence recipe_assets_id_seq); recipe_ingredient_ref_link (the read account has no SELECT on its sequence recipe_ingredient_ref_link_id_seq); server_tasks (the read account has no SELECT on its sequence server_tasks_id_seq); shopping_list_extras (the read account has no SELECT on its sequence shopping_list_extras_id_seq); shopping_list_item_extras (the read account has no SELECT on its sequence shopping_list_item_extras_id_seq). Skip a table only by allow-listing it with mode skip and a reason)" + ], + "moved": [], + "seconds": 2.26 + } + ], + "attribution": [ + { + "table": "recipes", + "column": "update_at", + "cause": "never moved", + "excluded": true, + "problem": "excluded, but it never moved in any probe write: nothing to excuse" + }, + { + "table": "recipes", + "column": "date_updated", + "cause": "never moved", + "excluded": true, + "problem": "excluded, but it never moved in any probe write: nothing to excuse" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..b85312fe5f --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.yaml @@ -0,0 +1,33 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield", CAST(r."group_id" AS TEXT) AS "group_id" FROM "recipes" r +effects: +- kind: record_written + probe: surface=record|recipe named by slug has the new description and yield + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: Mealie deletes and re-inserts every instruction row of the saved recipe with fresh ids on each save regardless of values written} + - {table: recipe_nutrition, mode: skip, reason: Mealie deletes and re-inserts the nutrition row of the saved recipe with a fresh id on each save} + - {table: recipe_settings, mode: skip, reason: Mealie deletes and re-inserts the settings row of the saved recipe with a fresh id on each save} + - {table: recipes_ingredients, mode: skip, reason: Mealie deletes and re-inserts every ingredient row of the saved recipe with fresh ids on each save} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-2.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-2.yaml new file mode 100644 index 0000000000..3d13e52bc3 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-2.yaml @@ -0,0 +1,45 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield", CAST(r."group_id" AS TEXT) AS "group_id" FROM "recipes" r +effects: +- kind: record_written + probe: surface=record|recipe named by slug has the new description and yield + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: Mealie deletes and re-inserts every instruction row of the saved recipe with fresh ids on each save regardless of values written} + - {table: recipe_nutrition, mode: skip, reason: Mealie deletes and re-inserts the nutrition row of the saved recipe with a fresh id on each save} + - {table: recipe_settings, mode: skip, reason: Mealie deletes and re-inserts the settings row of the saved recipe with a fresh id on each save} + - {table: recipes_ingredients, mode: skip, reason: Mealie deletes and re-inserts every ingredient row of the saved recipe with fresh ids on each save} + - {table: api_extras, mode: skip, reason: read account has no SELECT on its id sequence so it cannot be snapshotted; the recipe description/yield patch does not write it} + - {table: group_meal_plans, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: ingredient_food_extras, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: invite_tokens, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: long_live_tokens, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: notes, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: password_reset_tokens, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: recipe_assets, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: recipe_ingredient_ref_link, mode: skip, reason: read account has no SELECT on its id sequence; child link rows rewritten with instructions on save, not a value the task writes} + - {table: server_tasks, mode: skip, reason: read account has no SELECT on its id sequence; background task log} + - {table: shopping_list_extras, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + - {table: shopping_list_item_extras, mode: skip, reason: read account has no SELECT on its id sequence; not written by a recipe description/yield patch} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-3.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-3.yaml new file mode 100644 index 0000000000..229080be1a --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-3.yaml @@ -0,0 +1,45 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield", CAST(r."group_id" AS TEXT) AS "group_id" FROM "recipes" r +effects: +- kind: record_written + probe: surface=record|recipe named by slug has the new description and yield + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: "Mealie deletes and re-inserts every instruction row of the saved recipe with fresh ids on each save regardless of values written"} + - {table: recipe_nutrition, mode: skip, reason: "Mealie deletes and re-inserts the nutrition row of the saved recipe with a fresh id on each save"} + - {table: recipe_settings, mode: skip, reason: "Mealie deletes and re-inserts the settings row of the saved recipe with a fresh id on each save"} + - {table: recipes_ingredients, mode: skip, reason: "Mealie deletes and re-inserts every ingredient row of the saved recipe with fresh ids on each save"} + - {table: api_extras, mode: skip, reason: "read account has no SELECT on its id sequence so it cannot be snapshotted; not written by a recipe description/yield patch"} + - {table: group_meal_plans, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: ingredient_food_extras, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: invite_tokens, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: long_live_tokens, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: notes, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: password_reset_tokens, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: recipe_assets, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: recipe_ingredient_ref_link, mode: skip, reason: "read account has no SELECT on its id sequence; child link rows rewritten with instructions on save and never hold a task value"} + - {table: server_tasks, mode: skip, reason: "read account has no SELECT on its id sequence; background task log"} + - {table: shopping_list_extras, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + - {table: shopping_list_item_extras, mode: skip, reason: "read account has no SELECT on its id sequence; not written by a recipe description/yield patch"} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/run.log b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/run.log new file mode 100644 index 0000000000..9b2a5c4624 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/run.log @@ -0,0 +1,7 @@ +[mealie] store: 62 tables; trace: 1 write request(s) +[mealie] demonstration: changed recipes, columns ['description', 'description_normalized', 'recipe_yield'] +[mealie] round 1: rejected (0/17 cases, 37s) +[mealie] round 2: draft refused before testing: the contract does not load: invalid draft: 1 validation error for VerifyConfig +frame.database.allow_tables.12.not a value the task writes + Extra inputs are not permitted [type=extra_forbidden, input_value=None, input_type=NoneType] + For further information visit https://errors.pydantic.dev/2.14/v/extra_forbidden diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/sandbox.yaml new file mode 100644 index 0000000000..98a2ef5f46 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/sandbox.yaml @@ -0,0 +1,40 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:9664 +actors: + agent: + id: d9224e48-25a7-40e2-87db-9537f3b7d832 + login: + method: POST + path: /api/auth/token + token_field: access_token + form: + username: changeme@example.com + password: ${VD_MEALIE_ADMIN_PW} + other: + id: c28151a1-557e-43ff-ae74-54c1a68ec718 + login: + method: POST + path: /api/auth/token + token_field: access_token + form: + username: cook2 + password: ${VD_MEALIE_COOK_PW} +store: + dialect: postgresql + read: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: mealie + user: vd_reader + sql_password_env: VD_MEALIE_READER_PW + admin: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: mealie + user: mealie + sql_password_env: VD_MEALIE_PG_PW diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/task.yaml new file mode 100644 index 0000000000..485fad004e --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/task.yaml @@ -0,0 +1,6 @@ +instruction: 'Update the recipe lentil-soup: set its description to ''Red lentils, + cumin and lemon. Ready in 40 minutes.'' and its yield to ''6 bowls''.' +params: + slug: lentil-soup + description: Red lentils, cumin and lemon. Ready in 40 minutes. + recipe_yield: 6 bowls diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/trace.har b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/trace.har new file mode 100644 index 0000000000..52ab0bfd61 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run1/setup/trace.har @@ -0,0 +1,92 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:9664/api/recipes/lentil-soup", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"id\":\"5b25a58d-ba98-403f-8bd3-911b1edc99ff\",\"userId\":\"d9224e48-25a7-40e2-87db-9537f3b7d832\",\"householdId\":\"f313b519-edae-4a9c-9fd9-6b530b1fb700\",\"groupId\":\"8d9e9d63-db2c-4892-aff1-8468bf282ba0\",\"name\":\"Lentil soup\",\"slug\":\"lentil-soup\",\"image\":null,\"recipeServings\":0.0,\"recipeYieldQuantity\":0.0,\"recipeYield\":\"4 servings\",\"totalTime\":null,\"prepTime\":null,\"cookTime\":null,\"performTime\":null,\"description\":\"Seed recipe one\",\"recipeCategory\":[],\"tags\":[],\"tools\":[],\"rating\":null,\"orgURL\":null,\"dateAdded\":\"2026-11-21\",\"dateUpdated\":\"2026-11-21T07:31:23.540064Z\",\"createdAt\":\"2026-11-21T07:31:22.449454Z\",\"updatedAt\":\"2026-11-21T07:31:23.544331Z\",\"lastMade\":null,\"recipeIngredient\":[{\"quantity\":1.0,\"unit\":null,\"food\":null,\"note\":\"1 Cup Flour\",\"isFood\":false,\"disableAmount\":true,\"display\":\"1 Cup Flour\",\"title\":null,\"originalText\":null,\"referenceId\":\"2f166769-9648-4422-bb72-b28ae2167bc3\"}],\"recipeInstructions\":[{\"id\":\"8991f461-c97d-4eb2-a185-48bab3f60a4e\",\"title\":\"\",\"summary\":\"\",\"text\":\"Recipe steps as well as other fields in the recipe page support markdown syntax.\\n\\n**Add a link**\\n\\n[My Link](https://demo.mealie.io)\\n\",\"ingredientReferences\":[]}],\"nutrition\":{\"calories\":null,\"carbohydrateContent\":null,\"cholesterolContent\":null,\"fatContent\":null,\"fiberContent\":null,\"proteinContent\":null,\"saturatedFatContent\":null,\"sodiumContent\":null,\"sugarContent\":null,\"transFatContent\":null,\"unsaturatedFatContent\":null},\"settings\":{\"public\":false,\"showNutrition\":false,\"showAssets\":false,\"landscapeView\":false,\"disableComments\":false,\"disableAmount\":true,\"locked\":false},\"assets\":[],\"notes\":[],\"extras\":{},\"comments\":[]}" + } + } + }, + { + "request": { + "method": "PATCH", + "url": "http://127.0.0.1:9664/api/recipes/lentil-soup", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + }, + { + "name": "Content-Length", + "value": "95" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ], + "postData": { + "mimeType": "application/json", + "text": "{\"description\": \"Red lentils, cumin and lemon. Ready in 40 minutes.\", \"recipeYield\": \"6 bowls\"}" + } + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"id\":\"5b25a58d-ba98-403f-8bd3-911b1edc99ff\",\"userId\":\"d9224e48-25a7-40e2-87db-9537f3b7d832\",\"householdId\":\"f313b519-edae-4a9c-9fd9-6b530b1fb700\",\"groupId\":\"8d9e9d63-db2c-4892-aff1-8468bf282ba0\",\"name\":\"Lentil soup\",\"slug\":\"lentil-soup\",\"image\":null,\"recipeServings\":0.0,\"recipeYieldQuantity\":0.0,\"recipeYield\":\"6 bowls\",\"totalTime\":null,\"prepTime\":null,\"cookTime\":null,\"performTime\":null,\"description\":\"Red lentils, cumin and lemon. Ready in 40 minutes.\",\"recipeCategory\":[],\"tags\":[],\"tools\":[],\"rating\":null,\"orgURL\":null,\"dateAdded\":\"2026-11-21\",\"dateUpdated\":\"2026-11-21T07:31:26.895586Z\",\"createdAt\":\"2026-11-21T07:31:22.449454Z\",\"updatedAt\":\"2026-11-21T07:31:26.901601Z\",\"lastMade\":null,\"recipeIngredient\":[{\"quantity\":1.0,\"unit\":null,\"food\":null,\"note\":\"1 Cup Flour\",\"isFood\":false,\"disableAmount\":true,\"display\":\"1 Cup Flour\",\"title\":null,\"originalText\":null,\"referenceId\":\"2f166769-9648-4422-bb72-b28ae2167bc3\"}],\"recipeInstructions\":[{\"id\":\"51e046b8-35b5-4983-b318-a3693aa3fc80\",\"title\":\"\",\"summary\":\"\",\"text\":\"Recipe steps as well as other fields in the recipe page support markdown syntax.\\n\\n**Add a link**\\n\\n[My Link](https://demo.mealie.io)\\n\",\"ingredientReferences\":[]}],\"nutrition\":{\"calories\":null,\"carbohydrateContent\":null,\"cholesterolContent\":null,\"fatContent\":null,\"fiberContent\":null,\"proteinContent\":null,\"saturatedFatContent\":null,\"sodiumContent\":null,\"sugarContent\":null,\"transFatContent\":null,\"unsaturatedFatContent\":null},\"settings\":{\"public\":false,\"showNutrition\":false,\"showAssets\":false,\"landscapeView\":false,\"disableComments\":false,\"disableAmount\":true,\"locked\":false},\"assets\":[],\"notes\":[],\"extras\":{},\"comments\":[]}" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json new file mode 100644 index 0000000000..754a0bede5 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json @@ -0,0 +1,46 @@ +{ + "admitted": false, + "rounds": 3, + "person_decisions": 0, + "seconds": 551.8, + "model_usd": 0.5761, + "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-2: the write with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-3: the write with payload 3. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-4: the write with payload 4. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-5: the write with payload 5. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:agent:p1: the write by agent with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:agent:p2: the write by agent with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:other:p1: the write by other with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:other:p2: the write by other with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)", + "contract": null, + "questions": [], + "rounds_detail": [ + { + "admitted": false, + "cases": 17, + "passed": 15, + "failed": [ + "wrong_value:description_normalized", + "lost_update" + ], + "problems": [], + "attribution_problems": [ + "recipe_instructions.id", + "recipe_nutrition.id", + "recipe_settings.id", + "recipes_ingredients.id" + ] + }, + { + "admitted": false, + "cases": 17, + "passed": 8, + "failed": [ + "clean-1", + "clean-2", + "clean-3", + "clean-4", + "clean-5", + "attribution:agent:p1", + "attribution:agent:p2", + "attribution:other:p1", + "attribution:other:p2" + ], + "problems": [], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..b908b81ed2 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.admission.json @@ -0,0 +1,777 @@ +{ + "admitted": false, + "check_sha256": "sha256:e2f913ef9de492bd3d6b80f44388af6a88893d53af83debc6657230213ba3f76", + "problems": [], + "masked": [], + "seconds": 161.52, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.18 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.07 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.9 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 12.4 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.9 + }, + { + "group": "fault", + "name": "wrong_value:description", + "detail": "recipes.description holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 12.72 + }, + { + "group": "fault", + "name": "wrong_value:description_normalized", + "detail": "recipes.description_normalized holds another value", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.44 + }, + { + "group": "fault", + "name": "wrong_value:recipe_yield", + "detail": "recipes.recipe_yield holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 13.18 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another recipes row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 13.53 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the recipes record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "added", + "columns": [ + "created_at", + "date_added", + "description", + "description_normalized", + "group_id", + "id", + "is_ocr_recipe", + "name", + "name_normalized", + "recipe_servings", + "recipe_yield", + "recipe_yield_quantity", + "slug", + "user_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 8.0 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another recipes row's created_at edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "created_at" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 7.83 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the recipes write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 10.94 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.32 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.22 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.57 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.58 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.95 + } + ], + "attribution": [ + { + "table": "recipe_instructions", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "id", + "cause": "payload", + "excluded": true, + "problem": "excluded, but it moves with the values written: the exclusion hides the write" + }, + { + "table": "recipe_instructions", + "column": "position", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "summary", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "text", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "title", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "type", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "calories", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "carbohydrate_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "cholesterol_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "fiber_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "id", + "cause": "payload", + "excluded": true, + "problem": "excluded, but it moves with the values written: the exclusion hides the write" + }, + { + "table": "recipe_nutrition", + "column": "protein_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "saturated_fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "sodium_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "sugar_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "trans_fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "unsaturated_fat_content", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "disable_amount", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "disable_comments", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "id", + "cause": "payload", + "excluded": true, + "problem": "excluded, but it moves with the values written: the exclusion hides the write" + }, + { + "table": "recipe_settings", + "column": "landscape_view", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "locked", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "public", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "show_assets", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "show_nutrition", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes", + "column": "date_updated", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes", + "column": "description", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "description_normalized", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "recipe_yield", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "-", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "created_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "food_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "id", + "cause": "payload", + "excluded": true, + "problem": "excluded, but it moves with the values written: the exclusion hides the write" + }, + { + "table": "recipes_ingredients", + "column": "note", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "note_normalized", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "original_text", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "original_text_normalized", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "position", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "quantity", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "recipe_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "reference_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "title", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "unit_id", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..7affdea791 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.yaml @@ -0,0 +1,33 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield" FROM "recipes" r +effects: +- kind: record_written + probe: surface=record|recipe named by slug carries the new description and yield + match: + slug: {param: slug} + description: {param: description} + recipe_yield: {param: recipe_yield} + expected_count: 1 +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, recipe_yield] + database: + dialect: postgresql + allow_tables: + - {table: recipe_instructions, mode: skip, reason: Mealie's recipe save deletes and re-inserts every instruction row of the recipe with new ids on each PATCH} + - {table: recipes_ingredients, mode: skip, reason: Mealie's recipe save deletes and re-inserts every ingredient row of the recipe with new ids on each PATCH} + - {table: recipe_nutrition, mode: skip, reason: Mealie's recipe save deletes and re-inserts the nutrition row with a new id on each PATCH} + - {table: recipe_settings, mode: skip, reason: Mealie's recipe save deletes and re-inserts the settings row with a new id on each PATCH} + ignore_columns: + recipes: [date_updated, update_at] + views: + recipes: record + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-2.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-2.yaml new file mode 100644 index 0000000000..d35cb5eedd --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-2.yaml @@ -0,0 +1,81 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(CASE WHEN r."description_normalized" = LOWER(r."description") THEN 'yes' ELSE 'no' END AS TEXT) AS "normalized_ok", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield" FROM "recipes" r + nutrition: + kind: sql + sql_query: SELECT CAST(n."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(n."recipe_id" AS TEXT) AS "recipe_id" FROM "recipe_nutrition" n JOIN "recipes" r ON r."id" = n."recipe_id" + settings: + kind: sql + sql_query: SELECT CAST(s."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(s."recipe_id" AS TEXT) AS "recipe_id" FROM "recipe_settings" s JOIN "recipes" r ON r."id" = s."recipe_id" + ingredients: + kind: sql + sql_query: SELECT CAST(i."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(i."recipe_id" AS TEXT) AS "recipe_id" FROM "recipes_ingredients" i JOIN "recipes" r ON r."id" = i."recipe_id" + instructions: + kind: sql + sql_query: SELECT CAST(x."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(x."recipe_id" AS TEXT) AS "recipe_id" FROM "recipe_instructions" x JOIN "recipes" r ON r."id" = x."recipe_id" +effects: +- kind: record_written + probe: surface=record|recipe named by slug carries the new description, its normalized form and the new yield + match: + slug: {param: slug} + description: {param: description} + normalized_ok: {literal: "yes"} + recipe_yield: {param: recipe_yield} + expected_count: 1 +- kind: record_written + probe: surface=nutrition|the save re-creates the recipe's nutrition row once + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +- kind: record_written + probe: surface=settings|the save re-creates the recipe's settings row once + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +- kind: record_written + probe: surface=ingredients|the save re-creates the recipe's ingredient rows + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +- kind: record_written + probe: surface=instructions|the save re-creates the recipe's instruction rows + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, normalized_ok, recipe_yield] + database: + dialect: postgresql + ignore_columns: + recipes: [date_updated, update_at] + judged_by: + recipes: record + recipe_nutrition: nutrition + recipe_settings: settings + recipes_ingredients: ingredients + recipe_instructions: instructions + new_row_fields: + recipe_nutrition: [id, recipe_id, calories, carbohydrate_content, cholesterol_content, fat_content, fiber_content, protein_content, saturated_fat_content, sodium_content, sugar_content, trans_fat_content, unsaturated_fat_content, created_at, update_at] + recipe_settings: [id, recipe_id, disable_amount, disable_comments, landscape_view, locked, public, show_assets, show_nutrition, created_at, update_at] + recipes_ingredients: [id, recipe_id, food_id, unit_id, note, note_normalized, original_text, original_text_normalized, position, quantity, reference_id, title, created_at, update_at] + recipe_instructions: [id, recipe_id, position, summary, text, title, type, created_at, update_at] + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + versions: + read: {kind: sql, sql_query: "SELECT CAST(r.\"id\" AS TEXT) AS \"id\", LPAD(CAST(n.\"id\" AS TEXT), 12, '0') AS \"ver\" FROM \"recipe_nutrition\" n JOIN \"recipes\" r ON r.\"id\" = n.\"recipe_id\""} + record_field: id + target_field: id + target_surface: record + version_field: ver + self: [{param: actor_id}] diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.admission.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.admission.json new file mode 100644 index 0000000000..571880f43b --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.admission.json @@ -0,0 +1,1815 @@ +{ + "admitted": false, + "check_sha256": "sha256:415b037e8e7e1e82767e528fb1fede8446f57bfe31b86bcdfdfb383b68e5fb8b", + "problems": [], + "masked": [], + "seconds": 242.79, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 10.18 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.08 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.3 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 12.83 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 10.84 + }, + { + "group": "fault", + "name": "wrong_value:description", + "detail": "recipes.description holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "10 record(s) outside the declared write moved (changed, removed); 10 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "record", + "change": "changed" + }, + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 18.17 + }, + { + "group": "fault", + "name": "wrong_value:description_normalized", + "detail": "recipes.description_normalized holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "10 record(s) outside the declared write moved (changed, removed); 10 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "record", + "change": "changed" + }, + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 17.77 + }, + { + "group": "fault", + "name": "wrong_value:recipe_yield", + "detail": "recipes.recipe_yield holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "10 record(s) outside the declared write moved (changed, removed); 10 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "record", + "change": "changed" + }, + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 17.17 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another recipes row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "10 record(s) outside the declared write moved (changed, removed); 10 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "record", + "change": "changed" + }, + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "description", + "description_normalized", + "recipe_yield" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 17.98 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the recipes record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "10 record(s) outside the declared write moved (added, removed); 10 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "record", + "change": "added" + }, + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes", + "change": "added", + "columns": [ + "created_at", + "date_added", + "description", + "description_normalized", + "group_id", + "id", + "is_ocr_recipe", + "name", + "name_normalized", + "recipe_servings", + "recipe_yield", + "recipe_yield_quantity", + "slug", + "user_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 12.84 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another recipes row's created_at edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "9 record(s) outside the declared write moved (changed, removed); 9 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes", + "change": "changed", + "columns": [ + "created_at" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 14.91 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the recipes write undone after the check", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 15.89 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 16.43 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 13.16 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 14.52 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 13.0 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "REFUTED", + "recheck": "", + "passed": false, + "applicable": true, + "note": "", + "reasons": [ + "the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted", + "8 record(s) outside the declared write moved (removed); 8 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "nutrition", + "change": "removed" + }, + { + "row": false, + "table": "settings", + "change": "removed" + }, + { + "row": false, + "table": "ingredients", + "change": "removed" + }, + { + "row": false, + "table": "instructions", + "change": "removed" + }, + { + "row": true, + "table": "recipe_instructions", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_nutrition", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipe_settings", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "recipes_ingredients", + "change": "removed", + "columns": [], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.98 + } + ], + "attribution": [ + { + "table": "recipe_instructions", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "-", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "created_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "id", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "position", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "recipe_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "summary", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "text", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "title", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "type", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_instructions", + "column": "update_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "-", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "calories", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "carbohydrate_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "cholesterol_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "created_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "fat_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "fiber_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "id", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "protein_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "recipe_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "saturated_fat_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "sodium_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "sugar_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "trans_fat_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "unsaturated_fat_content", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_nutrition", + "column": "update_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "-", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "created_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "disable_amount", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "disable_comments", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "id", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "landscape_view", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "locked", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "public", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "recipe_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "show_assets", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "show_nutrition", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipe_settings", + "column": "update_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "date_updated", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes", + "column": "description", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "description_normalized", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "recipe_yield", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes", + "column": "update_at", + "cause": "clock", + "excluded": true, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "-", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "created_at", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "food_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "id", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "note", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "note_normalized", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "original_text", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "original_text_normalized", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "position", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "quantity", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "recipe_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "reference_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "title", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "unit_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "recipes_ingredients", + "column": "update_at", + "cause": "clock", + "excluded": false, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.yaml new file mode 100644 index 0000000000..f7191f2559 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.yaml @@ -0,0 +1,80 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(r."name" AS TEXT) AS "name", CAST(r."description" AS TEXT) AS "description", CAST(r."description_normalized" AS TEXT) AS "description_normalized", CAST(CASE WHEN r."description_normalized" = LOWER(r."description") THEN 'yes' ELSE 'no' END AS TEXT) AS "normalized_ok", CAST(r."recipe_yield" AS TEXT) AS "recipe_yield" FROM "recipes" r + nutrition: + kind: sql + sql_query: SELECT CAST(n."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(n."recipe_id" AS TEXT) AS "recipe_id" FROM "recipe_nutrition" n JOIN "recipes" r ON r."id" = n."recipe_id" + settings: + kind: sql + sql_query: SELECT CAST(s."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(s."recipe_id" AS TEXT) AS "recipe_id" FROM "recipe_settings" s JOIN "recipes" r ON r."id" = s."recipe_id" + ingredients: + kind: sql + sql_query: SELECT CAST(i."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(i."recipe_id" AS TEXT) AS "recipe_id" FROM "recipes_ingredients" i JOIN "recipes" r ON r."id" = i."recipe_id" + instructions: + kind: sql + sql_query: SELECT CAST(x."id" AS TEXT) AS "id", CAST(r."slug" AS TEXT) AS "slug", CAST(x."recipe_id" AS TEXT) AS "recipe_id" FROM "recipe_instructions" x JOIN "recipes" r ON r."id" = x."recipe_id" +effects: +- kind: record_written + probe: surface=record|recipe named by slug carries the new description, its normalized form and the new yield + match: + slug: {param: slug} + description: {param: description} + normalized_ok: {literal: "yes"} + recipe_yield: {param: recipe_yield} + expected_count: 1 +- kind: record_written + probe: surface=nutrition|the save re-creates the recipe's nutrition row once + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +- kind: record_written + probe: surface=settings|the save re-creates the recipe's settings row once + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +- kind: record_written + probe: surface=ingredients|the save re-creates the recipe's ingredient rows + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +- kind: record_written + probe: surface=instructions|the save re-creates the recipe's instruction rows + match: + slug: {param: slug} + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: [description, description_normalized, normalized_ok, recipe_yield] + database: + dialect: postgresql + ignore_columns: + recipes: [date_updated, update_at] + judged_by: + recipes: record + recipe_nutrition: nutrition + recipe_settings: settings + recipes_ingredients: ingredients + recipe_instructions: instructions + new_row_fields: + recipe_nutrition: [id, recipe_id, calories, carbohydrate_content, cholesterol_content, fat_content, fiber_content, protein_content, saturated_fat_content, sodium_content, sugar_content, trans_fat_content, unsaturated_fat_content, created_at, update_at] + recipe_settings: [id, recipe_id, disable_amount, disable_comments, landscape_view, locked, public, show_assets, show_nutrition, created_at, update_at] + recipes_ingredients: [id, recipe_id, food_id, unit_id, note, note_normalized, original_text, original_text_normalized, position, quantity, reference_id, title, created_at, update_at] + recipe_instructions: [id, recipe_id, position, summary, text, title, type, created_at, update_at] + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + versions: + read: {kind: sql, sql_query: "SELECT CAST(r.\"id\" AS TEXT) AS \"id\", LPAD(CAST(n.\"id\" AS TEXT), 12, '0') AS \"ver\" FROM \"recipe_nutrition\" n JOIN \"recipes\" r ON r.\"id\" = n.\"recipe_id\""} + record_field: id + target_field: id + target_surface: record + version_field: ver diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json new file mode 100644 index 0000000000..b8f9bbfb94 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json @@ -0,0 +1,103 @@ +{ + "app": "mealie", + "untuned": true, + "describe": "openapi", + "operator_setup_seconds": 3.3, + "operator_inputs": [ + "app base URL", + "two users' sign-in (user, password env)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 9.2, + "person_decisions": 0, + "questions": [], + "drafts": 2, + "drafts_admitted": 0, + "drafts_rejected": 2, + "admitted": false, + "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-2: the write with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-3: the write with payload 3. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-4: the write with payload 4. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-5: the write with payload 5. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 recor", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.5761, + "model_calls": [ + { + "at": 1795246641.254219, + "label": "mealie", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 19914, + "output_tokens": 2641, + "cache_read_tokens": 2155, + "cache_write_tokens": 0, + "usd": 0.132907, + "seconds": 25.64, + "request_id": "", + "stop_reason": "end_turn" + }, + { + "at": 1795246895.488529, + "label": "mealie", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 21852, + "output_tokens": 9619, + "cache_read_tokens": 2155, + "cache_write_tokens": 0, + "usd": 0.280219, + "seconds": 92.65, + "request_id": "", + "stop_reason": "end_turn" + }, + { + "at": 1795246918.697357, + "label": "mealie", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 25057, + "output_tokens": 3114, + "cache_read_tokens": 2155, + "cache_write_tokens": 0, + "usd": 0.162939, + "seconds": 23.2, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": false, + "faults_applicable": 8, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 4, + "attribution_problems": [ + "recipe_instructions.id: excluded, but it moves with the values written: the exclusion hides the write", + "recipe_nutrition.id: excluded, but it moves with the values written: the exclusion hides the write", + "recipe_settings.id: excluded, but it moves with the values written: the exclusion hides the write", + "recipes_ingredients.id: excluded, but it moves with the values written: the exclusion hides the write" + ], + "not_applicable": {}, + "seconds": 161.52 + }, + { + "admitted": false, + "faults_applicable": 8, + "faults_caught": 8, + "clean": 5, + "false_stops": [ + "clean-1", + "clean-2", + "clean-3", + "clean-4", + "clean-5" + ], + "probe_writes_confirmed": 0, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 242.79 + } + ], + "notes": [] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log new file mode 100644 index 0000000000..7e26ba9ad7 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log @@ -0,0 +1,67 @@ +[mealie] store: 62 tables; trace: 1 write request(s) +[mealie] demonstration: changed recipes, columns ['description', 'description_normalized', 'recipe_yield'] +[mealie] round 1: rejected (15/17 cases, 162s) +[mealie] round 2: draft refused before testing: the contract does not load: invalid draft: 1 validation error for VerifyConfig +frame.versions + Value error, frame.versions: author_field and self go together (whose versions are the agent's own) [type=value_error, input_value={'read': {'kind': 'sql', ...[{'param': 'actor_id'}]}, input_type=dict] + For further information visit https://errors.pydantic.dev/2.14/v/value_error +[mealie] round 3: rejected (8/17 cases, 243s) +{ + "app": "mealie", + "untuned": true, + "describe": "openapi", + "operator_setup_seconds": 3.3, + "operator_inputs": [ + "app base URL", + "two users' sign-in (user, password env)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 9.2, + "person_decisions": 0, + "questions": [], + "drafts": 2, + "drafts_admitted": 0, + "drafts_rejected": 2, + "admitted": false, + "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-2: the write with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-3: the write with payload 3. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-4: the write with payload 4. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-5: the write with payload 5. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 recor", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.5761, + "rounds": [ + { + "admitted": false, + "faults_applicable": 8, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 4, + "attribution_problems": [ + "recipe_instructions.id: excluded, but it moves with the values written: the exclusion hides the write", + "recipe_nutrition.id: excluded, but it moves with the values written: the exclusion hides the write", + "recipe_settings.id: excluded, but it moves with the values written: the exclusion hides the write", + "recipes_ingredients.id: excluded, but it moves with the values written: the exclusion hides the write" + ], + "not_applicable": {}, + "seconds": 161.52 + }, + { + "admitted": false, + "faults_applicable": 8, + "faults_caught": 8, + "clean": 5, + "false_stops": [ + "clean-1", + "clean-2", + "clean-3", + "clean-4", + "clean-5" + ], + "probe_writes_confirmed": 0, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 242.79 + } + ], + "notes": [] +} diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/sandbox.yaml new file mode 100644 index 0000000000..9f3af322ea --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/sandbox.yaml @@ -0,0 +1,40 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:9664 +actors: + agent: + id: 726456f4-60c7-4786-a001-1cf388299150 + login: + method: POST + path: /api/auth/token + token_field: access_token + form: + username: changeme@example.com + password: ${VD_MEALIE_ADMIN_PW} + other: + id: 776f4fbc-280f-4968-b127-3d7f192ad619 + login: + method: POST + path: /api/auth/token + token_field: access_token + form: + username: cook2 + password: ${VD_MEALIE_COOK_PW} +store: + dialect: postgresql + read: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: mealie + user: vd_reader + sql_password_env: VD_MEALIE_READER_PW + admin: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: mealie + user: mealie + sql_password_env: VD_MEALIE_PG_PW diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/task.yaml new file mode 100644 index 0000000000..485fad004e --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/task.yaml @@ -0,0 +1,6 @@ +instruction: 'Update the recipe lentil-soup: set its description to ''Red lentils, + cumin and lemon. Ready in 40 minutes.'' and its yield to ''6 bowls''.' +params: + slug: lentil-soup + description: Red lentils, cumin and lemon. Ready in 40 minutes. + recipe_yield: 6 bowls diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/trace.har b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/trace.har new file mode 100644 index 0000000000..671209ebbd --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/setup/trace.har @@ -0,0 +1,92 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:9664/api/recipes/lentil-soup", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"id\":\"30e3dff6-290c-4f01-87dc-ec4ae5b4407d\",\"userId\":\"726456f4-60c7-4786-a001-1cf388299150\",\"householdId\":\"4c74852c-4654-494e-b2ac-8efc54604452\",\"groupId\":\"92da6dad-a729-48aa-b30c-4836f5de0343\",\"name\":\"Lentil soup\",\"slug\":\"lentil-soup\",\"image\":null,\"recipeServings\":0.0,\"recipeYieldQuantity\":0.0,\"recipeYield\":\"4 servings\",\"totalTime\":null,\"prepTime\":null,\"cookTime\":null,\"performTime\":null,\"description\":\"Seed recipe one\",\"recipeCategory\":[],\"tags\":[],\"tools\":[],\"rating\":null,\"orgURL\":null,\"dateAdded\":\"2026-11-21\",\"dateUpdated\":\"2026-11-21T07:36:45.842140Z\",\"createdAt\":\"2026-11-21T07:36:45.150160Z\",\"updatedAt\":\"2026-11-21T07:36:45.844926Z\",\"lastMade\":null,\"recipeIngredient\":[{\"quantity\":1.0,\"unit\":null,\"food\":null,\"note\":\"1 Cup Flour\",\"isFood\":false,\"disableAmount\":true,\"display\":\"1 Cup Flour\",\"title\":null,\"originalText\":null,\"referenceId\":\"b5b50097-7ac7-45e3-a5ce-0a7cba3555df\"}],\"recipeInstructions\":[{\"id\":\"42d4adfc-db16-4a9c-9352-c4e64724bfee\",\"title\":\"\",\"summary\":\"\",\"text\":\"Recipe steps as well as other fields in the recipe page support markdown syntax.\\n\\n**Add a link**\\n\\n[My Link](https://demo.mealie.io)\\n\",\"ingredientReferences\":[]}],\"nutrition\":{\"calories\":null,\"carbohydrateContent\":null,\"cholesterolContent\":null,\"fatContent\":null,\"fiberContent\":null,\"proteinContent\":null,\"saturatedFatContent\":null,\"sodiumContent\":null,\"sugarContent\":null,\"transFatContent\":null,\"unsaturatedFatContent\":null},\"settings\":{\"public\":false,\"showNutrition\":false,\"showAssets\":false,\"landscapeView\":false,\"disableComments\":false,\"disableAmount\":true,\"locked\":false},\"assets\":[],\"notes\":[],\"extras\":{},\"comments\":[]}" + } + } + }, + { + "request": { + "method": "PATCH", + "url": "http://127.0.0.1:9664/api/recipes/lentil-soup", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + }, + { + "name": "Content-Length", + "value": "95" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ], + "postData": { + "mimeType": "application/json", + "text": "{\"description\": \"Red lentils, cumin and lemon. Ready in 40 minutes.\", \"recipeYield\": \"6 bowls\"}" + } + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"id\":\"30e3dff6-290c-4f01-87dc-ec4ae5b4407d\",\"userId\":\"726456f4-60c7-4786-a001-1cf388299150\",\"householdId\":\"4c74852c-4654-494e-b2ac-8efc54604452\",\"groupId\":\"92da6dad-a729-48aa-b30c-4836f5de0343\",\"name\":\"Lentil soup\",\"slug\":\"lentil-soup\",\"image\":null,\"recipeServings\":0.0,\"recipeYieldQuantity\":0.0,\"recipeYield\":\"6 bowls\",\"totalTime\":null,\"prepTime\":null,\"cookTime\":null,\"performTime\":null,\"description\":\"Red lentils, cumin and lemon. Ready in 40 minutes.\",\"recipeCategory\":[],\"tags\":[],\"tools\":[],\"rating\":null,\"orgURL\":null,\"dateAdded\":\"2026-11-21\",\"dateUpdated\":\"2026-11-21T07:36:46.697147Z\",\"createdAt\":\"2026-11-21T07:36:45.150160Z\",\"updatedAt\":\"2026-11-21T07:36:46.698842Z\",\"lastMade\":null,\"recipeIngredient\":[{\"quantity\":1.0,\"unit\":null,\"food\":null,\"note\":\"1 Cup Flour\",\"isFood\":false,\"disableAmount\":true,\"display\":\"1 Cup Flour\",\"title\":null,\"originalText\":null,\"referenceId\":\"b5b50097-7ac7-45e3-a5ce-0a7cba3555df\"}],\"recipeInstructions\":[{\"id\":\"ff4ac1b2-f33a-4766-8dba-cb130d162832\",\"title\":\"\",\"summary\":\"\",\"text\":\"Recipe steps as well as other fields in the recipe page support markdown syntax.\\n\\n**Add a link**\\n\\n[My Link](https://demo.mealie.io)\\n\",\"ingredientReferences\":[]}],\"nutrition\":{\"calories\":null,\"carbohydrateContent\":null,\"cholesterolContent\":null,\"fatContent\":null,\"fiberContent\":null,\"proteinContent\":null,\"saturatedFatContent\":null,\"sodiumContent\":null,\"sugarContent\":null,\"transFatContent\":null,\"unsaturatedFatContent\":null},\"settings\":{\"public\":false,\"showNutrition\":false,\"showAssets\":false,\"landscapeView\":false,\"disableComments\":false,\"disableAmount\":true,\"locked\":false},\"assets\":[],\"notes\":[],\"extras\":{},\"comments\":[]}" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench.log b/packages/flow/benchmark/verify_draft/results/workbench.log new file mode 100644 index 0000000000..342f29a47e --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench.log @@ -0,0 +1,315 @@ +[workbench] store: 4 tables; trace: 1 write request(s) +[workbench] demonstration: changed patients, columns ['email', 'phone'] +[workbench] round 1: ADMITTED (15/15 cases, 51s) +{ + "app": "workbench", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 1.3, + "operator_inputs": [ + "app base URL", + "agent sign-in (user, password)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 1.21, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.0615, + "rounds": [ + { + "admitted": true, + "faults_applicable": 6, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 3, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the sandbox has no second user" + }, + "seconds": 51.35 + } + ], + "notes": [ + "the workbench signs in one user only: no second actor, so no lost-update case and no actor axis" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.46 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.05 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.42 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.55 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.1 + }, + { + "group": "fault", + "name": "wrong_value:email", + "detail": "patients.email holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.55 + }, + { + "group": "fault", + "name": "wrong_value:phone", + "detail": "patients.phone holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.36 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another patients row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.66 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the patients record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "added", + "columns": [ + "dob", + "email", + "first_name", + "id", + "last_name", + "mrn", + "phone", + "status", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.27 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another patients row's mrn edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "mrn" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.37 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the patients write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.62 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "note": "the sandbox has no second user", + "reasons": [], + "moved": [], + "seconds": 0.0 + } + ], + "faults_applicable": 6, + "faults_caught": 6, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml new file mode 100644 index 0000000000..d682d96aba --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml @@ -0,0 +1,104 @@ +# Drafted by a model and admitted by OpenAdapt qualification (openadapt verify draft). Runs make no model calls. +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(p."id" AS TEXT) AS "id", CAST(p."mrn" AS TEXT) AS "mrn", + CAST(p."phone" AS TEXT) AS "phone", CAST(p."email" AS TEXT) AS "email", CAST(p."version" + AS TEXT) AS "version", CAST(p."updated_by" AS TEXT) AS "updated_by" FROM "patients" + p + sql_driver: psycopg2 + sql_connect_args: &id001 + host: 127.0.0.1 + port: 9796 + dbname: wb_mockmed + user: wb_reader + audit: + kind: sql + sql_query: SELECT CAST(a."id" AS TEXT) AS "id", CAST(a."actor" AS TEXT) AS "actor", + CAST(a."table_name" AS TEXT) AS "table_name", CAST(a."event" AS TEXT) AS "event", + CAST(a."record_id" AS TEXT) AS "record_id", CAST(p."mrn" AS TEXT) AS "mrn" + FROM "audit_log" a JOIN "patients" p ON a."table_name" = 'patients' AND a."record_id" + = p."id" + sql_driver: psycopg2 + sql_connect_args: *id001 +effects: +- kind: record_written + probe: surface=record|patient with this MRN has the new phone and email + match: + mrn: + param: mrn + phone: + param: phone + email: + param: email + expected_count: 1 +- kind: record_written + probe: surface=audit|exactly one new update audit row for this patient + match: + mrn: + param: mrn + table_name: + literal: patients + event: + literal: update + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: + - phone + - email + - version + - updated_by + database: + dialect: postgresql + views: + patients: record + judged_by: + audit_log: audit + new_row_fields: + audit_log: + - id + - actor + - record_id + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + read: + sql_driver: psycopg2 + sql_connect_args: *id001 +provenance: + drafted_by: + model: claude-opus-5-5 + response_model: claude-opus-5-5 + effort: medium + prompt_version: verify-draft-prompt/1 + prompt_sha256: sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840 + inputs: + description: + kind: database + file_sha256: null + text_sha256: sha256:92cd3d4fdfe7b1bfefd0f4be2c402a7b16f7ff6abca24f498c730f38096b1026 + trace_sha256: sha256:afef2366549ad4e15d4e8c42ae1ce19399d852f76f2c540a0079a1e6b6ff637e + task_sha256: sha256:40052528dbd5404c4c5c5688be9d1511b89e13ee461df22aa2a4f0faeef8e4ff + admission: + suite: openadapt.verify-draft-admission/v1 + check_sha256: sha256:fa6321a417660282b30c3320be0570e5e986ec460257b5023fed2ff2f00c3249 + rounds: 1 + admitted_at: '2026-11-21T07:55:27Z' + recheck_window_tested_s: 2.0 + faults: + wrong_value:email: refuted + wrong_value:phone: refuted + wrong_row: refuted + duplicate: refuted + sibling_edit: refuted + late_revert: refuted + lost_update: 'not applicable: the sandbox has no second user' + clean_writes_confirmed: 5 + attribution_probe_writes: 3 + bookkeeping_confirmed_by_person: [] diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json b/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json new file mode 100644 index 0000000000..10e1af9e8f --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json @@ -0,0 +1,20 @@ +{ + "admitted": true, + "rounds": 1, + "person_decisions": 0, + "seconds": 72.6, + "model_usd": 0.0615, + "reason": "admitted", + "contract": "benchmark/verify_draft/results/workbench/draft/contract.yaml", + "questions": [], + "rounds_detail": [ + { + "admitted": true, + "cases": 15, + "passed": 15, + "failed": [], + "problems": [], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..06934816a1 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json @@ -0,0 +1,384 @@ +{ + "admitted": true, + "check_sha256": "sha256:fa6321a417660282b30c3320be0570e5e986ec460257b5023fed2ff2f00c3249", + "problems": [], + "masked": [], + "seconds": 51.35, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.12 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.9 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.97 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.98 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.08 + }, + { + "group": "fault", + "name": "wrong_value:email", + "detail": "patients.email holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.7 + }, + { + "group": "fault", + "name": "wrong_value:phone", + "detail": "patients.phone holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.49 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another patients row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.54 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the patients record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "added", + "columns": [ + "dob", + "email", + "first_name", + "id", + "last_name", + "mrn", + "phone", + "status", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.35 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another patients row's mrn edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "mrn" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.35 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the patients write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 4.73 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "note": "the sandbox has no second user", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.4 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.31 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.39 + } + ], + "attribution": [ + { + "table": "audit_log", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "actor", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "event", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "record_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "table_name", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "email", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "phone", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "updated_by", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "version", + "cause": "constant", + "excluded": false, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..00965a0c7f --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml @@ -0,0 +1,41 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(p."id" AS TEXT) AS "id", CAST(p."mrn" AS TEXT) AS "mrn", CAST(p."phone" AS TEXT) AS "phone", CAST(p."email" AS TEXT) AS "email", CAST(p."version" AS TEXT) AS "version", CAST(p."updated_by" AS TEXT) AS "updated_by" FROM "patients" p + audit: + kind: sql + sql_query: SELECT CAST(a."id" AS TEXT) AS "id", CAST(a."actor" AS TEXT) AS "actor", CAST(a."table_name" AS TEXT) AS "table_name", CAST(a."event" AS TEXT) AS "event", CAST(a."record_id" AS TEXT) AS "record_id", CAST(p."mrn" AS TEXT) AS "mrn" FROM "audit_log" a JOIN "patients" p ON a."table_name" = 'patients' AND a."record_id" = p."id" +effects: +- kind: record_written + probe: surface=record|patient with this MRN has the new phone and email + match: + mrn: {param: mrn} + phone: {param: phone} + email: {param: email} + expected_count: 1 +- kind: record_written + probe: surface=audit|exactly one new update audit row for this patient + match: + mrn: {param: mrn} + table_name: {literal: patients} + event: {literal: update} + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: [phone, email, version, updated_by] + database: + dialect: postgresql + views: + patients: record + judged_by: + audit_log: audit + new_row_fields: + audit_log: [id, actor, record_id] + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 diff --git a/packages/flow/benchmark/verify_draft/results/workbench/result.json b/packages/flow/benchmark/verify_draft/results/workbench/result.json new file mode 100644 index 0000000000..9235a95956 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/result.json @@ -0,0 +1,328 @@ +{ + "app": "workbench", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 1.3, + "operator_inputs": [ + "app base URL", + "agent sign-in (user, password)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 1.21, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", + "model_usd": 0.0615, + "model_calls": [ + { + "at": 1795247675.958372, + "label": "workbench", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 761, + "output_tokens": 2382, + "cache_read_tokens": 0, + "cache_write_tokens": 2155, + "usd": 0.061459, + "seconds": 20.73, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": true, + "faults_applicable": 6, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 3, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the sandbox has no second user" + }, + "seconds": 51.35 + } + ], + "notes": [ + "the workbench signs in one user only: no second actor, so no lost-update case and no actor axis" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.46 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.05 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.42 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.55 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.1 + }, + { + "group": "fault", + "name": "wrong_value:email", + "detail": "patients.email holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.55 + }, + { + "group": "fault", + "name": "wrong_value:phone", + "detail": "patients.phone holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.36 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another patients row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.66 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the patients record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "added", + "columns": [ + "dob", + "email", + "first_name", + "id", + "last_name", + "mrn", + "phone", + "status", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.27 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another patients row's mrn edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "mrn" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.37 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the patients write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.62 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "note": "the sandbox has no second user", + "reasons": [], + "moved": [], + "seconds": 0.0 + } + ], + "faults_applicable": 6, + "faults_caught": 6, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml new file mode 100644 index 0000000000..fc5d3a2e9d --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml @@ -0,0 +1,28 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:58055 +actors: + agent: + id: clinician + login: + method: POST + path: /login + form: + username: clinician + password: synthetic +store: + dialect: postgresql + read: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9796 + dbname: wb_mockmed + user: wb_reader + admin: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9796 + dbname: wb_mockmed + user: wb_admin diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml new file mode 100644 index 0000000000..76c4cbc1b9 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml @@ -0,0 +1,5 @@ +instruction: Update patient MRN-1002's phone to 555-0177 and email to b.okafor@clinic.example.org. +params: + mrn: MRN-1002 + phone: 555-0177 + email: b.okafor@clinic.example.org diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har b/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har new file mode 100644 index 0000000000..142362b22e --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har @@ -0,0 +1,135 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "POST", + "url": "http://127.0.0.1:58055/login", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Content-Length", + "value": "37" + }, + { + "name": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "text": "username=clinician&password=synthetic" + } + }, + "response": { + "status": 303, + "content": { + "mimeType": "", + "text": "" + } + } + }, + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:58055/e/patient/2/edit", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Cookie", + "value": "REDACTED" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "text/html; charset=utf-8", + "text": "Edit Ben Okafor - MockMed
MockMedPatientsSigned in as clinician Sign out

Edit Ben Okafor

" + } + } + }, + { + "request": { + "method": "POST", + "url": "http://127.0.0.1:58055/e/patient/2/edit", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Cookie", + "value": "REDACTED" + }, + { + "name": "Content-Length", + "value": "109" + }, + { + "name": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "text": "__version=1&first_name=Ben&last_name=Okafor&dob=1975-07-30&phone=555-0177&email=b.okafor%40clinic.example.org" + } + }, + "response": { + "status": 303, + "content": { + "mimeType": "", + "text": "" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/run.py b/packages/flow/benchmark/verify_draft/run.py index cbc7473fa4..e6688701f8 100644 --- a/packages/flow/benchmark/verify_draft/run.py +++ b/packages/flow/benchmark/verify_draft/run.py @@ -43,7 +43,13 @@ def heldout(run: AppRun, contract_path: Path, work: Path) -> dict[str, Any]: task = load_task(run.task) base = store.read() - demo = A.record_demo(store, app, writes(load_trace(run.trace), skip_paths=app.login_paths()), task.params, base) + demo = A.record_demo( + store, + app, + writes(load_trace(run.trace), skip_paths=app.login_paths()), + task.params, + base, + ) q = A.Qualifier(sandbox, store, app, demo, seed=1, workdir=work) contract = yaml.safe_load(contract_path.read_text(encoding="utf-8")) contract.pop("provenance", None) @@ -51,16 +57,27 @@ def heldout(run: AppRun, contract_path: Path, work: Path) -> dict[str, Any]: adm = q.qualify(contract, run.heldout_payloads, base_values=values, attribute=False) extra: list[A.Case] = [] if run.other_record: - case = A.Case("fault", "app_sibling", f"the same write also sent to {run.other_record} through the app", "refuted") + case = A.Case( + "fault", + "app_sibling", + f"the same write also sent to {run.other_record} through the app", + "refuted", + ) def both(pre: Any, post: Any) -> None: - app.send(demo.writes, "agent", swap_map(demo.params, {**values, **run.other_record})) + app.send( + demo.writes, + "agent", + swap_map(demo.params, {**values, **run.other_record}), + ) q.run(contract, case, values=values, fault=both) q._judge(case) extra.append(case) if demo.change == "added": - case = A.Case("fault", "app_duplicate", "the write sent twice through the app", "refuted") + case = A.Case( + "fault", "app_duplicate", "the write sent twice through the app", "refuted" + ) def twice(pre: Any, post: Any) -> None: app.send(demo.writes, "agent", swap_map(demo.params, values)) @@ -71,9 +88,17 @@ def twice(pre: Any, post: Any) -> None: cases = adm.cases + extra return { "cases": [c.as_dict() for c in cases], - "faults_applicable": sum(1 for c in cases if c.group == "fault" and c.applicable), - "faults_caught": sum(1 for c in cases if c.group == "fault" and c.applicable and c.passed), - "faults_missed": [c.name for c in cases if c.group == "fault" and c.applicable and not c.passed], + "faults_applicable": sum( + 1 for c in cases if c.group == "fault" and c.applicable + ), + "faults_caught": sum( + 1 for c in cases if c.group == "fault" and c.applicable and c.passed + ), + "faults_missed": [ + c.name + for c in cases + if c.group == "fault" and c.applicable and not c.passed + ], "clean": sum(1 for c in cases if c.group == "clean"), "false_stops": [c.name for c in cases if c.group == "clean" and not c.passed], "problems": adm.problems, @@ -84,7 +109,9 @@ def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser() ap.add_argument("app", choices=sorted(SETUPS)) ap.add_argument("--out", required=True) - ap.add_argument("--spend-ledger", default="benchmark/verify_draft/results/spend.jsonl") + ap.add_argument( + "--spend-ledger", default="benchmark/verify_draft/results/spend.jsonl" + ) ap.add_argument("--spend-cap-usd", type=float, default=30.0) args = ap.parse_args(argv) out = Path(args.out) @@ -109,12 +136,26 @@ def main(argv: list[str] | None = None) -> int: rounds = [ { "admitted": a.admitted, - "faults_applicable": sum(1 for c in a.cases if c.group == "fault" and c.applicable), - "faults_caught": sum(1 for c in a.cases if c.group == "fault" and c.applicable and c.passed), + "faults_applicable": sum( + 1 for c in a.cases if c.group == "fault" and c.applicable + ), + "faults_caught": sum( + 1 + for c in a.cases + if c.group == "fault" and c.applicable and c.passed + ), "clean": sum(1 for c in a.cases if c.group == "clean"), - "false_stops": [c.name for c in a.cases if c.group == "clean" and not c.passed], - "probe_writes_confirmed": sum(1 for c in a.cases if c.group == "probe" and c.passed), - "attribution_problems": [f"{x.table}.{x.column}: {x.problem}" for x in a.attribution if x.problem], + "false_stops": [ + c.name for c in a.cases if c.group == "clean" and not c.passed + ], + "probe_writes_confirmed": sum( + 1 for c in a.cases if c.group == "probe" and c.passed + ), + "attribution_problems": [ + f"{x.table}.{x.column}: {x.problem}" + for x in a.attribution + if x.problem + ], "not_applicable": {c.name: c.note for c in a.cases if not c.applicable}, "seconds": a.seconds, } @@ -129,9 +170,10 @@ def main(argv: list[str] | None = None) -> int: "setup_minutes": round(minutes, 2), "person_decisions": outcome.decisions, "questions": outcome.questions, - "drafts": len(outcome.admissions) or outcome.rounds, + "drafts": outcome.rounds, "drafts_admitted": sum(1 for a in outcome.admissions if a.admitted), - "drafts_rejected": (len(outcome.admissions) or outcome.rounds) - sum(1 for a in outcome.admissions if a.admitted), + "drafts_rejected": outcome.rounds + - sum(1 for a in outcome.admissions if a.admitted), "admitted": outcome.admitted, "reason": outcome.reason[:2000], "model": M.MODEL, @@ -142,9 +184,19 @@ def main(argv: list[str] | None = None) -> int: "notes": run.notes, } if outcome.admitted and outcome.contract_path is not None: - result["heldout"] = heldout(run, outcome.contract_path, out / "heldout-work") - (out / "result.json").write_text(json.dumps(result, indent=1, default=str), encoding="utf-8") - print(json.dumps({k: v for k, v in result.items() if k not in ("model_calls",)}, indent=1, default=str)) + result["heldout"] = heldout( + run, outcome.contract_path, out / "heldout-work" + ) + (out / "result.json").write_text( + json.dumps(result, indent=1, default=str), encoding="utf-8" + ) + print( + json.dumps( + {k: v for k, v in result.items() if k not in ("model_calls",)}, + indent=1, + default=str, + ) + ) return 0 finally: run.teardown() diff --git a/packages/flow/docs/VERIFY_DRAFT.md b/packages/flow/docs/VERIFY_DRAFT.md new file mode 100644 index 0000000000..a83fc6b7ad --- /dev/null +++ b/packages/flow/docs/VERIFY_DRAFT.md @@ -0,0 +1,199 @@ +# Draft a write contract with a model, admit it by qualification + +Writing a [write contract](VERIFY_WRITES.md) by hand for a new system takes +time and many small decisions: which tables to read, which columns identify +the record, what the app writes on its own, how long to wait for a late +change. `openadapt verify draft` hands that work to a model at setup time, +then tests what the model wrote before anything trusts it: + +- the model drafts the contract from the system's description, one trace of + a correct write, and the task; +- OpenAdapt plants faults in a sandbox copy and replays clean writes there; +- the contract is admitted only if it catches every fault and accepts every + clean write. + +Running an admitted contract makes no model calls. It is an ordinary +`openadapt.verify/v1` contract, judged by the deterministic verifier. + +```bash +export ANTHROPIC_API_KEY=... # read from the environment only +openadapt verify draft \ + --describe openapi.json \ # or a GraphQL schema, a FHIR CapabilityStatement, db, or none + --trace demo.har \ # one correct demonstration + --task task.yaml \ # the instruction and the values it used + --sandbox sandbox.yaml \ # where to test it + --out contracts/update_recipe +``` + +## What you give it + +**The system's description** (`--describe`). One of: + +- an OpenAPI or Swagger document; +- a GraphQL schema, as SDL text or an introspection result; +- a FHIR CapabilityStatement; +- `db`, which reads the database schema through the sandbox (tables, + columns, keys); +- `none`. + +The command cuts the description down to what a check needs before it goes +to the model. + +**One trace** (`--trace`). A HAR file of one correct demonstration of the +write. The command replays its write requests in the sandbox. Before anything +is sent to the model, it removes sign-in headers (`Authorization`, `Cookie`, +API-key headers) and masks fields whose names look secret (password, token, +key, session). + +**The task** (`--task`): + +```yaml +instruction: Update the recipe lentil-soup's description and yield. +params: + slug: lentil-soup + description: Red lentils, cumin and lemon. + recipe_yield: 6 bowls +``` + +`actor_id` is reserved. The sandbox binds it to the acting user's id. + +**The sandbox** (`--sandbox`, `openadapt.verify-sandbox/v1`). It holds +facts, not judgments about the check: + +- where the app answers; +- how two users sign in; +- two connections to the app's database: the read-only one the contract + will read with, and a privileged one that plants faults. + +```yaml +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:9000 +actors: + agent: # the user the agent writes as + id: "87c53c26-..." # that user's id as the store holds it + login: {method: POST, path: /api/auth/token, token_field: access_token, + form: {username: agent@example.org, password: "${AGENT_PW}"}} + other: # a second, ordinary user (optional) + id: "4be1..." + login: {method: POST, path: /api/auth/token, token_field: access_token, + form: {username: cook2, password: "${COOK_PW}"}} +store: + dialect: postgresql # or sqlite, mysql + read: {sql_driver: psycopg2, sql_connect_args: {host: 127.0.0.1, port: 5432, user: reader, dbname: app}, sql_password_env: APP_READER_PW} + admin: {sql_driver: psycopg2, sql_connect_args: {host: 127.0.0.1, port: 5432, user: app, dbname: app}, sql_password_env: APP_PW} +``` + +An actor can instead give fixed `headers` (for example +`Authorization: "Bearer ${TOKEN}"`). The command checks once, before any +model call, that the read account can take a whole-database snapshot. The +sandbox must be a copy you can write to: admission writes to it and puts +it back between cases by restoring the rows it read at the start. You write +no reset hook. + +## What it does + +1. **Record the demonstration.** The sandbox replays the trace's writes + once, between two reads of the store, to see which rows they move. The + model gets the rows and columns that moved, with their values. The + sandbox holds synthetic data only. +2. **Draft.** The pinned model writes a contract that diffs the whole + database (`frame.database`). It also writes other valid values for the + task to test with. Connection keys are filled in from the sandbox. A + draft that sets a hook, a session, a reset or a command, or whose read is + not a plain SELECT, is refused without being run. +3. **Qualify.** Each case restores the store, takes the contract's + baseline, replays the write through the app, and then plants one fault + with the privileged connection: + + | Case | What the store holds after the write | Must be | + |---|---|---| + | `wrong_value` | one written column of the record holds another value (one case per column that holds a task value as written; a lower-cased copy only for an email address) | refuted | + | `wrong_row` | the write on another record: an update moved to a sibling, or a create filed under another parent | refuted | + | `duplicate` | a second copy of the record (unique columns changed so the store accepts it) | refuted | + | `sibling_edit` | another business record edited beside the write | refuted | + | `late_revert` | the write undone after the check confirmed it | refuted at the recheck | + | `lost_update` | updates only: the other user saves the record first, then the agent's save overwrites it, both through the app | refuted, or prevented by the app | + | 5 clean writes | the write with other values, and a recheck of each | confirmed | + | attribution probe | the write by two users with two sets of values (2 x 2), and the first of them again | confirmed | + + The **causal-attribution probe** sorts every column that moved by cause: + + - on its own (`clock` or `fresh`): it differs between two identical + writes, like a timestamp or a new row id; + - the values written (`payload`); + - who wrote (`actor`); + - nothing (`constant`): it moves the same way every time. + + The contract's bookkeeping exclusions (`allow_tables`, `ignore_columns`) + must agree with that sorting: + + - excluding a column that follows the values written hides the write + itself, so it fails; + - excluding a column that never moved has nothing to excuse and can only + hide a fault, so it fails too. + + A literal in an effect that pins the demonstrated record also fails, for + example its id or its name. The check must hold for any record the task + names. +4. **Feed back.** A failed admission goes back to the model with each + failing case, its reasons and the rows that moved (names only). This + happens at most 3 rounds in all. Then the command stops and prints why + (`report.json`). +5. **Ask once, only when needed.** Sometimes a planted fault could go only + into columns the draft excludes. Then the command asks a person, once, + whether those columns are bookkeeping the app sets on its own or data + people edit. Answer from a file with `--answers answers.yaml` + (`table.column: bookkeeping` or `business`), or at the terminal. With + `--no-input`, or no terminal, the draft is refused rather than admitted + on a guess. + +Admission runs with the contract's recheck window shortened to 2 seconds. +The check is otherwise the same, and the admitted contract keeps its own +window. + +## What it writes + +- `contract.yaml`, only when the draft was admitted. Its `provenance` + section records: + - the model and the prompt (version and SHA-256); + - the inputs' digests; + - the admission: the check digest, each fault's result, the clean writes + and probe writes confirmed, and any column a person confirmed as + bookkeeping. + + `verify-run` and the verifier ignore `provenance`. +- `rounds/round-N.yaml` and `rounds/round-N.admission.json`: every draft and + every case's outcome. +- `report.json`: admitted or not, rounds, person decisions, seconds and + model cost. + +`openadapt verify draft --check contract.yaml` tells you whether the file is +still the check that was admitted. Any edit to its effects, its reads or its +frame after admission makes the check fail. + +## The model and its cost + +The model is pinned in `openadapt_flow/verify_draft/model.py` (`MODEL`, +`EFFORT`, `PROMPT_VERSION`). A refusal, or a model that falls back to +another, never changes the check silently: the response's model id is +recorded too. Every call is appended to a spend ledger (`--spend-ledger`, +default `~/.openadapt/verify-draft/spend.jsonl`). The command refuses to +send a call that could pass `--spend-cap-usd` (default 30). + +## Limits + +- The store must be SQLite, PostgreSQL or MySQL/MariaDB, reachable from the + machine that runs the command. A system you can only reach through its API + can't be qualified this way yet: the late-revert case needs the + whole-database recheck. +- The clean writes and the attribution probe vary the task's values, not + the record. A check that only works on the demonstrated record is caught + by the literal-pin rule, not by a write to another record. +- Lost updates need a second user in the sandbox. Without one, that case is + reported as not applicable. +- Faults are planted in the database, not made by the app. An app-made + fault the store can't express this way, such as an email sent, is outside + the contract's read. + +Measured on three apps: [benchmark/verify_draft/RESULTS.md](../benchmark/verify_draft/RESULTS.md). diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py index 0862d13485..6c2ce18ccc 100644 --- a/packages/flow/openadapt_flow/verify_draft/admit.py +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -76,9 +76,22 @@ #: The recheck window admission cases use. ADMISSION_RECHECK_S = 2.0 _FORBIDDEN_KEYS = frozenset( - {"session", "reset", "command", "python", "hook", "hooks", "sql_driver", - "sql_connect_args", "sql_password_env", "sqlite_database", "admission", - "owned_sqlite_insert", "profile", "profile_sha256"} + { + "session", + "reset", + "command", + "python", + "hook", + "hooks", + "sql_driver", + "sql_connect_args", + "sql_password_env", + "sqlite_database", + "admission", + "owned_sqlite_insert", + "profile", + "profile_sha256", + } ) _IDENTIFIER = re.compile(r"(^|_)(id|key|no|number|code|slug|mrn|ref|uuid)$", re.I) @@ -96,7 +109,11 @@ def _walk(value: Any, path: str = "") -> list[str]: for k, v in value.items(): if k in _FORBIDDEN_KEYS: bad.append(f"{path}{k}") - if isinstance(v, str) and re.fullmatch(r"[\w.]+:[\w]+", v) and k not in ("probe",): + if ( + isinstance(v, str) + and re.fullmatch(r"[\w.]+:[\w]+", v) + and k not in ("probe",) + ): if k in ("driver", "module", "function"): bad.append(f"{path}{k}") bad += _walk(v, f"{path}{k}.") @@ -174,7 +191,11 @@ def excluded(contract: Mapping[str, Any]) -> dict[str, set[str]]: out: dict[str, set[str]] = {} for entry in database.get("allow_tables") or []: table = entry if isinstance(entry, str) else entry.get("table") - mode = "append_only" if isinstance(entry, str) else entry.get("mode", "append_only") + mode = ( + "append_only" + if isinstance(entry, str) + else entry.get("mode", "append_only") + ) out.setdefault(str(table), set()).add("*" if mode == "skip" else "+") for table, cols in (database.get("ignore_columns") or {}).items(): out.setdefault(str(table), set()).update(str(c) for c in cols) @@ -227,7 +248,9 @@ def moved_text(self) -> str: ) for c in cols } - lines.append(f"{m.change} {m.table} key={_keytext(m.key)}: {json.dumps(vals)[:1500]}") + lines.append( + f"{m.change} {m.table} key={_keytext(m.key)}: {json.dumps(vals)[:1500]}" + ) return "\n".join(lines) or "(nothing moved)" @@ -239,8 +262,10 @@ def _matches(stored: Any, value: Any) -> bool: a, b = text(stored).strip(), text(value).strip() if not b: return False - if a == b or a.casefold() == b.casefold(): + if a == b: return True + if "@" in b and a.casefold() == b.casefold(): + return True # an email address the app stored in another case try: return decimal.Decimal(a) == decimal.Decimal(b) except (decimal.InvalidOperation, ValueError): @@ -248,7 +273,9 @@ def _matches(stored: Any, value: Any) -> bool: return len(b) >= 10 and a.startswith(b) # a date read back as a date-time -def main_move(found: Sequence[Move], params: Mapping[str, Any]) -> tuple[Optional[Move], dict[str, str]]: +def main_move( + found: Sequence[Move], params: Mapping[str, Any] +) -> tuple[Optional[Move], dict[str, str]]: """The added or changed row holding the most task values, and which of its columns holds which value.""" @@ -275,9 +302,10 @@ def main_move(found: Sequence[Move], params: Mapping[str, Any]) -> tuple[Optiona def record_demo( store: Store, app: App, writes: list[Request], params: dict[str, Any], base: Rows ) -> Demo: + store.remember(base) store.restore(base) statuses = app.send(writes, "agent", {}) - after = store.read() + after = store.read_moved(base) found = moves(base, after) main, cols = main_move(found, params) store.restore(base) @@ -494,14 +522,16 @@ def run( case.note = f"the app refused the write (HTTP {max(statuses)})" return None pre = self.demo.base - post = self.store.read() + post = self.store.read_moved(pre) if fault is not None: fault(pre, post) - post = self.store.read() + post = self.store.read_moved(pre) result = verify_write(pending, seal=False) case.outcome = result.outcome.value case.reasons = list(result.reasons) - case.moved = list(((result.evidence or {}).get("frame") or {}).get("moves") or [])[:20] + case.moved = list( + ((result.evidence or {}).get("frame") or {}).get("moves") or [] + )[:20] if rechecks and result.outcome.value == "CONFIRMED": if result.recheck is None: case.recheck = "NONE" @@ -511,7 +541,14 @@ def run( else: if revert is not None: revert(pre, post) - rr = recheck(c, result, params=params, actor=Actor("agent", f"verify-draft-{actor}"), wait=True, ledger=ledger) + rr = recheck( + c, + result, + params=params, + actor=Actor("agent", f"verify-draft-{actor}"), + wait=True, + ledger=ledger, + ) case.recheck = str(getattr(rr.outcome, "value", rr.outcome)) case.reasons += list(rr.reasons) return pre, post @@ -530,10 +567,20 @@ def _judge(case: Case) -> None: case.passed = True return if case.expect == "confirmed": - case.passed = case.outcome == "CONFIRMED" and case.recheck in ("", "CONFIRMED") + # No recheck scheduled is the late-revert case's failure, not a + # false stop on a clean write. + case.passed = case.outcome == "CONFIRMED" and case.recheck in ( + "", + "CONFIRMED", + "NONE", + ) else: final = case.recheck or case.outcome - case.passed = case.outcome not in ("", "ERROR", "NO_BASELINE") and final != "CONFIRMED" and final != "NONE" + case.passed = ( + case.outcome not in ("", "ERROR", "NO_BASELINE") + and final != "CONFIRMED" + and final != "NONE" + ) # -- the suite @@ -564,13 +611,35 @@ def qualify( for i, v in enumerate(values): if len(accepted) >= clean: break - case = Case("clean", f"clean-{len(accepted) + 1}", f"the write with payload {i + 1}", "confirmed") + case = Case( + "clean", + f"clean-{len(accepted) + 1}", + f"the write with payload {i + 1}", + "confirmed", + ) self.run(contract, case, values=v, rechecks=True) if not case.applicable: continue # the app refused these values: not a probe self._judge(case) cases.append(case) accepted.append(v) + if not case.passed and len(accepted) == 1: + # A check that stops a clean write can't be judged on faults + # yet: say so now rather than spend the round. + problems.append( + "stopped after the first clean write was not confirmed: fix that first " + "(no fault was planted this round)" + ) + self.store.restore(demo.base) + return Admission( + False, + check_sha256(contract), + cases, + [], + problems, + [], + round(time.monotonic() - started, 2), + ) if len(accepted) < clean: problems.append( f"only {len(accepted)} of the payloads were accepted by the app; {clean} clean writes are needed" @@ -585,7 +654,9 @@ def qualify( attribution: list[Attribution] = [] probe_cases: list[Case] = [] if attribute: - attribution, probe_cases = self._attribute(contract, [base_values] + accepted[:1]) + attribution, probe_cases = self._attribute( + contract, [base_values] + accepted[:1] + ) cases += probe_cases self.store.restore(demo.base) # leave the sandbox as it was found for c in cases: @@ -615,16 +686,22 @@ def _pins(self, contract: Mapping[str, Any]) -> list[str]: m = self.demo.main if m is None: return [] - rows = list(self.demo.base.get(m.table, {}).values()) + list(self.demo.after.get(m.table, {}).values()) - own = {text(v) for v in (m.before or {}).values()} | {text(v) for v in (m.after or {}).values()} + rows = list(self.demo.base.get(m.table, {}).values()) + list( + self.demo.after.get(m.table, {}).values() + ) + own = {text(v) for v in (m.before or {}).values()} | { + text(v) for v in (m.after or {}).values() + } common = set() - for col in (m.after or {}): + for col in m.after or {}: values = {text(r.get(col)) for r in rows} if len(values) == 1: common |= values out = [] for effect in contract.get("effects") or []: - selectors = [effect.get("match") or {}] + list(effect.get("new_records") or []) + selectors = [effect.get("match") or {}] + list( + effect.get("new_records") or [] + ) for sel in selectors: for field_name, expr in sel.items(): if isinstance(expr, dict) and "literal" in expr: @@ -648,7 +725,9 @@ def _values(self, payload: Mapping[str, Any]) -> dict[str, Any]: # -- fault operators - def _target(self, pre: Rows, post: Rows, values: Mapping[str, Any]) -> tuple[Optional[Move], dict[str, str]]: + def _target( + self, pre: Rows, post: Rows, values: Mapping[str, Any] + ) -> tuple[Optional[Move], dict[str, str]]: return main_move(moves(pre, post), values) def _fault( @@ -664,17 +743,30 @@ def _fault( mask = excluded(contract) if name == "wrong_value": - cols = sorted(demo.param_columns)[: 4] or [] + cols = sorted(demo.param_columns)[:4] or [] if not cols: - c = Case("fault", "wrong_value", "no written column holds a task value", "refuted", applicable=False) + c = Case( + "fault", + "wrong_value", + "no written column holds a task value", + "refuted", + applicable=False, + ) return [c] for col in cols: - case = Case("fault", f"wrong_value:{col}", f"{table}.{col} holds another value", "refuted") + case = Case( + "fault", + f"wrong_value:{col}", + f"{table}.{col} holds another value", + "refuted", + ) def plant(pre: Rows, post: Rows, col: str = col) -> None: m, _ = self._target(pre, post, values) if m is None: - raise RuntimeError("the write moved no row holding a task value") + raise RuntimeError( + "the write moved no row holding a task value" + ) self.store.update(m.table, m.key, {col: _perturb(m.after[col])}) self.run(contract, case, values=values, fault=plant) @@ -696,19 +788,31 @@ def plant_row(pre: Rows, post: Rows) -> None: other = others[self.seed % len(others)] moved = {c: m.after[c] for c in m.columns} self.store.update(m.table, other, moved) - self.store.update(m.table, m.key, {c: m.before[c] for c in m.columns}) + self.store.update( + m.table, m.key, {c: m.before[c] for c in m.columns} + ) case.detail = f"the update landed on another {m.table} row" return fk = [c for c in m.columns if c in t.fks and m.after.get(c) is not None] if fk: col = fk[0] ref = self.store.tables[t.fks[col]] - choices = [k for k in post.get(ref.name, {}) if len(ref.pk) == 1 and text(k[0]) != text(m.after[col])] + choices = [ + k + for k in post.get(ref.name, {}) + if len(ref.pk) == 1 and text(k[0]) != text(m.after[col]) + ] if choices: - self.store.update(m.table, m.key, {col: choices[self.seed % len(choices)][0]}) + self.store.update( + m.table, m.key, {col: choices[self.seed % len(choices)][0]} + ) case.detail = f"the new {m.table} row points at another {ref.name} ({col})" return - ids = [c for c, p in cols.items() if _IDENTIFIER.search(c) or _IDENTIFIER.search(p)] + ids = [ + c + for c, p in cols.items() + if _IDENTIFIER.search(c) or _IDENTIFIER.search(p) + ] if not ids: raise _NotApplicable("the new row names no parent record") self.store.update(m.table, m.key, {ids[0]: _perturb(m.after[ids[0]])}) @@ -718,13 +822,17 @@ def plant_row(pre: Rows, post: Rows) -> None: return [case] if name == "duplicate": - case = Case("fault", "duplicate", f"a second copy of the {table} record", "refuted") + case = Case( + "fault", "duplicate", f"a second copy of the {table} record", "refuted" + ) def plant_dup(pre: Rows, post: Rows) -> None: m, _ = self._target(pre, post, values) if m is None: raise RuntimeError("the write moved no row holding a task value") - self.store.insert(m.table, self.store.new_key_row(m.table, m.after, post)) + self.store.insert( + m.table, self.store.new_key_row(m.table, m.after, post) + ) self._planted(contract, case, values, plant_dup) return [case] @@ -734,10 +842,18 @@ def plant_dup(pre: Rows, post: Rows) -> None: def plant_sib(pre: Rows, post: Rows) -> None: m, _ = self._target(pre, post, values) - order = [m.table] + [t for t in self.store.tables if t != m.table] if m else list(self.store.tables) + order = ( + [m.table] + [t for t in self.store.tables if t != m.table] + if m + else list(self.store.tables) + ) hidden: list[str] = [] for tname in order: - rows = [(k, r) for k, r in post.get(tname, {}).items() if not (m and tname == m.table and k == m.key)] + rows = [ + (k, r) + for k, r in post.get(tname, {}).items() + if not (m and tname == m.table and k == m.key) + ] t = self.store.tables[tname] for key, row in rows: for col in t.columns: @@ -753,13 +869,16 @@ def plant_sib(pre: Rows, post: Rows) -> None: if not t.pk: continue self.store.update(tname, key, {col: _perturb(row[col])}) - case.detail = f"another {tname} row's {col} edited beside the write" + case.detail = ( + f"another {tname} row's {col} edited beside the write" + ) return if hidden: for h in hidden[:3]: self.masked.append({"fault": "sibling_edit", "column": h}) raise _NotApplicable( - "every editable column of the other records is excluded: " + ", ".join(hidden[:3]) + "every editable column of the other records is excluded: " + + ", ".join(hidden[:3]) ) raise _NotApplicable("the store holds no other record to edit") @@ -767,7 +886,12 @@ def plant_sib(pre: Rows, post: Rows) -> None: return [case] if name == "late_revert": - case = Case("fault", "late_revert", f"the {table} write undone after the check", "refuted") + case = Case( + "fault", + "late_revert", + f"the {table} write undone after the check", + "refuted", + ) def undo(pre: Rows, post: Rows) -> None: m, _ = self._target(pre, post, values) @@ -776,7 +900,9 @@ def undo(pre: Rows, post: Rows) -> None: if m.change == "added": self.store.delete(m.table, m.key) else: - self.store.update(m.table, m.key, {c: m.before[c] for c in m.columns}) + self.store.update( + m.table, m.key, {c: m.before[c] for c in m.columns} + ) self.run(contract, case, values=values, revert=undo, rechecks=True) if case.outcome == "CONFIRMED" and not case.recheck: @@ -786,30 +912,48 @@ def undo(pre: Rows, post: Rows) -> None: if name == "lost_update": case = Case("fault", "lost_update", "", "refuted") if demo.change != "changed": - case.applicable, case.note = False, "the write creates a record; nothing can be overwritten" + case.applicable, case.note = ( + False, + "the write creates a record; nothing can be overwritten", + ) return [case] if "other" not in self.sandbox.actors: case.applicable, case.note = False, "the sandbox has no second user" return [case] other_values = accepted[0] if accepted else None if other_values is None: - case.applicable, case.note = False, "no accepted payload for the other user" + case.applicable, case.note = ( + False, + "no accepted payload for the other user", + ) return [case] def first_save() -> Optional[str]: - st = self.app.send(demo.writes, "other", swap_map(demo.params, other_values)) + st = self.app.send( + demo.writes, "other", swap_map(demo.params, other_values) + ) if any(s >= 400 for s in st): return f"the other user's save was refused (HTTP {max(st)})" return None - case.detail = "the other user saves the record, then the agent's save overwrites it" + case.detail = ( + "the other user saves the record, then the agent's save overwrites it" + ) self.run(contract, case, values=values, before=first_save) if case.note.startswith("the app refused"): - case.note = "the app refused the stale save: it prevents lost updates itself" + case.note = ( + "the app refused the stale save: it prevents lost updates itself" + ) return [case] raise ValueError(f"unknown fault {name}") - def _planted(self, contract: Mapping[str, Any], case: Case, values: Mapping[str, Any], plant: Callable[[Rows, Rows], None]) -> None: + def _planted( + self, + contract: Mapping[str, Any], + case: Case, + values: Mapping[str, Any], + plant: Callable[[Rows, Rows], None], + ) -> None: def guarded(pre: Rows, post: Rows) -> None: try: plant(pre, post) @@ -835,13 +979,22 @@ def _attribute( return [], [] runs: dict[tuple[str, int], list[Move]] = {} cases = [] - for actor in actors: - for i, values in enumerate(payloads[:2]): - case = Case("probe", f"attribution:{actor}:p{i + 1}", f"the write by {actor} with payload {i + 1}", "confirmed") - got = self.run(contract, case, values=values, actor=actor) - cases.append(case) - if got is not None: - runs[(actor, i)] = moves(*got) + # Each actor with each payload, plus the first one again: what moves + # between two identical writes moves on its own (a clock, a new id). + plan = [(a, i) for a in actors for i in (0, 1)] + [(actors[0], 2)] + for actor, i in plan: + values = payloads[min(i, 1) if i < 2 else 0] + label = f"p{i + 1}" if i < 2 else "p1-again" + case = Case( + "probe", + f"attribution:{actor}:{label}", + f"the write by {actor} with payload {1 if i == 2 else i + 1}", + "confirmed", + ) + got = self.run(contract, case, values=values, actor=actor) + cases.append(case) + if got is not None: + runs[(actor, i)] = moves(*got) # Every (table, column) that moved, with its new value per run. cells: dict[tuple[str, str], dict[tuple[str, int], str]] = {} for run, found in runs.items(): @@ -851,9 +1004,14 @@ def _attribute( continue cols = m.columns if m.change == "changed" else sorted(m.after or {}) for col in cols: - cells.setdefault((m.table, col), {})[run] = text((m.after or {}).get(col)) + cells.setdefault((m.table, col), {})[run] = text( + (m.after or {}).get(col) + ) if m.change == "added": cells.setdefault((m.table, "+"), {})[run] = "added" + for seen in cells.values(): # a run that didn't move the cell + for run in runs: + seen.setdefault(run, "") mask = excluded(contract) out: list[Attribution] = [] for (table, col), seen in sorted(cells.items()): @@ -861,7 +1019,7 @@ def _attribute( ex = mask.get(table, set()) is_ex = "*" in ex or col in ex or (col == "+" and "+" in ex) a = Attribution(table, col, cause, is_ex) - if is_ex and cause == "payload": + if is_ex and cause == "payload" and col != "+": a.problem = "excluded, but it moves with the values written: the exclusion hides the write" out.append(a) moved = {(a.table, a.column) for a in out} @@ -872,21 +1030,40 @@ def _attribute( if col == "+" and (table, "+") in moved: continue if (table, col) not in moved and col not in ("*", "+"): - out.append(Attribution(table, col, "never moved", True, "excluded, but it never moved in any probe write: nothing to excuse")) + out.append( + Attribution( + table, + col, + "never moved", + True, + "excluded, but it never moved in any probe write: nothing to excuse", + ) + ) return out, cases def _cause(seen: Mapping[tuple[str, int], str], actors: Sequence[str]) -> str: - """payload, actor, clock or constant, from the 2 x 2 runs.""" + """payload, actor, fresh, clock or constant, from the 2 x 2 runs and + the repeated first run (index 2).""" + if (actors[0], 2) in seen and (actors[0], 0) in seen: + if seen.get((actors[0], 0)) != seen.get((actors[0], 2)): + values = [v for v in seen.values()] + return "clock" if _clockish(values) else "fresh" by_payload = any( - seen.get((a, 0)) != seen.get((a, 1)) for a in actors if (a, 0) in seen or (a, 1) in seen + seen.get((a, 0)) != seen.get((a, 1)) + for a in actors + if (a, 0) in seen or (a, 1) in seen ) by_actor = len(actors) > 1 and any( seen.get((actors[0], i)) != seen.get((actors[1], i)) for i in (0, 1) ) values = [v for v in seen.values()] - if len(set(values)) == len(values) and len(values) == 2 * len(actors) and _clockish(values): + if ( + len(set(values)) == len(values) + and len(values) == 2 * len(actors) + and _clockish(values) + ): return "clock" if by_payload and not by_actor: return "payload" @@ -899,7 +1076,11 @@ def _cause(seen: Mapping[tuple[str, int], str], actors: Sequence[str]) -> str: def _clockish(values: Sequence[str]) -> bool: - return all(re.match(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}", v or "") or re.fullmatch(r"\d{9,}(\.\d+)?", v or "") for v in values) + return all( + re.match(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}", v or "") + or re.fullmatch(r"\d{9,}(\.\d+)?", v or "") + for v in values + ) class _NotApplicable(Exception): @@ -907,4 +1088,9 @@ class _NotApplicable(Exception): def digest(value: Any) -> str: - return "sha256:" + hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest() + return ( + "sha256:" + + hashlib.sha256( + json.dumps(value, sort_keys=True, default=str).encode() + ).hexdigest() + ) diff --git a/packages/flow/openadapt_flow/verify_draft/draft.py b/packages/flow/openadapt_flow/verify_draft/draft.py index 77b79862f8..09ff1f62d4 100644 --- a/packages/flow/openadapt_flow/verify_draft/draft.py +++ b/packages/flow/openadapt_flow/verify_draft/draft.py @@ -25,7 +25,6 @@ from __future__ import annotations import argparse -import copy import datetime as _dt import hashlib import json @@ -78,7 +77,9 @@ def as_dict(self) -> dict[str, Any]: Asker = Callable[[str, Sequence[str]], Optional[Mapping[str, str]]] -def first_message(task: I.Task, desc: I.Description, trace: list[Any], demo: A.Demo, dialect: str) -> str: +def first_message( + task: I.Task, desc: I.Description, trace: list[Any], demo: A.Demo, dialect: str +) -> str: writes = [I.masked(r) for r in demo.writes] return "\n\n".join( [ @@ -119,19 +120,38 @@ def run( writes = I.writes(trace, skip_paths=app.login_paths()) if not writes: raise I.InputError("the trace holds no write request") + problem = read_account_problem(sandbox) + if problem: + # An operator fix, not something a model round can repair. + raise I.InputError( + f"the sandbox's read account can't read the whole database: {problem}" + ) base = store.read() log(f"store: {len(store.tables)} tables; trace: {len(writes)} write request(s)") demo = A.record_demo(store, app, writes, task.params, base) if demo.main is None or any(s >= 400 for s in demo.statuses): return _finish( - out, started, Outcome(False, 0, 0, 0.0, 0.0, - f"replaying the trace moved no row holding a task value (HTTP {demo.statuses})"), + out, + started, + Outcome( + False, + 0, + 0, + 0.0, + 0.0, + f"replaying the trace moved no row holding a task value (HTTP {demo.statuses})", + ), [], ) - log(f"demonstration: {demo.change} {demo.main.table}, columns {sorted(demo.param_columns)}") + log( + f"demonstration: {demo.change} {demo.main.table}, columns {sorted(demo.param_columns)}" + ) qualifier = A.Qualifier(sandbox, store, app, demo, workdir=out / "work") messages: list[dict[str, Any]] = [ - {"role": "user", "content": first_message(task, desc, trace, demo, sandbox.store.dialect)} + { + "role": "user", + "content": first_message(task, desc, trace, demo, sandbox.store.dialect), + } ] usd = 0.0 decisions = 0 @@ -146,16 +166,34 @@ def run( used += 1 draft = drafter.draft(messages) usd += draft.call.usd if draft.call else 0.0 - messages.append({"role": "assistant", "content": draft.raw or json.dumps( - {"contract_yaml": draft.contract_yaml, "payloads": draft.payloads, "notes": draft.notes})}) + messages.append( + { + "role": "assistant", + "content": draft.raw + or json.dumps( + { + "contract_yaml": draft.contract_yaml, + "payloads": draft.payloads, + "notes": draft.notes, + } + ), + } + ) (out / "rounds").mkdir(exist_ok=True) - (out / "rounds" / f"round-{used}.yaml").write_text(draft.contract_yaml or "", encoding="utf-8") + (out / "rounds" / f"round-{used}.yaml").write_text( + draft.contract_yaml or "", encoding="utf-8" + ) try: contract = A.prepare(draft.contract_yaml, sandbox) except A.DraftProblem as exc: reason = str(exc) log(f"round {used}: draft refused before testing: {reason}") - messages.append({"role": "user", "content": f"The contract could not be tested: {reason}\nFix it and answer with the same JSON object."}) + messages.append( + { + "role": "user", + "content": f"The contract could not be tested: {reason}\nFix it and answer with the same JSON object.", + } + ) continue adm = qualifier.qualify(contract, draft.payloads) if adm.masked and not asked and ask is not None: @@ -170,7 +208,9 @@ def run( answers = ask(question, columns) if answers is not None: decisions += 1 - keep = [c for c, a in answers.items() if str(a).lower().startswith("book")] + keep = [ + c for c, a in answers.items() if str(a).lower().startswith("book") + ] qualifier.bookkeeping.update(keep) if set(keep) >= set(columns): adm = qualifier.qualify(contract, draft.payloads) @@ -179,7 +219,9 @@ def run( json.dumps(adm.as_dict(), indent=1, default=str), encoding="utf-8" ) passed = sum(c.passed for c in adm.cases) - log(f"round {used}: {'ADMITTED' if adm.admitted else 'rejected'} ({passed}/{len(adm.cases)} cases, {adm.seconds:.0f}s)") + log( + f"round {used}: {'ADMITTED' if adm.admitted else 'rejected'} ({passed}/{len(adm.cases)} cases, {adm.seconds:.0f}s)" + ) if adm.admitted: break reason = adm.feedback() @@ -193,9 +235,14 @@ def run( ) admitted = bool(admissions and admissions[-1].admitted) outcome = Outcome( - admitted, used, decisions, 0.0, usd, + admitted, + used, + decisions, + 0.0, + usd, "admitted" if admitted else f"refused after {used} round(s): {reason}", - admissions=admissions, questions=questions, + admissions=admissions, + questions=questions, ) if admitted and contract is not None and draft is not None: adm = admissions[-1] @@ -214,7 +261,22 @@ def run( return _finish(out, started, outcome, admissions) -def _finish(out: Path, started: float, outcome: Outcome, admissions: list[A.Admission]) -> Outcome: +def read_account_problem(sandbox: SandboxConfig) -> Optional[str]: + """Why the read-only connection can't take a whole-database snapshot, + or None. Checked once, before any model call.""" + + from openadapt_flow.verifier import BaselineUnreadable, capture_database + + try: + capture_database(A.connection(sandbox), sandbox.store.dialect) + except BaselineUnreadable as exc: + return str(exc) + return None + + +def _finish( + out: Path, started: float, outcome: Outcome, admissions: list[A.Admission] +) -> Outcome: outcome.seconds = round(time.monotonic() - started, 1) (out / "report.json").write_text( json.dumps( @@ -227,7 +289,9 @@ def _finish(out: Path, started: float, outcome: Outcome, admissions: list[A.Admi "passed": sum(c.passed for c in a.cases), "failed": [c.name for c in a.cases if not c.passed], "problems": a.problems, - "attribution_problems": [f"{x.table}.{x.column}" for x in a.attribution if x.problem], + "attribution_problems": [ + f"{x.table}.{x.column}" for x in a.attribution if x.problem + ], } for a in admissions ], @@ -261,7 +325,9 @@ def provenance( "inputs": { "description": { "kind": desc.kind, - "file_sha256": _sha(Path(describe).read_bytes()) if describe and Path(describe).is_file() else None, + "file_sha256": _sha(Path(describe).read_bytes()) + if describe and Path(describe).is_file() + else None, "text_sha256": _sha(desc.text.encode("utf-8")), }, "trace_sha256": _sha(Path(trace_path).read_bytes()), @@ -271,14 +337,22 @@ def provenance( "suite": SUITE, "check_sha256": adm.check_sha256, "rounds": rounds, - "admitted_at": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "admitted_at": _dt.datetime.now(_dt.timezone.utc).strftime( + "%Y-%m-%dT%H:%M:%SZ" + ), "recheck_window_tested_s": qualifier.recheck_s, "faults": { - c.name: ("refuted" if c.passed else "missed") if c.applicable else f"not applicable: {c.note}" + c.name: ("refuted" if c.passed else "missed") + if c.applicable + else f"not applicable: {c.note}" for c in faults }, - "clean_writes_confirmed": sum(c.passed for c in adm.cases if c.group == "clean"), - "attribution_probe_writes": sum(c.passed for c in adm.cases if c.group == "probe"), + "clean_writes_confirmed": sum( + c.passed for c in adm.cases if c.group == "clean" + ), + "attribution_probe_writes": sum( + c.passed for c in adm.cases if c.group == "probe" + ), "bookkeeping_confirmed_by_person": sorted(qualifier.bookkeeping), }, } @@ -304,14 +378,18 @@ def _ask_from(answers_path: Optional[str], interactive: bool) -> Optional[Asker] if answers_path: given = yaml.safe_load(Path(answers_path).read_text(encoding="utf-8")) or {} - def from_file(question: str, columns: Sequence[str]) -> Optional[Mapping[str, str]]: + def from_file( + question: str, columns: Sequence[str] + ) -> Optional[Mapping[str, str]]: got = {c: str(given[c]) for c in columns if c in given} return got if len(got) == len(columns) else None return from_file if interactive and sys.stdin.isatty(): - def from_tty(question: str, columns: Sequence[str]) -> Optional[Mapping[str, str]]: + def from_tty( + question: str, columns: Sequence[str] + ) -> Optional[Mapping[str, str]]: print(question, file=sys.stderr) out = {} for c in columns: @@ -328,18 +406,41 @@ def main(argv: Optional[list[str]] = None) -> int: description="Draft a write contract with a model and admit it only if OpenAdapt qualifies it.", allow_abbrev=False, ) - ap.add_argument("--describe", default="none", - help="OpenAPI, GraphQL or FHIR CapabilityStatement file; 'db' for the sandbox's database schema; or 'none'") - ap.add_argument("--trace", required=True, help="HAR file of one correct demonstration") - ap.add_argument("--task", required=True, help="task.yaml: instruction and the demonstration's params") - ap.add_argument("--sandbox", required=True, help="sandbox.yaml (openadapt.verify-sandbox/v1)") + ap.add_argument( + "--describe", + default="none", + help="OpenAPI, GraphQL or FHIR CapabilityStatement file; 'db' for the sandbox's database schema; or 'none'", + ) + ap.add_argument( + "--trace", required=True, help="HAR file of one correct demonstration" + ) + ap.add_argument( + "--task", + required=True, + help="task.yaml: instruction and the demonstration's params", + ) + ap.add_argument( + "--sandbox", required=True, help="sandbox.yaml (openadapt.verify-sandbox/v1)" + ) ap.add_argument("--out", required=True, help="output folder") - ap.add_argument("--rounds", type=int, default=MAX_ROUNDS, choices=range(1, MAX_ROUNDS + 1)) - ap.add_argument("--answers", help="answers to the one question (table.column: bookkeeping|business)") + ap.add_argument( + "--rounds", type=int, default=MAX_ROUNDS, choices=range(1, MAX_ROUNDS + 1) + ) + ap.add_argument( + "--answers", + help="answers to the one question (table.column: bookkeeping|business)", + ) ap.add_argument("--no-input", action="store_true", help="never ask; refuse instead") - ap.add_argument("--spend-ledger", default=str(Path.home() / ".openadapt" / "verify-draft" / "spend.jsonl")) + ap.add_argument( + "--spend-ledger", + default=str(Path.home() / ".openadapt" / "verify-draft" / "spend.jsonl"), + ) ap.add_argument("--spend-cap-usd", type=float, default=30.0) - ap.add_argument("--check", metavar="CONTRACT", help="only check that CONTRACT is still the admitted check") + ap.add_argument( + "--check", + metavar="CONTRACT", + help="only check that CONTRACT is still the admitted check", + ) args = ap.parse_args(argv) if args.check: problem = admission_problem(args.check) diff --git a/packages/flow/openadapt_flow/verify_draft/inputs.py b/packages/flow/openadapt_flow/verify_draft/inputs.py index 160c26a041..3273979707 100644 --- a/packages/flow/openadapt_flow/verify_draft/inputs.py +++ b/packages/flow/openadapt_flow/verify_draft/inputs.py @@ -26,7 +26,14 @@ MAX_DESCRIPTION_CHARS = 40_000 _SECRET = re.compile(r"pass(word)?|secret|token|api[-_]?key|session|csrf|auth", re.I) _SECRET_HEADERS = frozenset( - {"authorization", "cookie", "set-cookie", "x-api-key", "x-csrf-token", "proxy-authorization"} + { + "authorization", + "cookie", + "set-cookie", + "x-api-key", + "x-csrf-token", + "proxy-authorization", + } ) _READS = frozenset({"GET", "HEAD", "OPTIONS"}) @@ -96,8 +103,12 @@ def load_description(source: Optional[str], *, schema_text: str = "") -> Descrip return Description("openapi", _openapi(doc), path.name) if isinstance(doc, dict) and doc.get("resourceType") == "CapabilityStatement": return Description("fhir", _fhir(doc), path.name) - if isinstance(doc, dict) and ("__schema" in doc or "__schema" in (doc.get("data") or {})): - return Description("graphql", _graphql(doc.get("data", doc)["__schema"]), path.name) + if isinstance(doc, dict) and ( + "__schema" in doc or "__schema" in (doc.get("data") or {}) + ): + return Description( + "graphql", _graphql(doc.get("data", doc)["__schema"]), path.name + ) if isinstance(doc, str) and re.search(r"\b(type|schema|input)\s+\w+\s*\{", doc): return Description("graphql", doc[:MAX_DESCRIPTION_CHARS], path.name) raise InputError( @@ -119,23 +130,35 @@ def _ref(schema: Any) -> str: def _openapi(doc: dict) -> str: - lines = [f"# {doc.get('info', {}).get('title', 'API')} {doc.get('info', {}).get('version', '')}"] + lines = [ + f"# {doc.get('info', {}).get('title', 'API')} {doc.get('info', {}).get('version', '')}" + ] for path, ops in (doc.get("paths") or {}).items(): for method, op in (ops or {}).items(): - if not isinstance(op, dict) or method.startswith("x-") or method == "parameters": + if ( + not isinstance(op, dict) + or method.startswith("x-") + or method == "parameters" + ): continue body = "" - content = ((op.get("requestBody") or {}).get("content") or {}) + content = (op.get("requestBody") or {}).get("content") or {} for mime, media in content.items(): body = f" body={_ref(media.get('schema'))} ({mime})" break - params = ",".join(p.get("name", "") for p in op.get("parameters") or [] if isinstance(p, dict)) + params = ",".join( + p.get("name", "") + for p in op.get("parameters") or [] + if isinstance(p, dict) + ) lines.append( f"{method.upper()} {path}{body}" + (f" params={params}" if params else "") + (f" -- {op.get('summary')}" if op.get("summary") else "") ) - schemas = (doc.get("components") or {}).get("schemas") or doc.get("definitions") or {} + schemas = ( + (doc.get("components") or {}).get("schemas") or doc.get("definitions") or {} + ) lines.append("# schemas") for name, schema in schemas.items(): props = (schema or {}).get("properties") or {} @@ -150,7 +173,9 @@ def _fhir(doc: dict) -> str: for res in rest.get("resource") or []: inter = ",".join(i.get("code", "") for i in res.get("interaction") or []) search = ",".join(s.get("name", "") for s in res.get("searchParam") or []) - lines.append(f"{res.get('type')}: {inter}" + (f" search={search}" if search else "")) + lines.append( + f"{res.get('type')}: {inter}" + (f" search={search}" if search else "") + ) return "\n".join(lines)[:MAX_DESCRIPTION_CHARS] @@ -159,7 +184,9 @@ def _graphql(schema: dict) -> str: for t in schema.get("types") or []: if str(t.get("name", "")).startswith("__"): continue - fields = ", ".join(f.get("name", "") for f in t.get("fields") or [] if isinstance(f, dict)) + fields = ", ".join( + f.get("name", "") for f in t.get("fields") or [] if isinstance(f, dict) + ) if fields: lines.append(f"{t.get('kind', '').lower()} {t['name']} {{{fields}}}") return "\n".join(lines)[:MAX_DESCRIPTION_CHARS] @@ -190,7 +217,9 @@ def load_trace(path: str | Path) -> list[Request]: Request( method=str(req.get("method", "GET")).upper(), url=str(req.get("url", "")), - headers={h["name"]: h.get("value", "") for h in req.get("headers") or []}, + headers={ + h["name"]: h.get("value", "") for h in req.get("headers") or [] + }, body=body, mime=str(post.get("mimeType") or ""), status=res.get("status"), @@ -200,7 +229,9 @@ def load_trace(path: str | Path) -> list[Request]: return out -def writes(trace: list[Request], *, skip_paths: set[str] = frozenset()) -> list[Request]: # type: ignore[assignment] +def writes( + trace: list[Request], *, skip_paths: set[str] = frozenset() +) -> list[Request]: # type: ignore[assignment] """The trace's write requests (anything but GET, HEAD and OPTIONS), without sign-in requests.""" @@ -210,7 +241,11 @@ def writes(trace: list[Request], *, skip_paths: set[str] = frozenset()) -> list[ def _mask_json(value: Any) -> Any: if isinstance(value, dict): return { - k: ("***" if _SECRET.search(str(k)) and not isinstance(v, (dict, list)) else _mask_json(v)) + k: ( + "***" + if _SECRET.search(str(k)) and not isinstance(v, (dict, list)) + else _mask_json(v) + ) for k, v in value.items() } if isinstance(value, list): @@ -230,7 +265,10 @@ def _mask_body(body: Optional[str], mime: str) -> Optional[str]: from urllib.parse import parse_qsl, urlencode return urlencode( - [(k, "***" if _SECRET.search(k) else v) for k, v in parse_qsl(body, keep_blank_values=True)] + [ + (k, "***" if _SECRET.search(k) else v) + for k, v in parse_qsl(body, keep_blank_values=True) + ] ) return body[:2000] @@ -243,16 +281,23 @@ def masked(req: Request, *, response_chars: int = 1500) -> dict[str, Any]: parts = urlsplit(req.url) query = urlencode( - [(k, "***" if _SECRET.search(k) else v) for k, v in parse_qsl(parts.query, keep_blank_values=True)] + [ + (k, "***" if _SECRET.search(k) else v) + for k, v in parse_qsl(parts.query, keep_blank_values=True) + ] ) response = req.response if response is not None: - response = _mask_body(response, "json" if response.lstrip()[:1] in "{[" else "text") + response = _mask_body( + response, "json" if response.lstrip()[:1] in "{[" else "text" + ) return { "method": req.method, "url": urlunsplit(("", "", parts.path, query, "")), "headers": { - k: v for k, v in req.headers.items() if k.lower() not in _SECRET_HEADERS and not _SECRET.search(k) + k: v + for k, v in req.headers.items() + if k.lower() not in _SECRET_HEADERS and not _SECRET.search(k) }, "body": _mask_body(req.body, req.mime), "status": req.status, diff --git a/packages/flow/openadapt_flow/verify_draft/model.py b/packages/flow/openadapt_flow/verify_draft/model.py index f34cd57353..270cdf4729 100644 --- a/packages/flow/openadapt_flow/verify_draft/model.py +++ b/packages/flow/openadapt_flow/verify_draft/model.py @@ -136,7 +136,10 @@ "type": "array", "items": { "type": "object", - "properties": {"param": {"type": "string"}, "value": {"type": "string"}}, + "properties": { + "param": {"type": "string"}, + "value": {"type": "string"}, + }, "required": ["param", "value"], "additionalProperties": False, }, @@ -268,7 +271,13 @@ def draft(self, messages: list[dict[str, Any]]) -> Draft: with self.client.messages.stream( model=MODEL, max_tokens=MAX_TOKENS, - system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}], + system=[ + { + "type": "text", + "text": SYSTEM_PROMPT, + "cache_control": {"type": "ephemeral"}, + } + ], messages=messages, output_config={ "effort": EFFORT, @@ -281,8 +290,12 @@ def draft(self, messages: list[dict[str, Any]]) -> Draft: response_model=str(getattr(response, "model", "")), input_tokens=int(response.usage.input_tokens or 0), output_tokens=int(response.usage.output_tokens or 0), - cache_read_tokens=int(getattr(response.usage, "cache_read_input_tokens", 0) or 0), - cache_write_tokens=int(getattr(response.usage, "cache_creation_input_tokens", 0) or 0), + cache_read_tokens=int( + getattr(response.usage, "cache_read_input_tokens", 0) or 0 + ), + cache_write_tokens=int( + getattr(response.usage, "cache_creation_input_tokens", 0) or 0 + ), usd=round(cost(response.usage), 6), seconds=round(time.monotonic() - started, 2), request_id=str(getattr(response, "_request_id", "") or ""), @@ -291,7 +304,9 @@ def draft(self, messages: list[dict[str, Any]]) -> Draft: self.ledger.add(call, self.label) if response.stop_reason == "refusal": return Draft("", [], "the model declined to draft", call) - raw = "".join(b.text for b in response.content if getattr(b, "type", "") == "text") + raw = "".join( + b.text for b in response.content if getattr(b, "type", "") == "text" + ) return parse_answer(raw, call) @@ -309,5 +324,13 @@ def parse_answer(raw: str, call: Optional[Call] = None) -> Draft: if isinstance(p, dict): payloads.append(p) elif isinstance(p, list): - payloads.append({str(i.get("param")): i.get("value") for i in p if isinstance(i, dict)}) - return Draft(str(data.get("contract_yaml") or ""), payloads, str(data.get("notes") or ""), call, raw) + payloads.append( + {str(i.get("param")): i.get("value") for i in p if isinstance(i, dict)} + ) + return Draft( + str(data.get("contract_yaml") or ""), + payloads, + str(data.get("notes") or ""), + call, + raw, + ) diff --git a/packages/flow/openadapt_flow/verify_draft/sandbox.py b/packages/flow/openadapt_flow/verify_draft/sandbox.py index 4c35808866..80be0a5d63 100644 --- a/packages/flow/openadapt_flow/verify_draft/sandbox.py +++ b/packages/flow/openadapt_flow/verify_draft/sandbox.py @@ -391,14 +391,70 @@ def _exec(self, statements: Sequence[tuple[str, Sequence[Any]]]) -> list[Any]: finally: con.close() + def digests(self) -> dict[str, str]: + """One digest per table, computed in the database where it can be, + so finding what moved doesn't read every row.""" + + if self.dialect == "sqlite": + return {name: _digest_rows(rows) for name, rows in self.read().items()} + con = self._con() + try: + cur = con.cursor() + if self.dialect == "postgresql": + parts = [ + f"SELECT {i} AS n, md5(coalesce(string_agg(md5(t::text), '' " + f"ORDER BY md5(t::text)), '')) FROM {self.q(name)} t" + for i, name in enumerate(self.tables) + ] + cur.execute(" UNION ALL ".join(parts)) + names = list(self.tables) + out = {names[int(n)]: str(d) for n, d in cur.fetchall()} + else: + cur.execute( + "CHECKSUM TABLE " + ", ".join(self.q(n) for n in self.tables) + ) + found = {str(r[0]).split(".", 1)[-1]: str(r[1]) for r in cur.fetchall()} + out = {n: found.get(n, "") for n in self.tables} + con.rollback() + return out + finally: + con.close() + + def remember(self, base: Rows) -> None: + """Remember ``base`` (a full read) and its digests, so restoring it + and reading what moved since touch only the tables that moved.""" + + self._marked = (base, self.digests()) + + def _moved_tables(self, snapshot: Rows) -> Optional[list[str]]: + marked = getattr(self, "_marked", None) + if marked is None or marked[0] is not snapshot: + return None + now = self.digests() + return [t for t, d in marked[1].items() if now.get(t) != d] + + def read_moved(self, base: Rows) -> Rows: + """A full read, fetching only the tables that moved since ``base`` + (when ``base`` is the marked read).""" + + moved = self._moved_tables(base) + if moved is None: + return self.read() + out = dict(base) + out.update(self.read(moved)) + return out + def restore(self, snapshot: Rows) -> int: """Put every table that differs from ``snapshot`` back. Returns how many tables were rewritten.""" - now = self.read() + moved = self._moved_tables(snapshot) + now = self.read(moved) if moved is not None else self.read() statements: list[tuple[str, Sequence[Any]]] = [] changed = 0 for name, rows in snapshot.items(): + if moved is not None and name not in moved: + continue if _digest_rows(now.get(name, {})) == _digest_rows(rows): continue changed += 1 @@ -434,7 +490,12 @@ def insert(self, table: str, row: Mapping[str, Any]) -> None: cols = ", ".join(self.q(c) for c in row) marks = ", ".join([self.mark] * len(row)) self._exec( - [(f"INSERT INTO {self.q(table)} ({cols}) VALUES ({marks})", list(row.values()))] + [ + ( + f"INSERT INTO {self.q(table)} ({cols}) VALUES ({marks})", + list(row.values()), + ) + ] ) def delete(self, table: str, key: tuple) -> None: @@ -451,7 +512,14 @@ def new_key_row(self, table: str, row: Row, existing: Rows) -> Row: out = dict(row) taken = existing.get(table, {}) for c in t.pk: - out[c] = _fresh(row[c], [k[t.pk.index(c)] for k in taken if isinstance(k, tuple) and len(k) == len(t.pk)]) + out[c] = _fresh( + row[c], + [ + k[t.pk.index(c)] + for k in taken + if isinstance(k, tuple) and len(k) == len(t.pk) + ], + ) for cols in t.unique: if any(out.get(c) is None for c in cols): continue @@ -475,7 +543,9 @@ def _fresh(value: Any, taken: Sequence[Any]) -> Any: except ValueError: pass if value.isdigit(): - return str(max([int(v) for v in taken if str(v).isdigit()] + [int(value)]) + 1000) + return str( + max([int(v) for v in taken if str(v).isdigit()] + [int(value)]) + 1000 + ) return value + "-copy" return value @@ -497,7 +567,9 @@ def _canon(value: Any) -> Any: return json.dumps([_canon(v) for v in value]) if isinstance(value, (bytes, memoryview)): return base64.b64encode(bytes(value)).decode() - if isinstance(value, (_dt.date, _dt.datetime, _dt.time, decimal.Decimal, uuid.UUID)): + if isinstance( + value, (_dt.date, _dt.datetime, _dt.time, decimal.Decimal, uuid.UUID) + ): return str(value) return value @@ -601,7 +673,9 @@ def session(self, actor: str) -> Any: if login.token_field: token = (r.json() or {}).get(login.token_field) if not token: - raise SandboxError(f"sign-in for {actor} returned no {login.token_field}") + raise SandboxError( + f"sign-in for {actor} returned no {login.token_field}" + ) s.headers["Authorization"] = f"Bearer {token}" self._sessions[actor] = s return s @@ -625,11 +699,16 @@ def send( parts = urlsplit(req.url) path = _swap_path(parts.path, swap) query = urlencode( - [(k, _swap_text(v, swap)) for k, v in parse_qsl(parts.query, keep_blank_values=True)] + [ + (k, _swap_text(v, swap)) + for k, v in parse_qsl(parts.query, keep_blank_values=True) + ] ) url = urlunsplit((base.scheme, base.netloc, path, query, "")) headers = { - k: v for k, v in req.headers.items() if k.lower() not in _DROP_HEADERS + k: v + for k, v in req.headers.items() + if k.lower() not in _DROP_HEADERS } body = _swap_body(req.body, req.mime, swap) r = s.request( @@ -650,7 +729,8 @@ def _swap_text(value: str, swap: Mapping[str, Any]) -> str: def _swap_path(path: str, swap: Mapping[str, Any]) -> str: return "/".join( - quote(str(swap[seg]), safe="") if seg in swap else seg for seg in path.split("/") + quote(str(swap[seg]), safe="") if seg in swap else seg + for seg in path.split("/") ) @@ -673,7 +753,9 @@ def _swap_json(value: Any, swap: Mapping[str, Any]) -> Any: return value -def _swap_body(body: Optional[str], mime: str, swap: Mapping[str, Any]) -> Optional[str]: +def _swap_body( + body: Optional[str], mime: str, swap: Mapping[str, Any] +) -> Optional[str]: if body is None or not swap: return body if "json" in mime: @@ -683,7 +765,10 @@ def _swap_body(body: Optional[str], mime: str, swap: Mapping[str, Any]) -> Optio return body if "x-www-form-urlencoded" in mime: return urlencode( - [(k, _swap_text(v, swap)) for k, v in parse_qsl(body, keep_blank_values=True)] + [ + (k, _swap_text(v, swap)) + for k, v in parse_qsl(body, keep_blank_values=True) + ] ) return body diff --git a/packages/flow/tests/test_verify_draft.py b/packages/flow/tests/test_verify_draft.py index f16274b83c..5a5abcd8df 100644 --- a/packages/flow/tests/test_verify_draft.py +++ b/packages/flow/tests/test_verify_draft.py @@ -57,12 +57,22 @@ #: Matches the loan only (the other columns are waved through as fields a #: new row may set), and schedules no recheck. WEAK = ( - GOOD.replace(" product: {param: product}\n amount: {param: amount}\n memo: {param: memo}\n", "") + GOOD.replace( + " product: {param: product}\n amount: {param: amount}\n memo: {param: memo}\n", + "", + ) .replace(" recheck_after_s: 300\n", "") - .replace("[id, source, record_key, surface]", "[id, source, record_key, surface, product, amount, memo]") + .replace( + "[id, source, record_key, surface]", + "[id, source, record_key, surface, product, amount, memo]", + ) ) PAYLOADS = [ - {"amount": f"{1000 + i * 111}.00", "memo": f"Probe memo {i}", "product": ["Auto", "Home", "Personal"][i % 3]} + { + "amount": f"{1000 + i * 111}.00", + "memo": f"Probe memo {i}", + "product": ["Auto", "Home", "Personal"][i % 3], + } for i in range(8) ] @@ -88,10 +98,19 @@ def mockloan(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: url, db, stop = fault_server.serve(0) base = url.rstrip("/") for loan, prod, amt in [("LN-1", "Auto", "10.00"), ("LN-2", "Home", "20.00")]: - requests.post(base + "/api/disbursement", json={"loan_id": loan, "product": prod, "amount": amt, "memo": "seed"}, timeout=10) + requests.post( + base + "/api/disbursement", + json={"loan_id": loan, "product": prod, "amount": amt, "memo": "seed"}, + timeout=10, + ) seeded = tmp_path / "seeded.sqlite3" shutil.copy(db.database_path, seeded) - params = {"loan_id": "LN-9", "product": "Personal", "amount": "31.50", "memo": "Kitchen"} + params = { + "loan_id": "LN-9", + "product": "Personal", + "amount": "31.50", + "memo": "Kitchen", + } trace = { "log": { "entries": [ @@ -99,9 +118,17 @@ def mockloan(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: "request": { "method": "POST", "url": base + "/api/disbursement", - "headers": [{"name": "Content-Type", "value": "application/json"}, - {"name": "Authorization", "value": "Bearer secret-demo-token"}], - "postData": {"mimeType": "application/json", "text": json.dumps({**params, "password": "hunter2"})}, + "headers": [ + {"name": "Content-Type", "value": "application/json"}, + { + "name": "Authorization", + "value": "Bearer secret-demo-token", + }, + ], + "postData": { + "mimeType": "application/json", + "text": json.dumps({**params, "password": "hunter2"}), + }, }, "response": {"status": 200, "content": {"text": "{}"}}, } @@ -109,15 +136,20 @@ def mockloan(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: } } (tmp_path / "trace.har").write_text(json.dumps(trace)) - (tmp_path / "task.yaml").write_text(yaml.safe_dump({"instruction": "Book it.", "params": params})) + (tmp_path / "task.yaml").write_text( + yaml.safe_dump({"instruction": "Book it.", "params": params}) + ) (tmp_path / "sandbox.yaml").write_text( yaml.safe_dump( { "schema_version": "openadapt.verify-sandbox/v1", "app": {"base_url": base}, "actors": {"agent": {"id": "a1"}, "other": {"id": "b2"}}, - "store": {"dialect": "sqlite", "read": {"sqlite_database": str(db.database_path)}, - "admin": {"sqlite_database": str(db.database_path)}}, + "store": { + "dialect": "sqlite", + "read": {"sqlite_database": str(db.database_path)}, + "admin": {"sqlite_database": str(db.database_path)}, + }, } ) ) @@ -148,7 +180,7 @@ def test_good_draft_is_admitted_and_bound(mockloan: Path) -> None: assert {"wrong_row", "duplicate", "sibling_edit", "late_revert"} <= names assert any(n.startswith("wrong_value:") for n in names) assert sum(c.passed for c in adm.cases if c.group == "clean") == A.CLEAN_PROBES - assert sum(c.passed for c in adm.cases if c.group == "probe") == 4 + assert sum(c.passed for c in adm.cases if c.group == "probe") == 5 path = outcome.contract_path assert path is not None and D.admission_problem(path) is None prov = yaml.safe_load(path.read_text())["provenance"] @@ -180,8 +212,14 @@ def test_weak_draft_is_refused_with_reasons_fed_back(mockloan: Path) -> None: def test_rounds_stop_at_three_and_unsafe_drafts_never_run(mockloan: Path) -> None: - unsafe = GOOD.replace(" kind: surfaces\n", " kind: surfaces\n session: my.hooks:login\n") - drafter = Fixed(unsafe, "not: [valid", GOOD.replace("FROM records", "FROM records; DELETE FROM records")) + unsafe = GOOD.replace( + " kind: surfaces\n", " kind: surfaces\n session: my.hooks:login\n" + ) + drafter = Fixed( + unsafe, + "not: [valid", + GOOD.replace("FROM records", "FROM records; DELETE FROM records"), + ) outcome = _run(mockloan, drafter, rounds=3) assert not outcome.admitted assert len(drafter.seen) == 3 and outcome.rounds == 3 @@ -191,7 +229,20 @@ def test_rounds_stop_at_three_and_unsafe_drafts_never_run(mockloan: Path) -> Non def test_rounds_are_capped() -> None: with pytest.raises(SystemExit): - D.main(["--trace", "t", "--task", "t", "--sandbox", "s", "--out", "o", "--rounds", "4"]) + D.main( + [ + "--trace", + "t", + "--task", + "t", + "--sandbox", + "s", + "--out", + "o", + "--rounds", + "4", + ] + ) def test_attribution_flags_masks(tmp_path: Path) -> None: @@ -199,8 +250,11 @@ def test_attribution_flags_masks(tmp_path: Path) -> None: assert A._cause(seen, ["agent", "other"]) == "payload" seen = {("agent", 0): "7", ("agent", 1): "7", ("other", 0): "9", ("other", 1): "9"} assert A._cause(seen, ["agent", "other"]) == "actor" - clock = {k: f"2026-11-21 07:0{i}:00" for i, k in enumerate(seen)} + clock = {k: f"2026-11-21 07:0{i}:00" for i, k in enumerate([*seen, ("agent", 2)])} assert A._cause(clock, ["agent", "other"]) == "clock" + # A new id on every write: it differs between two identical writes. + fresh = {**{k: str(i) for i, k in enumerate(seen)}, ("agent", 2): "99"} + assert A._cause(fresh, ["agent", "other"]) == "fresh" def test_spend_ledger_refuses_past_the_cap(tmp_path: Path) -> None: @@ -211,21 +265,67 @@ def test_spend_ledger_refuses_past_the_cap(tmp_path: Path) -> None: def test_descriptions_and_masking(tmp_path: Path) -> None: - api = {"openapi": "3.1.0", "info": {"title": "T", "version": "1"}, - "paths": {"/r/{slug}": {"patch": {"summary": "Update", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/R"}}}}}}}, - "components": {"schemas": {"R": {"properties": {"name": {"type": "string"}}}}}} + api = { + "openapi": "3.1.0", + "info": {"title": "T", "version": "1"}, + "paths": { + "/r/{slug}": { + "patch": { + "summary": "Update", + "requestBody": { + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/R"} + } + } + }, + } + } + }, + "components": {"schemas": {"R": {"properties": {"name": {"type": "string"}}}}}, + } (tmp_path / "api.json").write_text(json.dumps(api)) d = I.load_description(str(tmp_path / "api.json")) - assert d.kind == "openapi" and "PATCH /r/{slug} body=R" in d.text and "R{name:string}" in d.text - (tmp_path / "cap.json").write_text(json.dumps({"resourceType": "CapabilityStatement", "rest": [{"resource": [{"type": "Patient", "interaction": [{"code": "update"}]}]}]})) - assert I.load_description(str(tmp_path / "cap.json")).text.endswith("Patient: update") - (tmp_path / "s.graphql").write_text("type Query { a: Int }\ntype Task { id: ID title: String }") + assert ( + d.kind == "openapi" + and "PATCH /r/{slug} body=R" in d.text + and "R{name:string}" in d.text + ) + (tmp_path / "cap.json").write_text( + json.dumps( + { + "resourceType": "CapabilityStatement", + "rest": [ + { + "resource": [ + {"type": "Patient", "interaction": [{"code": "update"}]} + ] + } + ], + } + ) + ) + assert I.load_description(str(tmp_path / "cap.json")).text.endswith( + "Patient: update" + ) + (tmp_path / "s.graphql").write_text( + "type Query { a: Int }\ntype Task { id: ID title: String }" + ) assert I.load_description(str(tmp_path / "s.graphql")).kind == "graphql" assert I.load_description("none").kind == "none" - req = I.Request("POST", "http://x/a?token=t1&q=1", {"Cookie": "c", "X-Api-Key": "k", "Accept": "*/*"}, - "username=u&password=p", "application/x-www-form-urlencoded") + req = I.Request( + "POST", + "http://x/a?token=t1&q=1", + {"Cookie": "c", "X-Api-Key": "k", "Accept": "*/*"}, + "username=u&password=p", + "application/x-www-form-urlencoded", + ) m = I.masked(req) - assert "t1" not in m["url"] and "Cookie" not in m["headers"] and "X-Api-Key" not in m["headers"] + assert ( + "t1" not in m["url"] + and "Cookie" not in m["headers"] + and "X-Api-Key" not in m["headers"] + ) assert "password=%2A%2A%2A" in m["body"] and "username=u" in m["body"] @@ -249,7 +349,16 @@ def test_run_path_makes_no_model_calls(mockloan: Path) -> None: print(r.outcome.value) """ ) - out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120, - env={"OPENADAPT_LOCAL_SEAL": "off", "PATH": "/usr/bin:/bin", "HOME": str(mockloan)}) + out = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True, + timeout=120, + env={ + "OPENADAPT_LOCAL_SEAL": "off", + "PATH": "/usr/bin:/bin", + "HOME": str(mockloan), + }, + ) assert out.returncode == 0, out.stderr assert out.stdout.strip() in ("REFUTED", "UNCERTAIN") # no new record was written From afc9d3862f6bc4b7fbefa998f7f7a40833907657 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:26:11 -0500 Subject: [PATCH 03/14] feat(verify): verify draft drafts as JSON (prompt v2), allowlists drafts, marks unbuildable cases untestable; protocol addendum before Directus --- .../flow/benchmark/verify_draft/PROTOCOL.md | 56 +++- packages/flow/benchmark/verify_draft/apps.py | 254 ++++++++++++++++- .../verify_draft/results/{ => v1}/mealie.log | 0 .../results/{ => v1}/mealie/draft/report.json | 0 .../{ => v1}/mealie/draft/rounds/round-1.yaml | 0 .../draft/rounds/round-2.admission.json | 0 .../{ => v1}/mealie/draft/rounds/round-2.yaml | 0 .../draft/rounds/round-3.admission.json | 0 .../{ => v1}/mealie/draft/rounds/round-3.yaml | 0 .../results/{ => v1}/mealie/result.json | 0 .../{ => v1}/mealie/setup/sandbox.yaml | 0 .../results/{ => v1}/mealie/setup/task.yaml | 0 .../results/{ => v1}/mealie/setup/trace.har | 0 .../results/{ => v1}/mockloan.log | 0 .../{ => v1}/mockloan/draft/contract.yaml | 0 .../{ => v1}/mockloan/draft/report.json | 0 .../draft/rounds/round-1.admission.json | 0 .../mockloan/draft/rounds/round-1.yaml | 0 .../results/{ => v1}/mockloan/result.json | 0 .../{ => v1}/mockloan/setup/sandbox.yaml | 0 .../results/{ => v1}/mockloan/setup/task.yaml | 0 .../results/{ => v1}/mockloan/setup/trace.har | 0 .../results/{ => v1}/workbench.log | 0 .../{ => v1}/workbench/draft/contract.yaml | 0 .../{ => v1}/workbench/draft/report.json | 0 .../draft/rounds/round-1.admission.json | 0 .../workbench/draft/rounds/round-1.yaml | 0 .../results/{ => v1}/workbench/result.json | 0 .../{ => v1}/workbench/setup/sandbox.yaml | 0 .../{ => v1}/workbench/setup/task.yaml | 0 .../{ => v1}/workbench/setup/trace.har | 0 packages/flow/benchmark/verify_draft/run.py | 2 +- packages/flow/docs/VERIFY_DRAFT.md | 20 +- .../flow/openadapt_flow/verify_draft/admit.py | 267 +++++++++++++----- .../flow/openadapt_flow/verify_draft/draft.py | 7 + .../openadapt_flow/verify_draft/inputs.py | 5 +- .../flow/openadapt_flow/verify_draft/model.py | 32 ++- .../openadapt_flow/verify_draft/sandbox.py | 31 +- packages/flow/tests/test_verify_draft.py | 81 ++++++ 39 files changed, 650 insertions(+), 105 deletions(-) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie.log (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/draft/report.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/draft/rounds/round-1.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/draft/rounds/round-2.admission.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/draft/rounds/round-2.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/draft/rounds/round-3.admission.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/draft/rounds/round-3.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/result.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/setup/sandbox.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/setup/task.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mealie/setup/trace.har (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan.log (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/draft/contract.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/draft/report.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/draft/rounds/round-1.admission.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/draft/rounds/round-1.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/result.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/setup/sandbox.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/setup/task.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/mockloan/setup/trace.har (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench.log (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/draft/contract.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/draft/report.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/draft/rounds/round-1.admission.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/draft/rounds/round-1.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/result.json (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/setup/sandbox.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/setup/task.yaml (100%) rename packages/flow/benchmark/verify_draft/results/{ => v1}/workbench/setup/trace.har (100%) diff --git a/packages/flow/benchmark/verify_draft/PROTOCOL.md b/packages/flow/benchmark/verify_draft/PROTOCOL.md index 9b643e23a5..b9ad783332 100644 --- a/packages/flow/benchmark/verify_draft/PROTOCOL.md +++ b/packages/flow/benchmark/verify_draft/PROTOCOL.md @@ -1,7 +1,8 @@ # Protocol: model-drafted write contracts, admitted by qualification -Written before the reported runs. Changes after a run go under -"Deviations" in [RESULTS.md](RESULTS.md), with the run they affect. +Written on 2026-11-21 after the first two Mealie runs and before the +second untuned app (Directus) was touched. What changed and when is under +"Addendum" below; every run, void or not, is in [RESULTS.md](RESULTS.md). ## Question @@ -10,9 +11,9 @@ description and one trace, so that setup takes minutes instead of about an hour? And does admission by qualification keep every admitted contract honest: no planted fault missed, no false stop on a clean write? -The baseline is the Vikunja setup in the second first-contact retest: 64.5 -minutes and 12 person decisions with the deterministic generator and hand -patches. +The baseline is an earlier setup of a held-out app with the deterministic +generator and hand patches: 64.5 minutes and 12 person decisions (private +study). ## Apps @@ -20,9 +21,10 @@ patches. |---|---|---|---|---| | MockLoan (OpenAdapt's fault server) | SQLite | create a disbursement (JSON POST) | `db` | yes (zero-config benchmark) | | Workbench, MockMed profile (OpenAdapt's task-generation app) | PostgreSQL | update a patient's phone and email (HTML form) | `db` | yes | -| Mealie v2.8.0 | PostgreSQL | update a recipe's description and yield (JSON PATCH) | OpenAPI (`/openapi.json`) | no: no agent had installed or probed it | +| Mealie v2.8.0 | PostgreSQL | update a recipe's description and yield (JSON PATCH) | OpenAPI (`/openapi.json`) | no agent had installed or probed it before this benchmark; tuned on by this benchmark after its first valid run | +| Directus 11.5.1 | PostgreSQL | update a ticket's status and priority (JSON PATCH) | OpenAPI (`/server/specs/oas`) | no: never installed or probed before its reported run | -Mealie runs on the lab's WSL host (PostgreSQL 16.4, both pinned images), +Mealie and Directus run on the lab's WSL host (PostgreSQL 16.4, pinned images), reached from the Mac through an SSH tunnel to loopback. All data is synthetic. @@ -49,7 +51,7 @@ synthetic. - **Setup minutes**: wall time of step 2, from the command's start to the admitted contract or the refusal. - **Person decisions**: answers to the command's question. As in the - Vikunja log, the facts in `sandbox.yaml` are listed as operator inputs, + earlier setup log, the facts in `sandbox.yaml` are listed as operator inputs, not decisions. - **Admitted versus rejected drafts**: one draft per model round. - **Planted-fault catches**: refuted faults over applicable faults, in the @@ -74,3 +76,41 @@ scored on the held-out faults as well. USD 30 in all, enforced by the ledger. A call is refused when the total plus the worst case of one call would pass it. + +## Addendum, 2026-11-21, before Directus + +Written after the Mealie runs and before any draft was run on Directus. The +only Directus contact before this addendum was the operator setup dry run +(start the stack, create the collection, the second user and three +tickets). + +- **Why a second untuned app.** On Mealie no draft passed the lost-update + case, and the store seems to keep nothing that could show one: no version, + no author and no save history. So Mealie can't separate "the approach + fails" from "this store can't show a lost update". Directus was picked by + one constraint: its store records each save with its author + (`directus_revisions` and `directus_activity`), and two users can sign in. + The blind trial reserves OpenProject, Taiga and BookStack, so they were + avoided. +- **Changes since the first valid Mealie run.** These were made in response + to Mealie, so Mealie no longer counts as untuned: + - the attribution probe repeats the first write, to tell a new id or a + clock from a value; + - a lower-cased copy of a value counts as written only for an email + address; + - only the tables that moved are re-read; + - a round stops at a clean write that isn't confirmed; + - a case the sandbox can't build (no second user, no other record) is + untestable: never a pass, and an operator fix; + - the draft filter is an allowlist (SQL reads only, no `${...}`); + - prompt `verify-draft-prompt/2` asks for the contract as JSON text, + because YAML with unquoted colons cost a round in two Mealie runs; + - the workbench gets a second session as its second actor; + - a parameter whose demonstrated value another parameter shares is not + varied (it can't be swapped in the trace alone); + - a sign-in token can be read from a nested reply field + (`data.access_token`). +- **Frozen.** The code and prompt for the Directus run are the commit that + adds this addendum. The tuned apps are rerun on the same commit. The + first valid Directus run is the reported number. Only an operator setup + error voids a run. diff --git a/packages/flow/benchmark/verify_draft/apps.py b/packages/flow/benchmark/verify_draft/apps.py index 1d383759f4..09dcb9f69c 100644 --- a/packages/flow/benchmark/verify_draft/apps.py +++ b/packages/flow/benchmark/verify_draft/apps.py @@ -305,7 +305,18 @@ def _workbench( "path": "/login", "form": {"username": "clinician", "password": "synthetic"}, }, - } + }, + # The workbench signs in one user, so the second actor is a + # second session of it: enough for a lost update, not for an + # actor axis. + "other": { + "id": "clinician", + "login": { + "method": "POST", + "path": "/login", + "form": {"username": "clinician", "password": "synthetic"}, + }, + }, }, "store": { "dialect": "postgresql", @@ -356,7 +367,7 @@ def teardown() -> None: teardown=teardown, setup_seconds=round(time.monotonic() - started, 1), notes=[ - "the workbench signs in one user only: no second actor, so no lost-update case and no actor axis" + "the workbench signs in one user only: the second actor is a second session of it, so the lost-update case runs but the attribution probe has no real actor axis" ], ) @@ -578,3 +589,242 @@ def token(user: str, pw: str) -> dict[str, str]: "workbench": setup_workbench, "mealie": setup_mealie, } + + +# -- Directus (second untuned app, on the lab) ------------------------------------ + + +DIRECTUS = os.environ.get("VD_DIRECTUS_URL", "http://127.0.0.1:9664") +DIRECTUS_PG_PORT = int(os.environ.get("VD_DIRECTUS_PG_PORT", "9665")) + + +def setup_directus(work: Path) -> AppRun: + """Directus 11.5.1 must be up (fresh volume) at VD_DIRECTUS_URL with its + PostgreSQL at VD_DIRECTUS_PG_PORT (the lab stack, tunnelled to loopback). + The operator creates a ``tickets`` collection, a second user and three + tickets, then records one update.""" + + import psycopg2 + + started = time.monotonic() + work.mkdir(parents=True, exist_ok=True) + os.environ.setdefault("VD_DIRECTUS_PG_PW", "vd-synthetic-pg") + os.environ.setdefault("VD_DIRECTUS_READER_PW", "vd-synthetic-reader") + os.environ.setdefault("VD_DIRECTUS_ADMIN_PW", "vd-synthetic-admin") + os.environ.setdefault("VD_DIRECTUS_EDITOR_PW", "vd-synthetic-editor") + + def token(email: str, pw: str) -> dict[str, str]: + r = requests.post( + DIRECTUS + "/auth/login", json={"email": email, "password": pw}, timeout=30 + ) + r.raise_for_status() + return {"Authorization": "Bearer " + r.json()["data"]["access_token"]} + + admin = token("admin@example.org", os.environ["VD_DIRECTUS_ADMIN_PW"]) + if ( + requests.get( + DIRECTUS + "/collections/tickets", headers=admin, timeout=30 + ).status_code + != 200 + ): + r = requests.post( + DIRECTUS + "/collections", + headers=admin, + timeout=60, + json={ + "collection": "tickets", + "meta": {"accountability": "all"}, + "schema": {}, + "fields": [ + { + "field": "id", + "type": "integer", + "meta": {"hidden": True}, + "schema": {"is_primary_key": True, "has_auto_increment": True}, + }, + {"field": "title", "type": "string"}, + {"field": "status", "type": "string"}, + {"field": "priority", "type": "integer"}, + {"field": "note", "type": "text"}, + ], + }, + ) + r.raise_for_status() + me = requests.get(DIRECTUS + "/users/me", headers=admin, timeout=30).json()["data"] + users = requests.get( + DIRECTUS + "/users?filter[email][_eq]=editor@example.org", + headers=admin, + timeout=30, + ).json()["data"] + if users: + editor = users[0] + else: + r = requests.post( + DIRECTUS + "/users", + headers=admin, + timeout=30, + json={ + "email": "editor@example.org", + "password": os.environ["VD_DIRECTUS_EDITOR_PW"], + "role": me["role"], + "first_name": "Second", + "last_name": "Editor", + }, + ) + r.raise_for_status() + editor = r.json()["data"] + have = requests.get( + DIRECTUS + "/items/tickets?limit=-1", headers=admin, timeout=30 + ).json()["data"] + if not have: + r = requests.post( + DIRECTUS + "/items/tickets", + headers=admin, + timeout=30, + json=[ + { + "title": "Printer jams on tray 2", + "status": "open", + "priority": 1, + "note": "Seed one", + }, + { + "title": "VPN drops every hour", + "status": "open", + "priority": 1, + "note": "Seed two", + }, + { + "title": "Badge reader offline", + "status": "open", + "priority": 1, + "note": "Seed three", + }, + ], + ) + r.raise_for_status() + have = r.json()["data"] + ticket = str(have[1]["id"]) + other_ticket = str(have[2]["id"]) + con = psycopg2.connect( + host="127.0.0.1", + port=DIRECTUS_PG_PORT, + user="directus", + password=os.environ["VD_DIRECTUS_PG_PW"], + dbname="directus", + ) + con.autocommit = True + cur = con.cursor() + cur.execute("SELECT 1 FROM pg_roles WHERE rolname='vd_reader'") + if not cur.fetchone(): + cur.execute( + "CREATE ROLE vd_reader LOGIN PASSWORD %s", + (os.environ["VD_DIRECTUS_READER_PW"],), + ) + cur.execute("GRANT USAGE ON SCHEMA public TO vd_reader") + cur.execute("GRANT SELECT ON ALL TABLES IN SCHEMA public TO vd_reader") + cur.execute("GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO vd_reader") + con.close() + # The demonstration: one PATCH, recorded, then undone (through the app). + before = requests.get( + DIRECTUS + f"/items/tickets/{ticket}", headers=admin, timeout=30 + ).json()["data"] + params = {"ticket_id": ticket, "status": "in_progress", "priority": "3"} + rec = Recorder(admin) + rec.session.get(DIRECTUS + f"/items/tickets/{ticket}", timeout=30) + rec.session.patch( + DIRECTUS + f"/items/tickets/{ticket}", + json={"status": params["status"], "priority": 3}, + timeout=30, + ) + rec.save(work / "trace.har") + requests.patch( + DIRECTUS + f"/items/tickets/{ticket}", + headers=admin, + timeout=30, + json={"status": before["status"], "priority": before["priority"]}, + ) + (work / "openapi.json").write_text( + requests.get(DIRECTUS + "/server/specs/oas", headers=admin, timeout=60).text, + encoding="utf-8", + ) + task = _write( + work / "task.yaml", + { + "instruction": f"Set ticket {ticket} to status 'in_progress' with priority 3.", + "params": params, + }, + ) + pg = { + "sql_driver": "psycopg2", + "sql_connect_args": { + "host": "127.0.0.1", + "port": DIRECTUS_PG_PORT, + "dbname": "directus", + }, + } + + def login(email: str, env: str) -> dict[str, Any]: + return { + "method": "POST", + "path": "/auth/login", + "token_field": "data.access_token", + "json": {"email": email, "password": "${" + env + "}"}, + } + + sandbox = _write( + work / "sandbox.yaml", + { + "schema_version": "openadapt.verify-sandbox/v1", + "app": {"base_url": DIRECTUS}, + "actors": { + "agent": { + "id": me["id"], + "login": login("admin@example.org", "VD_DIRECTUS_ADMIN_PW"), + }, + "other": { + "id": editor["id"], + "login": login("editor@example.org", "VD_DIRECTUS_EDITOR_PW"), + }, + }, + "store": { + "dialect": "postgresql", + "read": { + **pg, + "sql_connect_args": {**pg["sql_connect_args"], "user": "vd_reader"}, + "sql_password_env": "VD_DIRECTUS_READER_PW", + }, + "admin": { + **pg, + "sql_connect_args": {**pg["sql_connect_args"], "user": "directus"}, + "sql_password_env": "VD_DIRECTUS_PG_PW", + }, + }, + }, + ) + return AppRun( + "directus", + True, + str(work / "openapi.json"), + work / "trace.har", + task, + sandbox, + heldout_payloads=[ + {"status": "blocked", "priority": "5"}, + {"status": "done", "priority": "4"}, + {"status": "waiting", "priority": "7"}, + {"status": "triage", "priority": "6"}, + {"status": "closed", "priority": "9"}, + ], + other_record={"ticket_id": other_ticket}, + operator_inputs=[ + "app base URL", + "two users' sign-in (email, password env)", + "read-only DB connection", + "admin DB connection", + ], + setup_seconds=round(time.monotonic() - started, 1), + ) + + +SETUPS["directus"] = setup_directus diff --git a/packages/flow/benchmark/verify_draft/results/mealie.log b/packages/flow/benchmark/verify_draft/results/v1/mealie.log similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie.log rename to packages/flow/benchmark/verify_draft/results/v1/mealie.log diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/report.json b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/report.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/draft/report.json rename to packages/flow/benchmark/verify_draft/results/v1/mealie/draft/report.json diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-1.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-1.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-1.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.admission.json b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.admission.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.admission.json rename to packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.admission.json diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.yaml b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-2.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.admission.json b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-3.admission.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.admission.json rename to packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-3.admission.json diff --git a/packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.yaml b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-3.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/draft/rounds/round-3.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mealie/draft/rounds/round-3.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mealie/result.json b/packages/flow/benchmark/verify_draft/results/v1/mealie/result.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/result.json rename to packages/flow/benchmark/verify_draft/results/v1/mealie/result.json diff --git a/packages/flow/benchmark/verify_draft/results/mealie/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/v1/mealie/setup/sandbox.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/setup/sandbox.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mealie/setup/sandbox.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mealie/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/v1/mealie/setup/task.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/setup/task.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mealie/setup/task.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mealie/setup/trace.har b/packages/flow/benchmark/verify_draft/results/v1/mealie/setup/trace.har similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mealie/setup/trace.har rename to packages/flow/benchmark/verify_draft/results/v1/mealie/setup/trace.har diff --git a/packages/flow/benchmark/verify_draft/results/mockloan.log b/packages/flow/benchmark/verify_draft/results/v1/mockloan.log similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan.log rename to packages/flow/benchmark/verify_draft/results/v1/mockloan.log diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/contract.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/contract.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json b/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/report.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/report.json diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/rounds/round-1.admission.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/rounds/round-1.admission.json diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/rounds/round-1.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/rounds/round-1.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/result.json b/packages/flow/benchmark/verify_draft/results/v1/mockloan/result.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/result.json rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/result.json diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/v1/mockloan/setup/sandbox.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/setup/sandbox.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/v1/mockloan/setup/task.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/setup/task.yaml diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har b/packages/flow/benchmark/verify_draft/results/v1/mockloan/setup/trace.har similarity index 100% rename from packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har rename to packages/flow/benchmark/verify_draft/results/v1/mockloan/setup/trace.har diff --git a/packages/flow/benchmark/verify_draft/results/workbench.log b/packages/flow/benchmark/verify_draft/results/v1/workbench.log similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench.log rename to packages/flow/benchmark/verify_draft/results/v1/workbench.log diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/contract.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml rename to packages/flow/benchmark/verify_draft/results/v1/workbench/draft/contract.yaml diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json b/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/report.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/draft/report.json rename to packages/flow/benchmark/verify_draft/results/v1/workbench/draft/report.json diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/rounds/round-1.admission.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json rename to packages/flow/benchmark/verify_draft/results/v1/workbench/draft/rounds/round-1.admission.json diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/rounds/round-1.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml rename to packages/flow/benchmark/verify_draft/results/v1/workbench/draft/rounds/round-1.yaml diff --git a/packages/flow/benchmark/verify_draft/results/workbench/result.json b/packages/flow/benchmark/verify_draft/results/v1/workbench/result.json similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/result.json rename to packages/flow/benchmark/verify_draft/results/v1/workbench/result.json diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/v1/workbench/setup/sandbox.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml rename to packages/flow/benchmark/verify_draft/results/v1/workbench/setup/sandbox.yaml diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/v1/workbench/setup/task.yaml similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml rename to packages/flow/benchmark/verify_draft/results/v1/workbench/setup/task.yaml diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har b/packages/flow/benchmark/verify_draft/results/v1/workbench/setup/trace.har similarity index 100% rename from packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har rename to packages/flow/benchmark/verify_draft/results/v1/workbench/setup/trace.har diff --git a/packages/flow/benchmark/verify_draft/run.py b/packages/flow/benchmark/verify_draft/run.py index e6688701f8..4b75d875ea 100644 --- a/packages/flow/benchmark/verify_draft/run.py +++ b/packages/flow/benchmark/verify_draft/run.py @@ -14,7 +14,7 @@ Person decisions are counted as the draft command counts them (answers to its one question). The sandbox file's facts are listed as operator inputs, -not decisions, as in the Vikunja setup log the brief compares against. +not decisions, as in the earlier setup log this is compared against. """ from __future__ import annotations diff --git a/packages/flow/docs/VERIFY_DRAFT.md b/packages/flow/docs/VERIFY_DRAFT.md index a83fc6b7ad..d824a632d4 100644 --- a/packages/flow/docs/VERIFY_DRAFT.md +++ b/packages/flow/docs/VERIFY_DRAFT.md @@ -97,11 +97,14 @@ no reset hook. once, between two reads of the store, to see which rows they move. The model gets the rows and columns that moved, with their values. The sandbox holds synthetic data only. -2. **Draft.** The pinned model writes a contract that diffs the whole - database (`frame.database`). It also writes other valid values for the - task to test with. Connection keys are filled in from the sandbox. A - draft that sets a hook, a session, a reset or a command, or whose read is - not a plain SELECT, is refused without being run. +2. **Draft.** The pinned model writes a contract, as JSON text, that diffs + the whole database (`frame.database`). It also writes other valid values + for the task to test with. The draft may only read the database with + plain SQL SELECTs: anything outside an allowlist of contract keys is + refused without being run. That includes a REST or FHIR read, a URL, a + credential, a hook, an app profile, an `admission` or `learned` section, + and any `${...}` reference. The connection keys are then filled in from + the sandbox. 3. **Qualify.** Each case restores the store, takes the contract's baseline, replays the write through the app, and then plants one fault with the privileged connection: @@ -117,6 +120,13 @@ no reset hook. | 5 clean writes | the write with other values, and a recheck of each | confirmed | | attribution probe | the write by two users with two sets of values (2 x 2), and the first of them again | confirmed | + A case the sandbox can't build is **untestable**, never a pass. Examples + are a lost update with no second user, or a sibling edit with no other + record. The command stops and names the sandbox fix, since no model + round can repair it. Only two cases are truly not applicable: a lost + update for a write that creates a record, and an app that refuses the + stale save itself. + The **causal-attribution probe** sorts every column that moved by cause: - on its own (`clock` or `fresh`): it differs between two identical diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py index 6c2ce18ccc..17ba62be6b 100644 --- a/packages/flow/openadapt_flow/verify_draft/admit.py +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -75,22 +75,74 @@ CLEAN_PROBES = 5 #: The recheck window admission cases use. ADMISSION_RECHECK_S = 2.0 -_FORBIDDEN_KEYS = frozenset( +#: What a drafted contract may contain. Everything else is refused before +#: the draft is run: the model read untrusted trace and row text, so a key it +#: wrote must not choose a store, a URL, a credential or a hook. +_TOP_KEYS = frozenset( { - "session", - "reset", - "command", - "python", - "hook", - "hooks", - "sql_driver", - "sql_connect_args", - "sql_password_env", - "sqlite_database", - "admission", - "owned_sqlite_insert", - "profile", - "profile_sha256", + "schema_version", + "verifier", + "effects", + "frame", + "environment_id", + "minimum_effect_strength", + "max_execution_window_s", + } +) +_READ_KEYS = frozenset({"kind", "sql_query", "records_drop_fields"}) +_FRAME_KEYS = frozenset( + { + "identity_field", + "ignore_fields", + "target_fields", + "target_fields_by_surface", + "attribution", + "side_records", + "database", + "versions", + } +) +_DATABASE_KEYS = frozenset( + { + "dialect", + "allow_tables", + "views", + "judged_by", + "new_row_fields", + "ignore_columns", + "max_rows", + "read_row_budget", + "settle_s", + "settle_attempts", + "recheck_after_s", + "schemas", + } +) +_VERSIONS_KEYS = frozenset( + { + "read", + "record_field", + "target_field", + "target_surface", + "version_field", + "author_field", + "self", + } +) +_ATTRIBUTION_KEYS = frozenset( + { + "kind", + "actor_field", + "record_field", + "record_key", + "self", + "read", + "event_field", + "write_events", + "insert_events", + "delete_events", + "table_field", + "server_set", } ) _IDENTIFIER = re.compile(r"(^|_)(id|key|no|number|code|slug|mrn|ref|uuid)$", re.I) @@ -103,23 +155,46 @@ class DraftProblem(ValueError): # -- the contract -------------------------------------------------------------- -def _walk(value: Any, path: str = "") -> list[str]: - bad = [] - if isinstance(value, dict): - for k, v in value.items(): - if k in _FORBIDDEN_KEYS: - bad.append(f"{path}{k}") - if ( - isinstance(v, str) - and re.fullmatch(r"[\w.]+:[\w]+", v) - and k not in ("probe",) - ): - if k in ("driver", "module", "function"): - bad.append(f"{path}{k}") - bad += _walk(v, f"{path}{k}.") - elif isinstance(value, list): - for i, v in enumerate(value): - bad += _walk(v, f"{path}{i}.") +def _sql_read(read: Any, where: str) -> list[str]: + if not isinstance(read, dict): + return [f"{where} must be a read"] + bad = [f"{where}.{k}" for k in read if k not in _READ_KEYS] + if read.get("kind") != "sql" or "sql_query" not in read: + bad.append(f"{where} must be kind: sql with a sql_query") + return bad + + +def _disallowed(data: Mapping[str, Any]) -> list[str]: + """Keys a draft may not set (an allowlist, not a denylist).""" + + bad = [k for k in data if k not in _TOP_KEYS] + verifier = data.get("verifier") + if not isinstance(verifier, dict): + return bad + ["verifier"] + if verifier.get("kind") == "surfaces": + bad += [f"verifier.{k}" for k in verifier if k not in ("kind", "surfaces")] + for name, sub in (verifier.get("surfaces") or {}).items(): + bad += _sql_read(sub, f"verifier.surfaces.{name}") + else: + bad += _sql_read(verifier, "verifier") + frame = data.get("frame") or {} + if not isinstance(frame, dict): + return bad + ["frame"] + bad += [f"frame.{k}" for k in frame if k not in _FRAME_KEYS] + db = frame.get("database") or {} + if isinstance(db, dict): + bad += [f"frame.database.{k}" for k in db if k not in _DATABASE_KEYS] + versions = frame.get("versions") + if isinstance(versions, dict): + bad += [f"frame.versions.{k}" for k in versions if k not in _VERSIONS_KEYS] + bad += _sql_read(versions.get("read"), "frame.versions.read") + attribution = frame.get("attribution") + if isinstance(attribution, dict): + bad += [ + f"frame.attribution.{k}" for k in attribution if k not in _ATTRIBUTION_KEYS + ] + if "read" in attribution: + bad += _sql_read(attribution["read"], "frame.attribution.read") return bad @@ -150,13 +225,20 @@ def prepare(contract_yaml: str, sandbox: SandboxConfig) -> dict[str, Any]: try: data = yaml.safe_load(contract_yaml) except yaml.YAMLError as exc: - raise DraftProblem(f"the contract is not valid YAML: {exc}") from exc + raise DraftProblem(f"the contract is not valid JSON or YAML: {exc}") from exc if not isinstance(data, dict): - raise DraftProblem("the contract must be a YAML mapping") + raise DraftProblem("the contract must be one JSON object") data.pop("provenance", None) - bad = _walk(data) + if "${" in json.dumps(data, default=str): + raise DraftProblem( + "the contract may not reference environment variables (${...})" + ) + bad = _disallowed(data) if bad: - raise DraftProblem("the contract may not set " + ", ".join(sorted(set(bad)))) + raise DraftProblem( + "the contract may only read the database with plain SQL; it may not set " + + ", ".join(sorted(set(bad))) + ) frame = data.get("frame") or {} database = frame.get("database") if isinstance(frame, dict) else None if not isinstance(database, dict): @@ -325,6 +407,9 @@ class Case: recheck: str = "" passed: bool = False applicable: bool = True + #: The sandbox can't build this case (no other record, no second user): + #: never a pass, and an operator fix rather than the model's. + untestable: bool = False note: str = "" reasons: list[str] = field(default_factory=list) moved: list[dict[str, Any]] = field(default_factory=list) @@ -334,7 +419,13 @@ def as_dict(self) -> dict[str, Any]: return dict(self.__dict__) def line(self) -> str: - verdict = "ok" if self.passed else ("n/a" if not self.applicable else "FAILED") + verdict = ( + "UNTESTABLE" + if self.untestable + else "ok" + if self.passed + else ("n/a" if not self.applicable else "FAILED") + ) got = self.outcome + (f", recheck {self.recheck}" if self.recheck else "") why = "; ".join(self.reasons[:3]) if self.moved and not self.passed: @@ -383,8 +474,30 @@ def as_dict(self) -> dict[str, Any]: "attribution": [a.as_dict() for a in self.attribution], } + def untestable(self) -> list[Case]: + return [c for c in self.cases if c.untestable] + + def only_untestable(self) -> bool: + """Every failure is the sandbox's, not the draft's.""" + + return bool(self.untestable()) and not ( + self.problems + or any(a.problem for a in self.attribution) + or any( + not c.passed and not c.untestable and c.applicable for c in self.cases + ) + ) + def feedback(self) -> str: - lines = [c.line() for c in self.cases if not c.passed and c.applicable] + lines = [ + c.line() + for c in self.cases + if not c.passed and c.applicable and not c.untestable + ] + lines += [ + c.line() + " (the sandbox can't build this case; not the contract's fault)" + for c in self.untestable() + ] lines += [ f"[FAILED] attribution {a.table}.{a.column} ({a.cause}): {a.problem}" for a in self.attribution @@ -510,15 +623,17 @@ def run( if before is not None: note = before() if note: - case.applicable = False + case.untestable = True # the setup step itself failed case.note = note - case.passed = True return None statuses = self.app.send( self.demo.writes, actor, swap_map(self.demo.params, values) ) if any(s >= 400 for s in statuses): + # For a clean write: the values were invalid (the caller + # skips them). For anything else the case can't be built. case.applicable = False + case.untestable = case.group != "clean" case.note = f"the app refused the write (HTTP {max(statuses)})" return None pre = self.demo.base @@ -563,6 +678,9 @@ def run( @staticmethod def _judge(case: Case) -> None: + if case.untestable: + case.passed = False + return if not case.applicable: case.passed = True return @@ -717,7 +835,14 @@ def _pins(self, contract: Mapping[str, Any]) -> list[str]: def _values(self, payload: Mapping[str, Any]) -> dict[str, Any]: out = dict(self.demo.params) changed = False + # A value the demonstration shares with another parameter can't be + # swapped in the trace without changing both: it is not varied. + shared = { + k for k in out for j in out if k != j and text(out[k]) == text(out[j]) + } for k, v in payload.items(): + if k in shared: + continue if k in out and v is not None and text(v) != text(out[k]): out[k] = v changed = True @@ -767,7 +892,7 @@ def plant(pre: Rows, post: Rows, col: str = col) -> None: raise RuntimeError( "the write moved no row holding a task value" ) - self.store.update(m.table, m.key, {col: _perturb(m.after[col])}) + self.store.update(m.table, m.key, {col: _perturb(m.a[col])}) self.run(contract, case, values=values, fault=plant) out.append(case) @@ -784,23 +909,21 @@ def plant_row(pre: Rows, post: Rows) -> None: if m.change == "changed": others = [k for k in post[m.table] if k != m.key] if not others: - raise _NotApplicable("the table holds no other record") + raise _Untestable("the table holds no other record") other = others[self.seed % len(others)] - moved = {c: m.after[c] for c in m.columns} + moved = {c: m.a[c] for c in m.columns} self.store.update(m.table, other, moved) - self.store.update( - m.table, m.key, {c: m.before[c] for c in m.columns} - ) + self.store.update(m.table, m.key, {c: m.b[c] for c in m.columns}) case.detail = f"the update landed on another {m.table} row" return - fk = [c for c in m.columns if c in t.fks and m.after.get(c) is not None] + fk = [c for c in m.columns if c in t.fks and m.a.get(c) is not None] if fk: col = fk[0] ref = self.store.tables[t.fks[col]] choices = [ k for k in post.get(ref.name, {}) - if len(ref.pk) == 1 and text(k[0]) != text(m.after[col]) + if len(ref.pk) == 1 and text(k[0]) != text(m.a[col]) ] if choices: self.store.update( @@ -814,8 +937,8 @@ def plant_row(pre: Rows, post: Rows) -> None: if _IDENTIFIER.search(c) or _IDENTIFIER.search(p) ] if not ids: - raise _NotApplicable("the new row names no parent record") - self.store.update(m.table, m.key, {ids[0]: _perturb(m.after[ids[0]])}) + raise _Untestable("the new row names no parent record") + self.store.update(m.table, m.key, {ids[0]: _perturb(m.a[ids[0]])}) case.detail = f"the new {m.table} row is filed under another {ids[0]}" self._planted(contract, case, values, plant_row) @@ -830,9 +953,7 @@ def plant_dup(pre: Rows, post: Rows) -> None: m, _ = self._target(pre, post, values) if m is None: raise RuntimeError("the write moved no row holding a task value") - self.store.insert( - m.table, self.store.new_key_row(m.table, m.after, post) - ) + self.store.insert(m.table, self.store.new_key_row(m.table, m.a, post)) self._planted(contract, case, values, plant_dup) return [case] @@ -876,11 +997,11 @@ def plant_sib(pre: Rows, post: Rows) -> None: if hidden: for h in hidden[:3]: self.masked.append({"fault": "sibling_edit", "column": h}) - raise _NotApplicable( + raise _Untestable( "every editable column of the other records is excluded: " + ", ".join(hidden[:3]) ) - raise _NotApplicable("the store holds no other record to edit") + raise _Untestable("the store holds no other record to edit") self._planted(contract, case, values, plant_sib) return [case] @@ -900,9 +1021,7 @@ def undo(pre: Rows, post: Rows) -> None: if m.change == "added": self.store.delete(m.table, m.key) else: - self.store.update( - m.table, m.key, {c: m.before[c] for c in m.columns} - ) + self.store.update(m.table, m.key, {c: m.b[c] for c in m.columns}) self.run(contract, case, values=values, revert=undo, rechecks=True) if case.outcome == "CONFIRMED" and not case.recheck: @@ -918,12 +1037,15 @@ def undo(pre: Rows, post: Rows) -> None: ) return [case] if "other" not in self.sandbox.actors: - case.applicable, case.note = False, "the sandbox has no second user" + case.untestable, case.note = ( + True, + "the sandbox has no second user (actors.other)", + ) return [case] other_values = accepted[0] if accepted else None if other_values is None: - case.applicable, case.note = ( - False, + case.untestable, case.note = ( + True, "no accepted payload for the other user", ) return [case] @@ -941,6 +1063,9 @@ def first_save() -> Optional[str]: ) self.run(contract, case, values=values, before=first_save) if case.note.startswith("the app refused"): + # The app itself refuses a save from a stale copy: nothing to + # catch, a true not-applicable. + case.untestable = False case.note = ( "the app refused the stale save: it prevents lost updates itself" ) @@ -961,13 +1086,21 @@ def guarded(pre: Rows, post: Rows) -> None: case.applicable = False case.note = str(exc) raise + except _Untestable as exc: + case.untestable = True + case.note = str(exc) + raise try: self.run(contract, case, values=values, fault=guarded) finally: - if not case.applicable: + if not case.applicable or case.untestable: case.outcome = case.outcome if case.outcome not in ("ERROR",) else "" - case.reasons = [r for r in case.reasons if "_NotApplicable" not in r] + case.reasons = [ + r + for r in case.reasons + if "_NotApplicable" not in r and "_Untestable" not in r + ] # -- causal attribution @@ -1023,8 +1156,8 @@ def _attribute( a.problem = "excluded, but it moves with the values written: the exclusion hides the write" out.append(a) moved = {(a.table, a.column) for a in out} - for table, cols in mask.items(): - for col in cols: + for table, masked_cols in mask.items(): + for col in masked_cols: if col == "*" and any(t == table for t, _ in moved): continue if col == "+" and (table, "+") in moved: @@ -1087,6 +1220,10 @@ class _NotApplicable(Exception): pass +class _Untestable(Exception): + pass + + def digest(value: Any) -> str: return ( "sha256:" diff --git a/packages/flow/openadapt_flow/verify_draft/draft.py b/packages/flow/openadapt_flow/verify_draft/draft.py index 09ff1f62d4..27245f3cf0 100644 --- a/packages/flow/openadapt_flow/verify_draft/draft.py +++ b/packages/flow/openadapt_flow/verify_draft/draft.py @@ -225,6 +225,13 @@ def run( if adm.admitted: break reason = adm.feedback() + if adm.only_untestable(): + # No model round can fix the sandbox. + reason = ( + "the sandbox can't build every case; fix it and run again:\n" + reason + ) + log(f"round {used}: stopped: {reason}") + break messages.append( { "role": "user", diff --git a/packages/flow/openadapt_flow/verify_draft/inputs.py b/packages/flow/openadapt_flow/verify_draft/inputs.py index 3273979707..36d729f56f 100644 --- a/packages/flow/openadapt_flow/verify_draft/inputs.py +++ b/packages/flow/openadapt_flow/verify_draft/inputs.py @@ -16,6 +16,7 @@ import json import re +from collections.abc import Collection from dataclasses import dataclass from pathlib import Path from typing import Any, Optional @@ -230,8 +231,8 @@ def load_trace(path: str | Path) -> list[Request]: def writes( - trace: list[Request], *, skip_paths: set[str] = frozenset() -) -> list[Request]: # type: ignore[assignment] + trace: list[Request], *, skip_paths: Collection[str] = frozenset() +) -> list[Request]: """The trace's write requests (anything but GET, HEAD and OPTIONS), without sign-in requests.""" diff --git a/packages/flow/openadapt_flow/verify_draft/model.py b/packages/flow/openadapt_flow/verify_draft/model.py index 270cdf4729..331d6b72fd 100644 --- a/packages/flow/openadapt_flow/verify_draft/model.py +++ b/packages/flow/openadapt_flow/verify_draft/model.py @@ -19,7 +19,7 @@ import time from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Optional, Protocol +from typing import Any, Optional, Protocol, cast #: The pinned model. A change here is a new prompt version too. MODEL = "claude-opus-5-5" @@ -27,7 +27,7 @@ MAX_TOKENS = 32_000 #: USD per million tokens for MODEL (input, output, cache read, cache write). PRICE_PER_MTOK = {"input": 4.0, "output": 20.0, "cache_read": 0.2, "cache_write": 5.0} -PROMPT_VERSION = "verify-draft-prompt/1" +PROMPT_VERSION = "verify-draft-prompt/2" SYSTEM_PROMPT = """\ You write record checks for OpenAdapt. A record check is an `openadapt.verify/v1` @@ -41,7 +41,8 @@ if it refutes every fault and confirms every clean write. At run time it makes no model calls, so everything it needs must be in the contract. -Write the contract in YAML with this shape. Leave out every connection key +Write the contract as one JSON object. Its shape, shown here in YAML for +brevity, is below. Leave out every connection key (sql_driver, sql_connect_args, sql_password_env, sqlite_database): OpenAdapt fills them in. Never write session, reset, command, python or hook keys. @@ -116,7 +117,7 @@ effect and let the frame refute any other. Answer with one JSON object: -{"contract_yaml": "", +{"contract_json": "", "payloads": [ [{"param": "", "value": ""}, ...], ... ], "notes": ""} `payloads` are 8 other valid sets of the task's VALUE parameters (not the @@ -129,7 +130,7 @@ OUTPUT_SCHEMA = { "type": "object", "properties": { - "contract_yaml": {"type": "string"}, + "contract_json": {"type": "string"}, "payloads": { "type": "array", "items": { @@ -147,7 +148,7 @@ }, "notes": {"type": "string"}, }, - "required": ["contract_yaml", "payloads", "notes"], + "required": ["contract_json", "payloads", "notes"], "additionalProperties": False, } @@ -278,11 +279,14 @@ def draft(self, messages: list[dict[str, Any]]) -> Draft: "cache_control": {"type": "ephemeral"}, } ], - messages=messages, - output_config={ - "effort": EFFORT, - "format": {"type": "json_schema", "schema": OUTPUT_SCHEMA}, - }, + messages=cast(Any, messages), + output_config=cast( + Any, + { + "effort": EFFORT, + "format": {"type": "json_schema", "schema": OUTPUT_SCHEMA}, + }, + ), ) as stream: response = stream.get_final_message() call = Call( @@ -305,7 +309,9 @@ def draft(self, messages: list[dict[str, Any]]) -> Draft: if response.stop_reason == "refusal": return Draft("", [], "the model declined to draft", call) raw = "".join( - b.text for b in response.content if getattr(b, "type", "") == "text" + str(getattr(b, "text", "")) + for b in response.content + if getattr(b, "type", "") == "text" ) return parse_answer(raw, call) @@ -328,7 +334,7 @@ def parse_answer(raw: str, call: Optional[Call] = None) -> Draft: {str(i.get("param")): i.get("value") for i in p if isinstance(i, dict)} ) return Draft( - str(data.get("contract_yaml") or ""), + str(data.get("contract_json") or data.get("contract_yaml") or ""), payloads, str(data.get("notes") or ""), call, diff --git a/packages/flow/openadapt_flow/verify_draft/sandbox.py b/packages/flow/openadapt_flow/verify_draft/sandbox.py index 80be0a5d63..ea8cd5d368 100644 --- a/packages/flow/openadapt_flow/verify_draft/sandbox.py +++ b/packages/flow/openadapt_flow/verify_draft/sandbox.py @@ -92,7 +92,8 @@ class Login(BaseModel): path: str form: Optional[dict[str, str]] = None json_body: Optional[dict[str, Any]] = Field(default=None, alias="json") - #: A JSON response field holding a bearer token (``access_token``). + #: A JSON response field holding a bearer token (``access_token``, or a + #: dotted path such as ``data.access_token``). token_field: Optional[str] = None @@ -301,17 +302,17 @@ def _introspect(self) -> dict[str, Table]: t.columns.append(col) t.types[col] = str(dtype).lower() for schema, table, col, kind, ref in cons: - t = out.get(self._name(schema, table)) - if t is None: + found = out.get(self._name(schema, table)) + if found is None: continue - if kind == "PRIMARY KEY" and col not in t.pk: - t.pk.append(col) + if kind == "PRIMARY KEY" and col not in found.pk: + found.pk.append(col) elif kind == "FOREIGN KEY" and ref: - t.fks[col] = self._name(schema, ref) + found.fks[col] = self._name(schema, ref) elif kind == "UNIQUE": - groups = getattr(t, "_ugroups", {}) + groups = getattr(found, "_ugroups", {}) groups.setdefault(ref, []).append(col) - t._ugroups = groups # type: ignore[attr-defined] + found._ugroups = groups # type: ignore[attr-defined] for t in out.values(): t.unique = [cols for cols in getattr(t, "_ugroups", {}).values()] return out @@ -603,6 +604,16 @@ class Move: before: Optional[Row] after: Optional[Row] + @property + def a(self) -> Row: + """The row after (empty for a removed row).""" + return self.after or {} + + @property + def b(self) -> Row: + """The row before (empty for an added row).""" + return self.before or {} + def moves(before: Rows, after: Rows) -> list[Move]: out: list[Move] = [] @@ -671,7 +682,9 @@ def session(self, actor: str) -> Any: if r.status_code >= 400: raise SandboxError(f"actor {actor} could not sign in ({r.status_code})") if login.token_field: - token = (r.json() or {}).get(login.token_field) + token: Any = r.json() or {} + for part in login.token_field.split("."): # data.access_token + token = token.get(part) if isinstance(token, dict) else None if not token: raise SandboxError( f"sign-in for {actor} returned no {login.token_field}" diff --git a/packages/flow/tests/test_verify_draft.py b/packages/flow/tests/test_verify_draft.py index 5a5abcd8df..f8fe7dc1f3 100644 --- a/packages/flow/tests/test_verify_draft.py +++ b/packages/flow/tests/test_verify_draft.py @@ -362,3 +362,84 @@ def test_run_path_makes_no_model_calls(mockloan: Path) -> None: ) assert out.returncode == 0, out.stderr assert out.stdout.strip() in ("REFUTED", "UNCERTAIN") # no new record was written + + +@pytest.mark.parametrize( + "edit, why", + [ + # A REST read would point the check at a URL the model chose. + ( + lambda c: c.update( + verifier={"kind": "rest", "base_url": "http://x", "records_path": "/a"} + ), + "verifier", + ), + ( + lambda c: c["verifier"]["surfaces"]["record"].update( + auth={"bearer_env": "ANTHROPIC_API_KEY"} + ), + "auth", + ), + ( + lambda c: c["effects"][0]["match"].update( + memo={"literal": "${ANTHROPIC_API_KEY}"} + ), + "environment", + ), + (lambda c: c["frame"]["database"].update(profile="openemr"), "profile"), + (lambda c: c.update(admission={"coverage": "x.json"}), "admission"), + (lambda c: c["frame"].update(learned={"excuses": []}), "learned"), + ], +) +def test_drafts_are_allowlisted(mockloan: Path, edit: Any, why: str) -> None: + contract = yaml.safe_load(GOOD) + edit(contract) + with pytest.raises(A.DraftProblem, match=why): + A.prepare(json.dumps(contract), load_sandbox(str(mockloan / "sandbox.yaml"))) + + +def test_good_draft_as_json_text_loads(mockloan: Path) -> None: + data = A.prepare( + json.dumps(yaml.safe_load(GOOD)), load_sandbox(str(mockloan / "sandbox.yaml")) + ) + assert data["frame"]["database"]["read"]["sqlite_database"] + + +def test_untestable_is_never_a_pass() -> None: + case = A.Case( + "fault", "lost_update", "", "refuted", untestable=True, note="no second user" + ) + A.Qualifier._judge(case) + assert not case.passed + adm = A.Admission(False, "sha256:" + "0" * 64, [case], [], []) + assert adm.only_untestable() and "not the contract's fault" in adm.feedback() + + +def test_one_question_at_most(mockloan: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A masked column is asked about once; the answer is a decision, and + 'bookkeeping' lets the same draft be qualified again.""" + + calls: list[set[str]] = [] + + def fake_qualify( + self: A.Qualifier, contract: Any, payloads: Any, **kw: Any + ) -> A.Admission: + calls.append(set(self.bookkeeping)) + ok = "records.memo" in self.bookkeeping + masked = [] if ok else [{"fault": "sibling_edit", "column": "records.memo"}] + return A.Admission(ok, "sha256:" + "0" * 64, [], [], [], masked) + + monkeypatch.setattr(A.Qualifier, "qualify", fake_qualify) + asked: list[str] = [] + + def ask(question: str, columns: Any) -> dict[str, str]: + asked.append(question) + return {c: "bookkeeping" for c in columns} + + outcome = _run(mockloan, Fixed(GOOD), rounds=3, ask=ask) + assert outcome.admitted and outcome.decisions == 1 and len(asked) == 1 + assert calls == [set(), {"records.memo"}] + # Without an answer the draft is refused, never admitted on a guess. + calls.clear() + outcome = _run(mockloan, Fixed(GOOD), rounds=1, ask=lambda q, c: None) + assert not outcome.admitted and outcome.decisions == 0 From 8ed183eafd02d77d695306ff34a01700d7ba1425 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:40:10 -0500 Subject: [PATCH 04/14] bench(verify): verify draft on Directus (untuned) and the prompt-2 reruns; results --- CAPABILITIES.md | 2 +- .../flow/benchmark/verify_draft/RESULTS.md | 170 ++++++ .../verify_draft/results/directus.load | 2 + .../verify_draft/results/directus.log | 413 ++++++++++++++ .../results/directus/draft/contract.yaml | 132 +++++ .../results/directus/draft/report.json | 30 + .../draft/rounds/round-1.admission.json | 527 ++++++++++++++++++ .../directus/draft/rounds/round-1.yaml | 1 + .../draft/rounds/round-2.admission.json | 520 +++++++++++++++++ .../directus/draft/rounds/round-2.yaml | 1 + .../verify_draft/results/directus/result.json | 439 +++++++++++++++ .../results/directus/setup/sandbox.yaml | 40 ++ .../results/directus/setup/task.yaml | 5 + .../results/directus/setup/trace.har | 92 +++ .../verify_draft/results/mockloan.log | 437 +++++++++++++++ .../results/mockloan/draft/contract.yaml | 83 +++ .../results/mockloan/draft/report.json | 20 + .../draft/rounds/round-1.admission.json | 482 ++++++++++++++++ .../mockloan/draft/rounds/round-1.yaml | 1 + .../verify_draft/results/mockloan/result.json | 450 +++++++++++++++ .../results/mockloan/setup/sandbox.yaml | 14 + .../results/mockloan/setup/task.yaml | 7 + .../results/mockloan/setup/trace.har | 84 +++ .../verify_draft/results/spend.jsonl | 4 + .../verify_draft/results/workbench.log | 327 +++++++++++ .../results/workbench/draft/contract.yaml | 108 ++++ .../results/workbench/draft/report.json | 20 + .../draft/rounds/round-1.admission.json | 429 ++++++++++++++ .../workbench/draft/rounds/round-1.yaml | 1 + .../results/workbench/result.json | 340 +++++++++++ .../results/workbench/setup/sandbox.yaml | 36 ++ .../results/workbench/setup/task.yaml | 5 + .../results/workbench/setup/trace.har | 135 +++++ packages/flow/docs/VERIFY_DRAFT.md | 2 +- 34 files changed, 5357 insertions(+), 2 deletions(-) create mode 100644 packages/flow/benchmark/verify_draft/RESULTS.md create mode 100644 packages/flow/benchmark/verify_draft/results/directus.load create mode 100644 packages/flow/benchmark/verify_draft/results/directus.log create mode 100644 packages/flow/benchmark/verify_draft/results/directus/draft/contract.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/directus/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/directus/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/directus/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/directus/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/directus/setup/trace.har create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan.log create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har create mode 100644 packages/flow/benchmark/verify_draft/results/workbench.log create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/report.json create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/result.json create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml create mode 100644 packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 0cc9847bd8..4654018a48 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -166,7 +166,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR (MEASURE_PLACEHOLDER) | MEASURE_EVIDENCE | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR (MEASURE_PLACEHOLDER) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/packages/flow/benchmark/verify_draft/RESULTS.md b/packages/flow/benchmark/verify_draft/RESULTS.md new file mode 100644 index 0000000000..fff7f77194 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/RESULTS.md @@ -0,0 +1,170 @@ +# Results: model-drafted write contracts, admitted by qualification + +Protocol: [PROTOCOL.md](PROTOCOL.md) and its addendum. Runs were made on +2026-11-21 with `claude-opus-5-5` at effort `medium`. Data was synthetic, +browser-free and headless. Raw data for every run, void or not, is under +[results/](results/): + +- `result.json`: the numbers; +- `draft/rounds/`: every draft and every admission case; +- `draft/contract.yaml`: the admitted contracts; +- `setup/`: the operator inputs; +- `spend.jsonl` and `spend-dev.jsonl`: every model call. + +## Verdict + +**The kill criterion fires on time.** No untuned app finished setup within +5 minutes: + +- **Mealie, first valid run: 9.2 minutes, and no contract was admitted.** +- **Directus, reported run: 6.0 minutes**, admitted in round 2. The first + draft passed every planted fault and every clean write. Round 1 was lost + only to a rule stricter than the brief, which refuses an exclusion that + never moved (below). + +The other two clauses do not fire: + +- **Person decisions:** 0 on every app. The command never needed its one + question. +- **Missed planted faults:** no admitted contract missed one, in admission + or held out. Across the three admitted contracts, the held-out check + caught 24 of 24 applicable faults, with 0 false stops on 15 held-out + clean writes. + +**Qualification did its job.** It refused every unsound draft: + +- a Mealie check that couldn't see a lost update; +- a Mealie check that stopped every clean write; +- every draft that didn't load. + +Each refusal said why. No refused draft would have been safe to admit. + +**Speed is now the constraint, not judgment.** One admission round takes +130 to 180 seconds on the lab apps. Each case reads a 28- or 62-table +database several times over an SSH tunnel. A model round takes 14 to 93 +seconds. So two rounds already pass 5 minutes. Setup took 1.3 to 1.4 +minutes on the two local apps, with one round each. + +## Per-app table (reported runs) + +| App | Tuned on? | Description | Setup minutes | Person decisions | Drafts admitted / rejected | Planted faults caught, admission | Planted faults caught, held out | False stops, admission clean writes | False stops, held-out clean writes | Model USD | +|---|---|---|---|---|---|---|---|---|---|---| +| MockLoan (create) | yes | `db` | 1.4 | 0 | 1 / 0 | 8/8 | 10/10 | 0/5 | 0/5 | 0.05 | +| Workbench, MockMed profile (update) | yes | `db` | 1.3 | 0 | 1 / 0 | 6/6 | 6/6 | 0/5 | 0/5 | 0.08 | +| Mealie v2.8.0 (update), first valid run | no | OpenAPI | 9.2 | 0 | 0 / 3 | best draft 6/8 | not run (nothing admitted) | best draft 0/5 | - | 0.58 | +| Directus 11.5.1 (update) | no | OpenAPI | 6.0 | 0 | 1 / 1 | 7/7 | 8/8 | 0/5 | 0/5 | 0.17 | + +How to read the columns: + +- "Planted faults caught" counts the applicable faults. One `wrong_value` + case is planted per written column. +- Each admitted contract also confirmed every write in its attribution + probe: 5 writes each (2 users x 2 payloads, plus the first write + repeated). +- Model cost per contract is USD 0.05 to 0.17 for the admitted ones, and + USD 0.58 for Mealie's refusal. + +The benchmark spent USD 2.52 in all: + +- USD 1.93 on the reported and void runs (`spend.jsonl`); +- USD 0.59 on development on the tuned apps (`spend-dev.jsonl`). + +The cap was USD 30. + +## What each case showed + +**MockLoan.** The drafted check reads the records table. It matches all +four values and the surface, and declares the columns the app sets on a new +row. It refuted the faults planted on other rows with other values. It also +refuted the two app-level faults: the same disbursement sent to another +loan, and the disbursement sent twice. MockLoan has no sign-in, so its two +actors send identical requests. The lost-update case is not applicable to a +create. + +**Workbench.** The drafted check reads the patient and counts the save's own +audit row. The audit row is tied to the patient by a join, and the frame +judges it through `judged_by`. The lost-update case ran, but it is not +applicable: the workbench refuses a save from a stale form (HTTP 409). The +workbench signs in one user, so its second actor is a second session of +that user, and the attribution probe has no real actor axis. There was no +app-level held-out fault, because the harness gave no second record to +write to. + +**Mealie, the first untuned app.** Mealie keeps no version, author or save +history for a recipe. Its PATCH deletes and re-creates the recipe's child +rows (instructions, ingredients, nutrition, settings) on every save. So a +lost update leaves the store exactly as a correct save would. No draft +caught one. Two drafts tried to read the re-created child rows' ids as +versions. Those ids come from a shared sequence, not a per-recipe one, so +those drafts stopped every clean write. Admission refused all of them, +which is the right outcome for a store that can't show a lost update. It +also makes Mealie a poor test of the approach, which is why Directus was +added. + +**Directus, the second untuned app.** The draft read four things: + +- the ticket; +- the save's revision, joined to its activity row to get the author; +- `frame.versions` from the same join, with `author_field`, so the other + user's save in the window refutes the agent's; +- the whole database, with the activity log append-only and the session + table skipped. + +All 17 cases passed in round 1, including the lost update. The draft was +rejected only because it also excluded `directus_users.last_access`. That +column moves at sign-in, not during a write, so it never moved in a probe. +Round 2 dropped that exclusion and was admitted. Held out, the contract +refuted all 8 applicable faults: + +- the faults planted on another ticket with other values; +- the late revert, at the recheck; +- the lost update; +- the same write sent to another ticket through the app. + +## Earlier runs (kept, not reported in the table) + +| Run | What happened | Minutes | Model USD | +|---|---|---|---| +| Mealie run 1, void | Operator setup error: the read-only role had no `SELECT` on the sequences, so no baseline could be taken. Stopped after round 2. The command now checks the read account once before any model call. | - | 0.51 | +| Mealie run 3, after the fixes below | Refused after 3 rounds. The best draft caught 6 of 7 faults, missing only the lost update. | 4.0 | 0.44 | +| MockLoan and workbench, prompt 1 (`results/v1/`) | Admitted in round 1 with the same numbers as the reported runs. | 1.4 and 1.2 | 0.04 and 0.06 | + +Mealie run 2 exposed three faults in the qualifier. They were fixed before +Directus, and the addendum lists them: + +1. **Fresh row ids counted as written values.** Without a repeated write, + the attribution probe counted the new id of a re-created row as moving + with the payload. So it flagged a correct `skip` exclusion. +2. **A derived copy counted as a written column.** A lower-cased copy + (`description_normalized`) was treated as a column the task writes, so + a wrong value was planted there. +3. **Unloadable YAML.** The prompt asked for YAML, and unquoted colons in + `reason:` strings made the YAML fail to load in two rounds. Prompt 2 + asks for JSON. + +Mealie run 2 also counted rounds in a way the harness has since fixed: its +`result.json` says 2 drafts, and there were 3. + +## Limits of this evidence + +- **Held-out coverage.** The held-out check ran only on admitted contracts. + That means the two tuned apps and Directus, not Mealie. +- **The faults are planted by OpenAdapt.** Most are written to the store + with the privileged connection. Only the lost update and the two + app-level held-out faults go through the app. No grader written by + someone else judged these runs; the blind trial covers that separately. +- **The attribution probe's definition is this PR's.** The brief describes + it as "two actors by two payloads"; [VERIFY_DRAFT.md](../../docs/VERIFY_DRAFT.md) + defines it. The rule that refuses an exclusion that never moved is + stricter than the brief, and it cost Directus a round. A rule that also + accepts an exclusion of a column the app moves at sign-in would need a + sign-in in the probe. That's a possible next step, not measured here. +- **Setup minutes are command wall time.** They don't include the + operator's work: starting the app, creating users, recording the trace + and writing `sandbox.yaml`. The harness scripted that work in 1 to 5 + seconds (`operator_setup_seconds`). A person doing it by hand would take + longer. +- **Host load.** The Mac's 1-minute load was 36 at the start of the + Directus run and 18 at the end (`results/directus.load`). Most of the time went to database reads + on the lab host and to model calls. +- **One task per app.** One run per app, so no spread is reported. diff --git a/packages/flow/benchmark/verify_draft/results/directus.load b/packages/flow/benchmark/verify_draft/results/directus.load new file mode 100644 index 0000000000..2d4068fbe2 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus.load @@ -0,0 +1,2 @@ + 3:30 up 5 days, 7:53, 9 users, load averages: 35.50 55.62 49.62 + 3:38 up 5 days, 8:01, 9 users, load averages: 17.67 30.24 39.15 diff --git a/packages/flow/benchmark/verify_draft/results/directus.log b/packages/flow/benchmark/verify_draft/results/directus.log new file mode 100644 index 0000000000..7c6c18f8e1 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus.log @@ -0,0 +1,413 @@ +[directus] store: 28 tables; trace: 1 write request(s) +[directus] demonstration: changed tickets, columns ['priority', 'status'] +[directus] round 1: rejected (17/17 cases, 182s) +[directus] round 2: ADMITTED (17/17 cases, 129s) +{ + "app": "directus", + "untuned": true, + "describe": "openapi", + "operator_setup_seconds": 1.8, + "operator_inputs": [ + "app base URL", + "two users' sign-in (email, password env)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 6.0, + "person_decisions": 0, + "questions": [], + "drafts": 2, + "drafts_admitted": 1, + "drafts_rejected": 1, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", + "model_usd": 0.1717, + "rounds": [ + { + "admitted": false, + "faults_applicable": 7, + "faults_caught": 7, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [ + "directus_users.last_access: excluded, but it never moved in any probe write: nothing to excuse" + ], + "not_applicable": {}, + "seconds": 182.4 + }, + { + "admitted": true, + "faults_applicable": 7, + "faults_caught": 7, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 129.09 + } + ], + "notes": [], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.47 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.01 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.21 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.95 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.98 + }, + { + "group": "fault", + "name": "wrong_value:priority", + "detail": "tickets.priority holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 10.84 + }, + { + "group": "fault", + "name": "wrong_value:status", + "detail": "tickets.status holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.46 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another tickets row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.16 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the tickets record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "added", + "columns": [ + "id", + "note", + "priority", + "status", + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.53 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another tickets row's title edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.37 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the tickets write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 8.77 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "lost update: another user saved a version of the target inside the window, so the agent's save may have overwritten it", + "3 record(s) outside the declared write moved (added, changed); 3 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "revision", + "change": "added" + }, + { + "row": true, + "table": "directus_revisions", + "change": "added", + "columns": [ + "activity", + "collection", + "data", + "delta", + "id", + "item" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "directus_users", + "change": "changed", + "columns": [ + "last_access" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.38 + }, + { + "group": "fault", + "name": "app_sibling", + "detail": "the same write also sent to {'ticket_id': '3'} through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "3 record(s) outside the declared write moved (added, changed); 3 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "revision", + "change": "added" + }, + { + "row": true, + "table": "directus_revisions", + "change": "added", + "columns": [ + "activity", + "collection", + "data", + "delta", + "id", + "item" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.04 + } + ], + "faults_applicable": 8, + "faults_caught": 8, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/directus/draft/contract.yaml new file mode 100644 index 0000000000..6e217ad7d1 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/contract.yaml @@ -0,0 +1,132 @@ +# Drafted by a model and admitted by OpenAdapt qualification (openadapt verify draft). Runs make no model calls. +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."title" AS TEXT) AS "title", + CAST(t."status" AS TEXT) AS "status", CAST(t."priority" AS TEXT) AS "priority", + CAST(t."note" AS TEXT) AS "note" FROM "tickets" t + sql_driver: psycopg2 + sql_connect_args: &id001 + host: 127.0.0.1 + port: 9665 + dbname: directus + user: vd_reader + sql_password_env: VD_DIRECTUS_READER_PW + revision: + kind: sql + sql_query: SELECT CAST(r."id" AS TEXT) AS "id", CAST(r."collection" AS TEXT) + AS "collection", CAST(r."item" AS TEXT) AS "item", CAST(a."action" AS TEXT) + AS "action", CAST(a."user" AS TEXT) AS "user" FROM "directus_revisions" r + JOIN "directus_activity" a ON a."id" = r."activity" + sql_driver: psycopg2 + sql_connect_args: *id001 + sql_password_env: VD_DIRECTUS_READER_PW +effects: +- kind: record_written + probe: surface=record|ticket has the new status and priority + match: + id: + param: ticket_id + status: + param: status + priority: + param: priority + expected_count: 1 +- kind: record_written + probe: surface=revision|one new update revision of this ticket by the actor + match: + collection: + literal: tickets + item: + param: ticket_id + action: + literal: update + user: + param: actor_id + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: + - status + - priority + database: + dialect: postgresql + allow_tables: + - table: directus_activity + mode: append_only + reason: Directus appends an activity row for every sign-in and every save; the + save's revision (joined to its activity) is checked as an effect + - table: directus_sessions + mode: skip + reason: auth session tokens created/refreshed on sign-in + views: + tickets: record + judged_by: + directus_revisions: revision + new_row_fields: + directus_revisions: + - id + - activity + - data + - delta + - parent + - version + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + read: + sql_driver: psycopg2 + sql_connect_args: *id001 + sql_password_env: VD_DIRECTUS_READER_PW + versions: + read: + kind: sql + sql_query: SELECT CAST(r."item" AS TEXT) AS "id", CAST(r."id" AS TEXT) AS "ver", + CAST(a."user" AS TEXT) AS "author" FROM "directus_revisions" r JOIN "directus_activity" + a ON a."id" = r."activity" WHERE r."collection" = 'tickets' + sql_driver: psycopg2 + sql_connect_args: *id001 + sql_password_env: VD_DIRECTUS_READER_PW + record_field: id + target_field: id + target_surface: record + version_field: ver + author_field: author + self: + - param: actor_id +provenance: + drafted_by: + model: claude-opus-5-5 + response_model: claude-opus-5-5 + effort: medium + prompt_version: verify-draft-prompt/2 + prompt_sha256: sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796 + inputs: + description: + kind: openapi + file_sha256: sha256:2be5c04f081d868272e9f198f707dfbf5a1e3fe61de5480b93bf83afea389018 + text_sha256: sha256:1cea058d8d45da073178f72590172487819d57b654925df4bf676c371897da2c + trace_sha256: sha256:07c664c7687d4c34f866219aa5ed8ff485d3aeb068c57eab9bafd0efcba295d1 + task_sha256: sha256:20e6582c1a1494720e2532a1722a0ca27dcf3d365a653a6eaffe11855be4b4a0 + admission: + suite: openadapt.verify-draft-admission/v1 + check_sha256: sha256:7edf764a8c51bf3c4b211d2fb47c10923d2eea0c92cdbca2deaa66d27fdaa33e + rounds: 2 + admitted_at: '2026-11-21T08:36:41Z' + recheck_window_tested_s: 2.0 + faults: + wrong_value:priority: refuted + wrong_value:status: refuted + wrong_row: refuted + duplicate: refuted + sibling_edit: refuted + late_revert: refuted + lost_update: refuted + clean_writes_confirmed: 5 + attribution_probe_writes: 5 + bookkeeping_confirmed_by_person: [] diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/report.json b/packages/flow/benchmark/verify_draft/results/directus/draft/report.json new file mode 100644 index 0000000000..6a6444e649 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/report.json @@ -0,0 +1,30 @@ +{ + "admitted": true, + "rounds": 2, + "person_decisions": 0, + "seconds": 359.9, + "model_usd": 0.1717, + "reason": "admitted", + "contract": "benchmark/verify_draft/results/directus/draft/contract.yaml", + "questions": [], + "rounds_detail": [ + { + "admitted": false, + "cases": 17, + "passed": 17, + "failed": [], + "problems": [], + "attribution_problems": [ + "directus_users.last_access" + ] + }, + { + "admitted": true, + "cases": 17, + "passed": 17, + "failed": [], + "problems": [], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..d0d1b6d792 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.admission.json @@ -0,0 +1,527 @@ +{ + "admitted": false, + "check_sha256": "sha256:c8c4754efb488390da8284af8fa30e8a113e5178158bf7cb4509de344e66e81b", + "problems": [], + "masked": [], + "seconds": 182.4, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.22 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.1 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.02 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.96 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.88 + }, + { + "group": "fault", + "name": "wrong_value:priority", + "detail": "tickets.priority holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.38 + }, + { + "group": "fault", + "name": "wrong_value:status", + "detail": "tickets.status holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.38 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another tickets row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.32 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the tickets record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "added", + "columns": [ + "id", + "note", + "priority", + "status", + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.3 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another tickets row's title edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.18 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the tickets write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 8.41 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "lost update: another user saved a version of the target inside the window, so the agent's save may have overwritten it", + "2 record(s) outside the declared write moved (added); 2 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "revision", + "change": "added" + }, + { + "row": true, + "table": "directus_revisions", + "change": "added", + "columns": [ + "activity", + "collection", + "data", + "delta", + "id", + "item" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 37.59 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 19.99 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.77 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.2 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 6.65 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 5.2 + } + ], + "attribution": [ + { + "table": "directus_activity", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "directus_activity", + "column": "action", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "collection", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "ip", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "item", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "origin", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "timestamp", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "user", + "cause": "actor", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "user_agent", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "activity", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "collection", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "data", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "delta", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "item", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "parent", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "version", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "tickets", + "column": "priority", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "tickets", + "column": "status", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "directus_users", + "column": "last_access", + "cause": "never moved", + "excluded": true, + "problem": "excluded, but it never moved in any probe write: nothing to excuse" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..d648b88e41 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-1.yaml @@ -0,0 +1 @@ +{"schema_version":"openadapt.verify/v1","verifier":{"kind":"surfaces","surfaces":{"record":{"kind":"sql","sql_query":"SELECT CAST(t.\"id\" AS TEXT) AS \"id\", CAST(t.\"title\" AS TEXT) AS \"title\", CAST(t.\"status\" AS TEXT) AS \"status\", CAST(t.\"priority\" AS TEXT) AS \"priority\", CAST(t.\"note\" AS TEXT) AS \"note\" FROM \"tickets\" t"},"revision":{"kind":"sql","sql_query":"SELECT CAST(r.\"id\" AS TEXT) AS \"id\", CAST(r.\"collection\" AS TEXT) AS \"collection\", CAST(r.\"item\" AS TEXT) AS \"item\", CAST(a.\"action\" AS TEXT) AS \"action\", CAST(a.\"user\" AS TEXT) AS \"user\" FROM \"directus_revisions\" r JOIN \"directus_activity\" a ON a.\"id\" = r.\"activity\""}}},"effects":[{"kind":"record_written","probe":"surface=record|ticket has the new status and priority","match":{"id":{"param":"ticket_id"},"status":{"param":"status"},"priority":{"param":"priority"}},"expected_count":1},{"kind":"record_written","probe":"surface=revision|one new update revision of this ticket by the actor","match":{"collection":{"literal":"tickets"},"item":{"param":"ticket_id"},"action":{"literal":"update"},"user":{"param":"actor_id"}},"expected_count":1,"count_new_only":true}],"frame":{"identity_field":"id","target_fields_by_surface":{"record":["status","priority"]},"database":{"dialect":"postgresql","allow_tables":[{"table":"directus_activity","mode":"append_only","reason":"Directus appends an activity row for every sign-in and every save; the save's revision (joined to its activity) is checked as an effect"},{"table":"directus_sessions","mode":"skip","reason":"auth session tokens created/refreshed on sign-in"}],"ignore_columns":{"directus_users":["last_access"]},"views":{"tickets":"record"},"judged_by":{"directus_revisions":"revision"},"new_row_fields":{"directus_revisions":["id","activity","data","delta","parent","version"]},"settle_s":1,"settle_attempts":3,"recheck_after_s":300},"versions":{"read":{"kind":"sql","sql_query":"SELECT CAST(r.\"item\" AS TEXT) AS \"id\", CAST(r.\"id\" AS TEXT) AS \"ver\", CAST(a.\"user\" AS TEXT) AS \"author\" FROM \"directus_revisions\" r JOIN \"directus_activity\" a ON a.\"id\" = r.\"activity\" WHERE r.\"collection\" = 'tickets'"},"record_field":"id","target_field":"id","target_surface":"record","version_field":"ver","author_field":"author","self":[{"param":"actor_id"}]}}} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.admission.json b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.admission.json new file mode 100644 index 0000000000..c7ec131d33 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.admission.json @@ -0,0 +1,520 @@ +{ + "admitted": true, + "check_sha256": "sha256:7edf764a8c51bf3c4b211d2fb47c10923d2eea0c92cdbca2deaa66d27fdaa33e", + "problems": [], + "masked": [], + "seconds": 129.09, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.83 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.96 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 9.66 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.22 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.9 + }, + { + "group": "fault", + "name": "wrong_value:priority", + "detail": "tickets.priority holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.54 + }, + { + "group": "fault", + "name": "wrong_value:status", + "detail": "tickets.status holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.05 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another tickets row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 10.98 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the tickets record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "added", + "columns": [ + "id", + "note", + "priority", + "status", + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.03 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another tickets row's title edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.52 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the tickets write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 8.19 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "lost update: another user saved a version of the target inside the window, so the agent's save may have overwritten it", + "2 record(s) outside the declared write moved (added); 2 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "revision", + "change": "added" + }, + { + "row": true, + "table": "directus_revisions", + "change": "added", + "columns": [ + "activity", + "collection", + "data", + "delta", + "id", + "item" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.03 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 5.54 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 5.69 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 5.28 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 5.54 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 5.33 + } + ], + "attribution": [ + { + "table": "directus_activity", + "column": "+", + "cause": "constant", + "excluded": true, + "problem": "" + }, + { + "table": "directus_activity", + "column": "action", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "collection", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "ip", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "item", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "origin", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "timestamp", + "cause": "clock", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "user", + "cause": "actor", + "excluded": false, + "problem": "" + }, + { + "table": "directus_activity", + "column": "user_agent", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "activity", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "collection", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "data", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "delta", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "item", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "parent", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "directus_revisions", + "column": "version", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "tickets", + "column": "priority", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "tickets", + "column": "status", + "cause": "payload", + "excluded": false, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.yaml b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.yaml new file mode 100644 index 0000000000..4ef24e4d2d --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/rounds/round-2.yaml @@ -0,0 +1 @@ +{"schema_version":"openadapt.verify/v1","verifier":{"kind":"surfaces","surfaces":{"record":{"kind":"sql","sql_query":"SELECT CAST(t.\"id\" AS TEXT) AS \"id\", CAST(t.\"title\" AS TEXT) AS \"title\", CAST(t.\"status\" AS TEXT) AS \"status\", CAST(t.\"priority\" AS TEXT) AS \"priority\", CAST(t.\"note\" AS TEXT) AS \"note\" FROM \"tickets\" t"},"revision":{"kind":"sql","sql_query":"SELECT CAST(r.\"id\" AS TEXT) AS \"id\", CAST(r.\"collection\" AS TEXT) AS \"collection\", CAST(r.\"item\" AS TEXT) AS \"item\", CAST(a.\"action\" AS TEXT) AS \"action\", CAST(a.\"user\" AS TEXT) AS \"user\" FROM \"directus_revisions\" r JOIN \"directus_activity\" a ON a.\"id\" = r.\"activity\""}}},"effects":[{"kind":"record_written","probe":"surface=record|ticket has the new status and priority","match":{"id":{"param":"ticket_id"},"status":{"param":"status"},"priority":{"param":"priority"}},"expected_count":1},{"kind":"record_written","probe":"surface=revision|one new update revision of this ticket by the actor","match":{"collection":{"literal":"tickets"},"item":{"param":"ticket_id"},"action":{"literal":"update"},"user":{"param":"actor_id"}},"expected_count":1,"count_new_only":true}],"frame":{"identity_field":"id","target_fields_by_surface":{"record":["status","priority"]},"database":{"dialect":"postgresql","allow_tables":[{"table":"directus_activity","mode":"append_only","reason":"Directus appends an activity row for every sign-in and every save; the save's revision (joined to its activity) is checked as an effect"},{"table":"directus_sessions","mode":"skip","reason":"auth session tokens created/refreshed on sign-in"}],"views":{"tickets":"record"},"judged_by":{"directus_revisions":"revision"},"new_row_fields":{"directus_revisions":["id","activity","data","delta","parent","version"]},"settle_s":1,"settle_attempts":3,"recheck_after_s":300},"versions":{"read":{"kind":"sql","sql_query":"SELECT CAST(r.\"item\" AS TEXT) AS \"id\", CAST(r.\"id\" AS TEXT) AS \"ver\", CAST(a.\"user\" AS TEXT) AS \"author\" FROM \"directus_revisions\" r JOIN \"directus_activity\" a ON a.\"id\" = r.\"activity\" WHERE r.\"collection\" = 'tickets'"},"record_field":"id","target_field":"id","target_surface":"record","version_field":"ver","author_field":"author","self":[{"param":"actor_id"}]}}} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/directus/result.json b/packages/flow/benchmark/verify_draft/results/directus/result.json new file mode 100644 index 0000000000..d63b0d0138 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/result.json @@ -0,0 +1,439 @@ +{ + "app": "directus", + "untuned": true, + "describe": "openapi", + "operator_setup_seconds": 1.8, + "operator_inputs": [ + "app base URL", + "two users' sign-in (email, password env)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 6.0, + "person_decisions": 0, + "questions": [], + "drafts": 2, + "drafts_admitted": 1, + "drafts_rejected": 1, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", + "model_usd": 0.1717, + "model_calls": [ + { + "at": 1795249874.283477, + "label": "directus", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 6762, + "output_tokens": 3260, + "cache_read_tokens": 2172, + "cache_write_tokens": 0, + "usd": 0.092682, + "seconds": 27.95, + "request_id": "", + "stop_reason": "end_turn" + }, + { + "at": 1795250072.8052962, + "label": "directus", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 8930, + "output_tokens": 2144, + "cache_read_tokens": 2172, + "cache_write_tokens": 0, + "usd": 0.079034, + "seconds": 16.08, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": false, + "faults_applicable": 7, + "faults_caught": 7, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [ + "directus_users.last_access: excluded, but it never moved in any probe write: nothing to excuse" + ], + "not_applicable": {}, + "seconds": 182.4 + }, + { + "admitted": true, + "faults_applicable": 7, + "faults_caught": 7, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": {}, + "seconds": 129.09 + } + ], + "notes": [], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.47 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.01 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 8.21 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.95 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 7.98 + }, + { + "group": "fault", + "name": "wrong_value:priority", + "detail": "tickets.priority holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 10.84 + }, + { + "group": "fault", + "name": "wrong_value:status", + "detail": "tickets.status holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.46 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another tickets row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 11.16 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the tickets record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "added", + "columns": [ + "id", + "note", + "priority", + "status", + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.53 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another tickets row's title edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "title" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.37 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the tickets write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 8.77 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "lost update: another user saved a version of the target inside the window, so the agent's save may have overwritten it", + "3 record(s) outside the declared write moved (added, changed); 3 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "revision", + "change": "added" + }, + { + "row": true, + "table": "directus_revisions", + "change": "added", + "columns": [ + "activity", + "collection", + "data", + "delta", + "id", + "item" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "directus_users", + "change": "changed", + "columns": [ + "last_access" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.38 + }, + { + "group": "fault", + "name": "app_sibling", + "detail": "the same write also sent to {'ticket_id': '3'} through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "3 record(s) outside the declared write moved (added, changed); 3 of them no actor explains" + ], + "moved": [ + { + "row": false, + "table": "revision", + "change": "added" + }, + { + "row": true, + "table": "directus_revisions", + "change": "added", + "columns": [ + "activity", + "collection", + "data", + "delta", + "id", + "item" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + }, + { + "row": true, + "table": "tickets", + "change": "changed", + "columns": [ + "priority", + "status" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 5.04 + } + ], + "faults_applicable": 8, + "faults_caught": 8, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/directus/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/directus/setup/sandbox.yaml new file mode 100644 index 0000000000..5711461fb5 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/setup/sandbox.yaml @@ -0,0 +1,40 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:9664 +actors: + agent: + id: 13a3e1e0-c049-443d-a2ea-fd7dc313af3e + login: + method: POST + path: /auth/login + token_field: data.access_token + json: + email: admin@example.org + password: ${VD_DIRECTUS_ADMIN_PW} + other: + id: 8b6660df-20b7-4305-8d6d-6af19b198ae1 + login: + method: POST + path: /auth/login + token_field: data.access_token + json: + email: editor@example.org + password: ${VD_DIRECTUS_EDITOR_PW} +store: + dialect: postgresql + read: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: directus + user: vd_reader + sql_password_env: VD_DIRECTUS_READER_PW + admin: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9665 + dbname: directus + user: directus + sql_password_env: VD_DIRECTUS_PG_PW diff --git a/packages/flow/benchmark/verify_draft/results/directus/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/directus/setup/task.yaml new file mode 100644 index 0000000000..853a7243d1 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/setup/task.yaml @@ -0,0 +1,5 @@ +instruction: Set ticket 2 to status 'in_progress' with priority 3. +params: + ticket_id: '2' + status: in_progress + priority: '3' diff --git a/packages/flow/benchmark/verify_draft/results/directus/setup/trace.har b/packages/flow/benchmark/verify_draft/results/directus/setup/trace.har new file mode 100644 index 0000000000..dcf65d6837 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/directus/setup/trace.har @@ -0,0 +1,92 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:9664/items/tickets/2", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json; charset=utf-8", + "text": "{\"data\":{\"id\":2,\"title\":\"VPN drops every hour\",\"status\":\"open\",\"priority\":1,\"note\":\"Seed two\"}}" + } + } + }, + { + "request": { + "method": "PATCH", + "url": "http://127.0.0.1:9664/items/tickets/2", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Authorization", + "value": "REDACTED" + }, + { + "name": "Content-Length", + "value": "40" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ], + "postData": { + "mimeType": "application/json", + "text": "{\"status\": \"in_progress\", \"priority\": 3}" + } + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json; charset=utf-8", + "text": "{\"data\":{\"id\":2,\"title\":\"VPN drops every hour\",\"status\":\"in_progress\",\"priority\":3,\"note\":\"Seed two\"}}" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan.log b/packages/flow/benchmark/verify_draft/results/mockloan.log new file mode 100644 index 0000000000..9f9782afc3 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan.log @@ -0,0 +1,437 @@ +[mockloan] store: 2 tables; trace: 1 write request(s) +[mockloan] demonstration: added records, columns ['amount', 'loan_id', 'memo', 'product'] +[mockloan] round 1: ADMITTED (19/19 cases, 67s) +{ + "app": "mockloan", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 0.0, + "operator_inputs": [ + "app base URL", + "SQLite file path (read and admin)" + ], + "setup_minutes": 1.39, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", + "model_usd": 0.0477, + "rounds": [ + { + "admitted": true, + "faults_applicable": 8, + "faults_caught": 8, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the write creates a record; nothing can be overwritten" + }, + "seconds": 66.95 + } + ], + "notes": [ + "MockLoan has no sign-in: the two actors send identical requests" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.88 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.02 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "fault", + "name": "wrong_value:amount", + "detail": "records.amount holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.02 + }, + { + "group": "fault", + "name": "wrong_value:loan_id", + "detail": "records.loan_id holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.04 + }, + { + "group": "fault", + "name": "wrong_value:memo", + "detail": "records.memo holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "wrong_value:product", + "detail": "records.product holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the new records row is filed under another loan_id", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.19 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the records record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another records row's loan_id edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "changed", + "columns": [ + "loan_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.02 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the records write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (removed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.08 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "untestable": false, + "note": "the write creates a record; nothing can be overwritten", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "fault", + "name": "app_sibling", + "detail": "the same write also sent to {'loan_id': 'LN-1002'} through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.05 + }, + { + "group": "fault", + "name": "app_duplicate", + "detail": "the write sent twice through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.26 + } + ], + "faults_applicable": 10, + "faults_caught": 10, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml new file mode 100644 index 0000000000..e4bf19ee9b --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/contract.yaml @@ -0,0 +1,83 @@ +# Drafted by a model and admitted by OpenAdapt qualification (openadapt verify draft). Runs make no model calls. +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."loan_id" AS TEXT) AS + "loan_id", CAST(t."product" AS TEXT) AS "product", CAST(t."amount" AS TEXT) + AS "amount", CAST(t."memo" AS TEXT) AS "memo", CAST(t."source" AS TEXT) AS + "source", CAST(t."record_key" AS TEXT) AS "record_key", CAST(t."surface" AS + TEXT) AS "surface" FROM "records" t + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-3eflo654/ledger.sqlite3 +effects: +- kind: record_written + probe: surface=record|one new disbursement row for the loan with the authorized + amount and memo + match: + loan_id: + param: loan_id + product: + param: product + amount: + param: amount + memo: + param: memo + surface: + literal: disbursements + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: [] + database: + dialect: sqlite + allow_tables: [] + ignore_columns: {} + views: + records: record + new_row_fields: + records: + - id + - source + - record_key + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + read: + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-3eflo654/ledger.sqlite3 +provenance: + drafted_by: + model: claude-opus-5-5 + response_model: claude-opus-5-5 + effort: medium + prompt_version: verify-draft-prompt/2 + prompt_sha256: sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796 + inputs: + description: + kind: database + file_sha256: null + text_sha256: sha256:c7f7799fc546b02f8effe2dcdbdb61cc87ab763ffbd609cb1fad04e215d670ac + trace_sha256: sha256:10b15ccea9db84574818f327250a15936cccae5af72687edd747342f392303e9 + task_sha256: sha256:5138e45fc7e532b1fb3abe9d915118eadf1e98e1e659cf6a7abb27bc179e01d9 + admission: + suite: openadapt.verify-draft-admission/v1 + check_sha256: sha256:bb9419bb5974566cb6f1d00bc854801d33f55130cd6463a4ae329ce3ed9cfbe9 + rounds: 1 + admitted_at: '2026-11-21T08:27:52Z' + recheck_window_tested_s: 2.0 + faults: + wrong_value:amount: refuted + wrong_value:loan_id: refuted + wrong_value:memo: refuted + wrong_value:product: refuted + wrong_row: refuted + duplicate: refuted + sibling_edit: refuted + late_revert: refuted + lost_update: 'not applicable: the write creates a record; nothing can be overwritten' + clean_writes_confirmed: 5 + attribution_probe_writes: 5 + bookkeeping_confirmed_by_person: [] diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json b/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json new file mode 100644 index 0000000000..038e12387b --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json @@ -0,0 +1,20 @@ +{ + "admitted": true, + "rounds": 1, + "person_decisions": 0, + "seconds": 83.2, + "model_usd": 0.0477, + "reason": "admitted", + "contract": "benchmark/verify_draft/results/mockloan/draft/contract.yaml", + "questions": [], + "rounds_detail": [ + { + "admitted": true, + "cases": 19, + "passed": 19, + "failed": [], + "problems": [], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..54aee7b5f8 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json @@ -0,0 +1,482 @@ +{ + "admitted": true, + "check_sha256": "sha256:bb9419bb5974566cb6f1d00bc854801d33f55130cd6463a4ae329ce3ed9cfbe9", + "problems": [], + "masked": [], + "seconds": 66.95, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.85 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.01 + }, + { + "group": "fault", + "name": "wrong_value:amount", + "detail": "records.amount holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "wrong_value:loan_id", + "detail": "records.loan_id holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.17 + }, + { + "group": "fault", + "name": "wrong_value:memo", + "detail": "records.memo holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.2 + }, + { + "group": "fault", + "name": "wrong_value:product", + "detail": "records.product holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.19 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the new records row is filed under another loan_id", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.18 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the records record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.03 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another records row's loan_id edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "changed", + "columns": [ + "loan_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.02 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the records write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (removed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 4.0 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "untestable": false, + "note": "the write creates a record; nothing can be overwritten", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.02 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.02 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.02 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.02 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.02 + } + ], + "attribution": [ + { + "table": "records", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "amount", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "loan_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "memo", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "product", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "record_key", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "source", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "records", + "column": "surface", + "cause": "constant", + "excluded": false, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..bd7d8fbde5 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml @@ -0,0 +1 @@ +{"schema_version":"openadapt.verify/v1","verifier":{"kind":"surfaces","surfaces":{"record":{"kind":"sql","sql_query":"SELECT CAST(t.\"id\" AS TEXT) AS \"id\", CAST(t.\"loan_id\" AS TEXT) AS \"loan_id\", CAST(t.\"product\" AS TEXT) AS \"product\", CAST(t.\"amount\" AS TEXT) AS \"amount\", CAST(t.\"memo\" AS TEXT) AS \"memo\", CAST(t.\"source\" AS TEXT) AS \"source\", CAST(t.\"record_key\" AS TEXT) AS \"record_key\", CAST(t.\"surface\" AS TEXT) AS \"surface\" FROM \"records\" t"}}},"effects":[{"kind":"record_written","probe":"surface=record|one new disbursement row for the loan with the authorized amount and memo","match":{"loan_id":{"param":"loan_id"},"product":{"param":"product"},"amount":{"param":"amount"},"memo":{"param":"memo"},"surface":{"literal":"disbursements"}},"expected_count":1,"count_new_only":true}],"frame":{"identity_field":"id","target_fields_by_surface":{"record":[]},"database":{"dialect":"sqlite","allow_tables":[],"ignore_columns":{},"views":{"records":"record"},"new_row_fields":{"records":["id","source","record_key"]},"settle_s":1,"settle_attempts":3,"recheck_after_s":300}}} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/result.json b/packages/flow/benchmark/verify_draft/results/mockloan/result.json new file mode 100644 index 0000000000..cf6a939ad8 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/result.json @@ -0,0 +1,450 @@ +{ + "app": "mockloan", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 0.0, + "operator_inputs": [ + "app base URL", + "SQLite file path (read and admin)" + ], + "setup_minutes": 1.39, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", + "model_usd": 0.0477, + "model_calls": [ + { + "at": 1795249605.1276119, + "label": "mockloan", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 583, + "output_tokens": 1726, + "cache_read_tokens": 0, + "cache_write_tokens": 2172, + "usd": 0.047712, + "seconds": 15.98, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": true, + "faults_applicable": 8, + "faults_caught": 8, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the write creates a record; nothing can be overwritten" + }, + "seconds": 66.95 + } + ], + "notes": [ + "MockLoan has no sign-in: the two actors send identical requests" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.88 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.0 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.02 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "fault", + "name": "wrong_value:amount", + "detail": "records.amount holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.02 + }, + { + "group": "fault", + "name": "wrong_value:loan_id", + "detail": "records.loan_id holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.04 + }, + { + "group": "fault", + "name": "wrong_value:memo", + "detail": "records.memo holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.22 + }, + { + "group": "fault", + "name": "wrong_value:product", + "detail": "records.product holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the new records row is filed under another loan_id", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.19 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the records record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another records row's loan_id edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "changed", + "columns": [ + "loan_id" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.02 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the records write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (removed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.08 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "untestable": false, + "note": "the write creates a record; nothing can be overwritten", + "reasons": [], + "moved": [], + "seconds": 0.0 + }, + { + "group": "fault", + "name": "app_sibling", + "detail": "the same write also sent to {'loan_id': 'LN-1002'} through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "records", + "change": "added", + "columns": [ + "amount", + "id", + "loan_id", + "memo", + "product", + "source", + "surface" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.05 + }, + { + "group": "fault", + "name": "app_duplicate", + "detail": "the write sent twice through the app", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed conflicting, 2 of 1 expected record(s)" + ], + "moved": [], + "seconds": 6.26 + } + ], + "faults_applicable": 10, + "faults_caught": 10, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml new file mode 100644 index 0000000000..d8c2eb7c76 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/setup/sandbox.yaml @@ -0,0 +1,14 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:62303 +actors: + agent: + id: officer-a + other: + id: officer-b +store: + dialect: sqlite + read: + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-3eflo654/ledger.sqlite3 + admin: + sqlite_database: /var/folders/35/pqjnmmwx24d2mtf4frt5dhcc0000gn/T/openadapt-mockloan-3eflo654/ledger.sqlite3 diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml new file mode 100644 index 0000000000..dacee2d591 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/setup/task.yaml @@ -0,0 +1,7 @@ +instruction: Authorize a disbursement of 3150.00 on loan LN-2040 (Personal) with the + memo 'Kitchen repair advance'. +params: + loan_id: LN-2040 + product: Personal + amount: '3150.00' + memo: Kitchen repair advance diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har b/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har new file mode 100644 index 0000000000..a6b1d2a264 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/mockloan/setup/trace.har @@ -0,0 +1,84 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:62303/api/disbursements", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"records\": [{\"id\": 1, \"loan_id\": \"LN-1001\", \"product\": \"Personal\", \"amount\": \"2500.00\", \"memo\": \"Seed one\", \"source\": \"replay\", \"surface\": \"disbursements\", \"key\": null}, {\"id\": 2, \"loan_id\": \"LN-1002\", \"product\": \"Auto\", \"amount\": \"9100.00\", \"memo\": \"Seed two\", \"source\": \"replay\", \"surface\": \"disbursements\", \"key\": null}, {\"id\": 3, \"loan_id\": \"LN-1003\", \"product\": \"Home\", \"amount\": \"120000.00\", \"memo\": \"Seed three\", \"source\": \"replay\", \"surface\": \"disbursements\", \"key\": null}], \"rejected_writes\": 0}" + } + } + }, + { + "request": { + "method": "POST", + "url": "http://127.0.0.1:62303/api/disbursement", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Content-Length", + "value": "100" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ], + "postData": { + "mimeType": "application/json", + "text": "{\"loan_id\": \"LN-2040\", \"product\": \"Personal\", \"amount\": \"3150.00\", \"memo\": \"Kitchen repair advance\"}" + } + }, + "response": { + "status": 200, + "content": { + "mimeType": "application/json", + "text": "{\"ok\": true, \"id\": 4}" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/spend.jsonl b/packages/flow/benchmark/verify_draft/results/spend.jsonl index 61960e0960..41d21c8e7f 100644 --- a/packages/flow/benchmark/verify_draft/results/spend.jsonl +++ b/packages/flow/benchmark/verify_draft/results/spend.jsonl @@ -9,3 +9,7 @@ {"at": 1795247848.794942, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19909, "output_tokens": 2429, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.128647, "seconds": 22.47, "request_id": "", "stop_reason": "end_turn"} {"at": 1795247862.9125051, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 21727, "output_tokens": 1766, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.122659, "seconds": 13.98, "request_id": "", "stop_reason": "end_turn"} {"at": 1795248054.955477, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 23470, "output_tokens": 4549, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.185291, "seconds": 45.48, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795249605.1276119, "label": "mockloan", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 583, "output_tokens": 1726, "cache_read_tokens": 0, "cache_write_tokens": 2172, "usd": 0.047712, "seconds": 15.98, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795249617.893177, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 3252, "cache_read_tokens": 0, "cache_write_tokens": 2172, "usd": 0.078944, "seconds": 28.29, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795249874.283477, "label": "directus", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 6762, "output_tokens": 3260, "cache_read_tokens": 2172, "cache_write_tokens": 0, "usd": 0.092682, "seconds": 27.95, "request_id": "", "stop_reason": "end_turn"} +{"at": 1795250072.8052962, "label": "directus", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 8930, "output_tokens": 2144, "cache_read_tokens": 2172, "cache_write_tokens": 0, "usd": 0.079034, "seconds": 16.08, "request_id": "", "stop_reason": "end_turn"} diff --git a/packages/flow/benchmark/verify_draft/results/workbench.log b/packages/flow/benchmark/verify_draft/results/workbench.log new file mode 100644 index 0000000000..319bf781e3 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench.log @@ -0,0 +1,327 @@ +[workbench] store: 4 tables; trace: 1 write request(s) +[workbench] demonstration: changed patients, columns ['email', 'phone'] +[workbench] round 1: ADMITTED (17/17 cases, 51s) +{ + "app": "workbench", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 1.6, + "operator_inputs": [ + "app base URL", + "agent sign-in (user, password)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 1.32, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", + "model_usd": 0.0789, + "rounds": [ + { + "admitted": true, + "faults_applicable": 6, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the app refused the stale save: it prevents lost updates itself" + }, + "seconds": 50.89 + } + ], + "notes": [ + "the workbench signs in one user only: the second actor is a second session of it, so the lost-update case runs but the attribution probe has no real actor axis" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.15 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.03 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.26 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.74 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "fault", + "name": "wrong_value:email", + "detail": "patients.email holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.26 + }, + { + "group": "fault", + "name": "wrong_value:phone", + "detail": "patients.phone holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.8 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another patients row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.62 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the patients record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "added", + "columns": [ + "dob", + "email", + "first_name", + "id", + "last_name", + "mrn", + "phone", + "status", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.76 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another patients row's mrn edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "mrn" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.69 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the patients write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 4.08 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "untestable": false, + "note": "the app refused the stale save: it prevents lost updates itself", + "reasons": [], + "moved": [], + "seconds": 0.08 + } + ], + "faults_applicable": 6, + "faults_caught": 6, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml b/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml new file mode 100644 index 0000000000..6529c5ae91 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/contract.yaml @@ -0,0 +1,108 @@ +# Drafted by a model and admitted by OpenAdapt qualification (openadapt verify draft). Runs make no model calls. +schema_version: openadapt.verify/v1 +verifier: + kind: surfaces + surfaces: + record: + kind: sql + sql_query: SELECT CAST(p."id" AS TEXT) AS "id", CAST(p."mrn" AS TEXT) AS "mrn", + CAST(p."first_name" AS TEXT) AS "first_name", CAST(p."last_name" AS TEXT) + AS "last_name", CAST(p."dob" AS TEXT) AS "dob", CAST(p."phone" AS TEXT) AS + "phone", CAST(p."email" AS TEXT) AS "email", CAST(p."status" AS TEXT) AS "status", + CAST(p."merged_into" AS TEXT) AS "merged_into", CAST(p."version" AS TEXT) + AS "version", CAST(p."updated_by" AS TEXT) AS "updated_by" FROM "patients" + p + sql_driver: psycopg2 + sql_connect_args: &id001 + host: 127.0.0.1 + port: 9796 + dbname: wb_mockmed + user: wb_reader + audit: + kind: sql + sql_query: SELECT CAST(a."id" AS TEXT) AS "id", CAST(a."actor" AS TEXT) AS "actor", + CAST(a."table_name" AS TEXT) AS "table_name", CAST(a."record_id" AS TEXT) + AS "record_id", CAST(a."event" AS TEXT) AS "event", CAST(p."mrn" AS TEXT) + AS "mrn" FROM "audit_log" a JOIN "patients" p ON a."table_name" = 'patients' + AND a."record_id" = p."id" + sql_driver: psycopg2 + sql_connect_args: *id001 +effects: +- kind: record_written + probe: surface=record|patient by MRN has the new phone and email + match: + mrn: + param: mrn + phone: + param: phone + email: + param: email + expected_count: 1 +- kind: record_written + probe: surface=audit|exactly one new update audit row for this patient + match: + mrn: + param: mrn + table_name: + literal: patients + event: + literal: update + expected_count: 1 + count_new_only: true +frame: + identity_field: id + target_fields_by_surface: + record: + - phone + - email + - version + - updated_by + database: + dialect: postgresql + views: + patients: record + judged_by: + audit_log: audit + new_row_fields: + audit_log: + - id + - record_id + - actor + settle_s: 1 + settle_attempts: 3 + recheck_after_s: 300 + read: + sql_driver: psycopg2 + sql_connect_args: *id001 +provenance: + drafted_by: + model: claude-opus-5-5 + response_model: claude-opus-5-5 + effort: medium + prompt_version: verify-draft-prompt/2 + prompt_sha256: sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796 + inputs: + description: + kind: database + file_sha256: null + text_sha256: sha256:92cd3d4fdfe7b1bfefd0f4be2c402a7b16f7ff6abca24f498c730f38096b1026 + trace_sha256: sha256:64e748c9f56085c35918c2ed0325c475ac24710433847f1f1d1e28e984473db7 + task_sha256: sha256:40052528dbd5404c4c5c5688be9d1511b89e13ee461df22aa2a4f0faeef8e4ff + admission: + suite: openadapt.verify-draft-admission/v1 + check_sha256: sha256:0ef8a82f2a8c175a476243a1e165e2c1c2f1524d4b71c1cc5806bc63b63ad666 + rounds: 1 + admitted_at: '2026-11-21T08:27:48Z' + recheck_window_tested_s: 2.0 + faults: + wrong_value:email: refuted + wrong_value:phone: refuted + wrong_row: refuted + duplicate: refuted + sibling_edit: refuted + late_revert: refuted + lost_update: 'not applicable: the app refused the stale save: it prevents lost + updates itself' + clean_writes_confirmed: 5 + attribution_probe_writes: 5 + bookkeeping_confirmed_by_person: [] diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json b/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json new file mode 100644 index 0000000000..33bfd3ea95 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json @@ -0,0 +1,20 @@ +{ + "admitted": true, + "rounds": 1, + "person_decisions": 0, + "seconds": 79.4, + "model_usd": 0.0789, + "reason": "admitted", + "contract": "benchmark/verify_draft/results/workbench/draft/contract.yaml", + "questions": [], + "rounds_detail": [ + { + "admitted": true, + "cases": 17, + "passed": 17, + "failed": [], + "problems": [], + "attribution_problems": [] + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json new file mode 100644 index 0000000000..9eef2255c0 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json @@ -0,0 +1,429 @@ +{ + "admitted": true, + "check_sha256": "sha256:0ef8a82f2a8c175a476243a1e165e2c1c2f1524d4b71c1cc5806bc63b63ad666", + "problems": [], + "masked": [], + "seconds": 50.89, + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.12 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.02 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.26 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.75 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.97 + }, + { + "group": "fault", + "name": "wrong_value:email", + "detail": "patients.email holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.23 + }, + { + "group": "fault", + "name": "wrong_value:phone", + "detail": "patients.phone holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.21 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another patients row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.33 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the patients record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "added", + "columns": [ + "dob", + "email", + "first_name", + "id", + "last_name", + "mrn", + "phone", + "status", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.43 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another patients row's mrn edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "mrn" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.38 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the patients write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 3.41 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "untestable": false, + "note": "the app refused the stale save: it prevents lost updates itself", + "reasons": [], + "moved": [], + "seconds": 0.05 + }, + { + "group": "probe", + "name": "attribution:agent:p1", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.13 + }, + { + "group": "probe", + "name": "attribution:agent:p2", + "detail": "the write by agent with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.22 + }, + { + "group": "probe", + "name": "attribution:other:p1", + "detail": "the write by other with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.11 + }, + { + "group": "probe", + "name": "attribution:other:p2", + "detail": "the write by other with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.13 + }, + { + "group": "probe", + "name": "attribution:agent:p1-again", + "detail": "the write by agent with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 1.12 + } + ], + "attribution": [ + { + "table": "audit_log", + "column": "+", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "actor", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "event", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "id", + "cause": "fresh", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "record_id", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "audit_log", + "column": "table_name", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "email", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "phone", + "cause": "payload", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "updated_by", + "cause": "constant", + "excluded": false, + "problem": "" + }, + { + "table": "patients", + "column": "version", + "cause": "constant", + "excluded": false, + "problem": "" + } + ] +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml new file mode 100644 index 0000000000..f7d525f900 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml @@ -0,0 +1 @@ +{"schema_version":"openadapt.verify/v1","verifier":{"kind":"surfaces","surfaces":{"record":{"kind":"sql","sql_query":"SELECT CAST(p.\"id\" AS TEXT) AS \"id\", CAST(p.\"mrn\" AS TEXT) AS \"mrn\", CAST(p.\"first_name\" AS TEXT) AS \"first_name\", CAST(p.\"last_name\" AS TEXT) AS \"last_name\", CAST(p.\"dob\" AS TEXT) AS \"dob\", CAST(p.\"phone\" AS TEXT) AS \"phone\", CAST(p.\"email\" AS TEXT) AS \"email\", CAST(p.\"status\" AS TEXT) AS \"status\", CAST(p.\"merged_into\" AS TEXT) AS \"merged_into\", CAST(p.\"version\" AS TEXT) AS \"version\", CAST(p.\"updated_by\" AS TEXT) AS \"updated_by\" FROM \"patients\" p"},"audit":{"kind":"sql","sql_query":"SELECT CAST(a.\"id\" AS TEXT) AS \"id\", CAST(a.\"actor\" AS TEXT) AS \"actor\", CAST(a.\"table_name\" AS TEXT) AS \"table_name\", CAST(a.\"record_id\" AS TEXT) AS \"record_id\", CAST(a.\"event\" AS TEXT) AS \"event\", CAST(p.\"mrn\" AS TEXT) AS \"mrn\" FROM \"audit_log\" a JOIN \"patients\" p ON a.\"table_name\" = 'patients' AND a.\"record_id\" = p.\"id\""}}},"effects":[{"kind":"record_written","probe":"surface=record|patient by MRN has the new phone and email","match":{"mrn":{"param":"mrn"},"phone":{"param":"phone"},"email":{"param":"email"}},"expected_count":1},{"kind":"record_written","probe":"surface=audit|exactly one new update audit row for this patient","match":{"mrn":{"param":"mrn"},"table_name":{"literal":"patients"},"event":{"literal":"update"}},"expected_count":1,"count_new_only":true}],"frame":{"identity_field":"id","target_fields_by_surface":{"record":["phone","email","version","updated_by"]},"database":{"dialect":"postgresql","views":{"patients":"record"},"judged_by":{"audit_log":"audit"},"new_row_fields":{"audit_log":["id","record_id","actor"]},"settle_s":1,"settle_attempts":3,"recheck_after_s":300}}} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/result.json b/packages/flow/benchmark/verify_draft/results/workbench/result.json new file mode 100644 index 0000000000..95f9ea2a45 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/result.json @@ -0,0 +1,340 @@ +{ + "app": "workbench", + "untuned": false, + "describe": "db", + "operator_setup_seconds": 1.6, + "operator_inputs": [ + "app base URL", + "agent sign-in (user, password)", + "read-only DB connection", + "admin DB connection" + ], + "setup_minutes": 1.32, + "person_decisions": 0, + "questions": [], + "drafts": 1, + "drafts_admitted": 1, + "drafts_rejected": 0, + "admitted": true, + "reason": "admitted", + "model": "claude-opus-5-5", + "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", + "model_usd": 0.0789, + "model_calls": [ + { + "at": 1795249617.893177, + "label": "workbench", + "request_model": "claude-opus-5-5", + "response_model": "claude-opus-5-5", + "input_tokens": 761, + "output_tokens": 3252, + "cache_read_tokens": 0, + "cache_write_tokens": 2172, + "usd": 0.078944, + "seconds": 28.29, + "request_id": "", + "stop_reason": "end_turn" + } + ], + "rounds": [ + { + "admitted": true, + "faults_applicable": 6, + "faults_caught": 6, + "clean": 5, + "false_stops": [], + "probe_writes_confirmed": 5, + "attribution_problems": [], + "not_applicable": { + "lost_update": "the app refused the stale save: it prevents lost updates itself" + }, + "seconds": 50.89 + } + ], + "notes": [ + "the workbench signs in one user only: the second actor is a second session of it, so the lost-update case runs but the attribution probe has no real actor axis" + ], + "heldout": { + "cases": [ + { + "group": "clean", + "name": "clean-1", + "detail": "the write with payload 1", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.15 + }, + { + "group": "clean", + "name": "clean-2", + "detail": "the write with payload 2", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.03 + }, + { + "group": "clean", + "name": "clean-3", + "detail": "the write with payload 3", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 4.26 + }, + { + "group": "clean", + "name": "clean-4", + "detail": "the write with payload 4", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.74 + }, + { + "group": "clean", + "name": "clean-5", + "detail": "the write with payload 5", + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [], + "moved": [], + "seconds": 3.99 + }, + { + "group": "fault", + "name": "wrong_value:email", + "detail": "patients.email holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.26 + }, + { + "group": "fault", + "name": "wrong_value:phone", + "detail": "patients.phone holds another value", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.8 + }, + { + "group": "fault", + "name": "wrong_row", + "detail": "the update landed on another patients row", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "record_written was refuted: observed absent, 0 of 1 expected record(s)", + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "email", + "phone", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 6.62 + }, + { + "group": "fault", + "name": "duplicate", + "detail": "a second copy of the patients record", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (added); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "added", + "columns": [ + "dob", + "email", + "first_name", + "id", + "last_name", + "mrn", + "phone", + "status", + "updated_by", + "version" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.76 + }, + { + "group": "fault", + "name": "sibling_edit", + "detail": "another patients row's mrn edited beside the write", + "expect": "refuted", + "outcome": "REFUTED", + "recheck": "", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) outside the declared write moved (changed); 1 of them no actor explains" + ], + "moved": [ + { + "row": true, + "table": "patients", + "change": "changed", + "columns": [ + "mrn" + ], + "target": false, + "attribution": "unattributed", + "actor_columns": [] + } + ], + "seconds": 1.69 + }, + { + "group": "fault", + "name": "late_revert", + "detail": "the patients write undone after the check", + "expect": "refuted", + "outcome": "CONFIRMED", + "recheck": "REFUTED", + "passed": true, + "applicable": true, + "untestable": false, + "note": "", + "reasons": [ + "1 record(s) moved after the verdict that nothing explains (changed); the earlier CONFIRMED no longer stands" + ], + "moved": [], + "seconds": 4.08 + }, + { + "group": "fault", + "name": "lost_update", + "detail": "the other user saves the record, then the agent's save overwrites it", + "expect": "refuted", + "outcome": "", + "recheck": "", + "passed": true, + "applicable": false, + "untestable": false, + "note": "the app refused the stale save: it prevents lost updates itself", + "reasons": [], + "moved": [], + "seconds": 0.08 + } + ], + "faults_applicable": 6, + "faults_caught": 6, + "faults_missed": [], + "clean": 5, + "false_stops": [], + "problems": [] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml b/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml new file mode 100644 index 0000000000..ee24dd7e59 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/setup/sandbox.yaml @@ -0,0 +1,36 @@ +schema_version: openadapt.verify-sandbox/v1 +app: + base_url: http://127.0.0.1:62324 +actors: + agent: + id: clinician + login: + method: POST + path: /login + form: + username: clinician + password: synthetic + other: + id: clinician + login: + method: POST + path: /login + form: + username: clinician + password: synthetic +store: + dialect: postgresql + read: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9796 + dbname: wb_mockmed + user: wb_reader + admin: + sql_driver: psycopg2 + sql_connect_args: + host: 127.0.0.1 + port: 9796 + dbname: wb_mockmed + user: wb_admin diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml b/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml new file mode 100644 index 0000000000..76c4cbc1b9 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/setup/task.yaml @@ -0,0 +1,5 @@ +instruction: Update patient MRN-1002's phone to 555-0177 and email to b.okafor@clinic.example.org. +params: + mrn: MRN-1002 + phone: 555-0177 + email: b.okafor@clinic.example.org diff --git a/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har b/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har new file mode 100644 index 0000000000..c575aff468 --- /dev/null +++ b/packages/flow/benchmark/verify_draft/results/workbench/setup/trace.har @@ -0,0 +1,135 @@ +{ + "log": { + "version": "1.2", + "creator": { + "name": "verify-draft-bench" + }, + "entries": [ + { + "request": { + "method": "POST", + "url": "http://127.0.0.1:62324/login", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Content-Length", + "value": "37" + }, + { + "name": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "text": "username=clinician&password=synthetic" + } + }, + "response": { + "status": 303, + "content": { + "mimeType": "", + "text": "" + } + } + }, + { + "request": { + "method": "GET", + "url": "http://127.0.0.1:62324/e/patient/2/edit", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Cookie", + "value": "REDACTED" + } + ] + }, + "response": { + "status": 200, + "content": { + "mimeType": "text/html; charset=utf-8", + "text": "Edit Ben Okafor - MockMed
MockMedPatientsSigned in as clinician Sign out

Edit Ben Okafor

" + } + } + }, + { + "request": { + "method": "POST", + "url": "http://127.0.0.1:62324/e/patient/2/edit", + "headers": [ + { + "name": "User-Agent", + "value": "python-requests/2.34.2" + }, + { + "name": "Accept-Encoding", + "value": "gzip, deflate" + }, + { + "name": "Accept", + "value": "*/*" + }, + { + "name": "Connection", + "value": "keep-alive" + }, + { + "name": "Cookie", + "value": "REDACTED" + }, + { + "name": "Content-Length", + "value": "109" + }, + { + "name": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "text": "__version=1&first_name=Ben&last_name=Okafor&dob=1975-07-30&phone=555-0177&email=b.okafor%40clinic.example.org" + } + }, + "response": { + "status": 303, + "content": { + "mimeType": "", + "text": "" + } + } + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/docs/VERIFY_DRAFT.md b/packages/flow/docs/VERIFY_DRAFT.md index d824a632d4..69195d8cf9 100644 --- a/packages/flow/docs/VERIFY_DRAFT.md +++ b/packages/flow/docs/VERIFY_DRAFT.md @@ -206,4 +206,4 @@ send a call that could pass `--spend-cap-usd` (default 30). fault the store can't express this way, such as an email sent, is outside the contract's read. -Measured on three apps: [benchmark/verify_draft/RESULTS.md](../benchmark/verify_draft/RESULTS.md). +Measured on four apps, two of them never set up before: [benchmark/verify_draft/RESULTS.md](../benchmark/verify_draft/RESULTS.md). From 8969f49b02477c5cf91998bf992bd59084e5287e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:41:05 -0500 Subject: [PATCH 05/14] docs: CAPABILITIES row links #2438; refresh llms-full --- llms-full.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/llms-full.txt b/llms-full.txt index 97d38a6b7c..82dafb9418 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -600,6 +600,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR (MEASURE_PLACEHOLDER) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | From b837cf54ab11f2d9d0aa8de3b3c3c7333503a6c5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:41:16 -0500 Subject: [PATCH 06/14] docs: CAPABILITIES row links #2438 --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 4654018a48..562f592dcc 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -166,7 +166,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR (MEASURE_PLACEHOLDER) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/llms-full.txt b/llms-full.txt index 82dafb9418..7ad64d8c29 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -600,7 +600,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR (MEASURE_PLACEHOLDER) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | From 946316ca061ebf33a1653e8a3c84655f7233f43e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:49:24 -0500 Subject: [PATCH 07/14] fix(verify): verify draft signs actors in before the first read, refuses an unmoved table exclusion, masks secret columns, uses httpx --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../flow/benchmark/verify_draft/RESULTS.md | 28 ++++++++++--- packages/flow/benchmark/verify_draft/run.py | 1 + packages/flow/docs/VERIFY_DRAFT.md | 24 ++++++++++-- .../flow/openadapt_flow/verify_draft/admit.py | 24 ++++++++---- .../flow/openadapt_flow/verify_draft/draft.py | 1 + .../openadapt_flow/verify_draft/sandbox.py | 25 ++++++++---- packages/flow/tests/test_verify_draft.py | 39 +++++++++++++++++++ 9 files changed, 120 insertions(+), 26 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 562f592dcc..7ae207a35f 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -166,7 +166,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions (round 1 was lost because a sign-in fell inside the measured window; fixed after the run, not rerun), 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/llms-full.txt b/llms-full.txt index 7ad64d8c29..f4cf678183 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -600,7 +600,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. Not yet: OpenAPI metadata | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions, 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions (round 1 was lost because a sign-in fell inside the measured window; fixed after the run, not rerun), 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/packages/flow/benchmark/verify_draft/RESULTS.md b/packages/flow/benchmark/verify_draft/RESULTS.md index fff7f77194..c211f5b557 100644 --- a/packages/flow/benchmark/verify_draft/RESULTS.md +++ b/packages/flow/benchmark/verify_draft/RESULTS.md @@ -19,8 +19,10 @@ browser-free and headless. Raw data for every run, void or not, is under - **Mealie, first valid run: 9.2 minutes, and no contract was admitted.** - **Directus, reported run: 6.0 minutes**, admitted in round 2. The first draft passed every planted fault and every clean write. Round 1 was lost - only to a rule stricter than the brief, which refuses an exclusion that - never moved (below). + to a qualifier bug found in review after the run. The agent signed in + inside the demonstration's window, so the model was shown the sign-in's + rows as part of the write and excluded `last_access`. The probe, signed in + by then, never saw it move (below). The other two clauses do not fire: @@ -111,9 +113,25 @@ added. table skipped. All 17 cases passed in round 1, including the lost update. The draft was -rejected only because it also excluded `directus_users.last_access`. That -column moves at sign-in, not during a write, so it never moved in a probe. -Round 2 dropped that exclusion and was admitted. Held out, the contract +rejected only because it also excluded `directus_users.last_access`, which +then never moved in a probe write. + +That exclusion came from a qualifier bug, found in review after the run. +Actors signed in lazily, so the agent's sign-in fell inside the +demonstration replay. The model was shown the rows a sign-in writes as part +of the write: a session, the sign-in activity row and `last_access`. + +Round 2 dropped the `last_access` exclusion and was admitted. It kept +`directus_sessions: skip`. A whole-table exclusion that never moved was not +checked then. It is now, so the committed contract would be refused today. +Since the run, every actor signs in before the store is first read, and a +skipped or append-only table that never moved in the probe is refused. + +The lost-update catch was checked in the case evidence. In round 2 and held +out, the first reason is `frame.versions`: "another user saved a version of +the target inside the window". In the held-out run the other user's sign-in +also moved `last_access` inside the window, for the same reason. A post-fix +Directus rerun was not made. Held out, the contract refuted all 8 applicable faults: - the faults planted on another ticket with other values; diff --git a/packages/flow/benchmark/verify_draft/run.py b/packages/flow/benchmark/verify_draft/run.py index 4b75d875ea..1b5408abcb 100644 --- a/packages/flow/benchmark/verify_draft/run.py +++ b/packages/flow/benchmark/verify_draft/run.py @@ -42,6 +42,7 @@ def heldout(run: AppRun, contract_path: Path, work: Path) -> dict[str, Any]: from openadapt_flow.verify_draft.inputs import load_task, load_trace, writes task = load_task(run.task) + app.sign_in_all() base = store.read() demo = A.record_demo( store, diff --git a/packages/flow/docs/VERIFY_DRAFT.md b/packages/flow/docs/VERIFY_DRAFT.md index 69195d8cf9..c7dbd8cc76 100644 --- a/packages/flow/docs/VERIFY_DRAFT.md +++ b/packages/flow/docs/VERIFY_DRAFT.md @@ -93,10 +93,14 @@ no reset hook. ## What it does -1. **Record the demonstration.** The sandbox replays the trace's writes - once, between two reads of the store, to see which rows they move. The - model gets the rows and columns that moved, with their values. The - sandbox holds synthetic data only. +1. **Record the demonstration.** Every actor signs in first, before the + store is read, so the rows a sign-in writes (a session, a last-login + time) are starting state and never land inside a write's window. The + sandbox then replays the trace's writes once, between two reads of the + store, to see which rows they move. The model gets the rows and columns + that moved, with their values, except a secret-named column (password, + token, secret, key, hash), whose value is masked. The sandbox holds + synthetic data only. 2. **Draft.** The pinned model writes a contract, as JSON text, that diffs the whole database (`frame.database`). It also writes other valid values for the task to test with. The draft may only read the database with @@ -191,6 +195,18 @@ recorded too. Every call is appended to a spend ledger (`--spend-ledger`, default `~/.openadapt/verify-draft/spend.jsonl`). The command refuses to send a call that could pass `--spend-cap-usd` (default 30). +## Install + +The command runs from the engine (`pip install openadapt`, which installs +`openadapt-flow`). It talks to the app through `httpx`, a base dependency. +It also needs: + +- the Anthropic SDK, to draft: `pip install anthropic`; +- the store's DB-API driver, as any SQL contract does: `psycopg2-binary` + for PostgreSQL, or `pymysql` for MySQL and MariaDB. SQLite needs none. + +Without the SDK the command stops before drafting and says what to install. + ## Limits - The store must be SQLite, PostgreSQL or MySQL/MariaDB, reachable from the diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py index 17ba62be6b..bac445194b 100644 --- a/packages/flow/openadapt_flow/verify_draft/admit.py +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -145,6 +145,9 @@ "server_set", } ) +_SECRET_COLUMN = re.compile( + r"pass(word)?|secret|token|api[-_]?key|hash|salt|(^|_)(otp|tfa)(_|$)", re.I +) _IDENTIFIER = re.compile(r"(^|_)(id|key|no|number|code|slug|mrn|ref|uuid)$", re.I) @@ -324,7 +327,9 @@ def moved_text(self) -> str: cols = m.columns if m.change == "changed" else sorted(row or {}) vals = { c: ( - f"{text((m.before or {}).get(c))!r} -> {text((m.after or {}).get(c))!r}" + "***" # a secret-named column: its name, never its value + if _SECRET_COLUMN.search(c) + else f"{text((m.before or {}).get(c))!r} -> {text((m.after or {}).get(c))!r}" if m.change == "changed" else text((row or {}).get(c)) ) @@ -1158,18 +1163,23 @@ def _attribute( moved = {(a.table, a.column) for a in out} for table, masked_cols in mask.items(): for col in masked_cols: - if col == "*" and any(t == table for t, _ in moved): - continue - if col == "+" and (table, "+") in moved: - continue - if (table, col) not in moved and col not in ("*", "+"): + if col == "*": + unexcused = not any(t == table for t, _ in moved) + what = "a skipped table" + elif col == "+": + unexcused = (table, "+") not in moved + what = "an append-only table" + else: + unexcused = (table, col) not in moved + what = "excluded" + if unexcused: out.append( Attribution( table, col, "never moved", True, - "excluded, but it never moved in any probe write: nothing to excuse", + f"{what}, but it never moved in any probe write: nothing to excuse", ) ) return out, cases diff --git a/packages/flow/openadapt_flow/verify_draft/draft.py b/packages/flow/openadapt_flow/verify_draft/draft.py index 27245f3cf0..70667a142e 100644 --- a/packages/flow/openadapt_flow/verify_draft/draft.py +++ b/packages/flow/openadapt_flow/verify_draft/draft.py @@ -126,6 +126,7 @@ def run( raise I.InputError( f"the sandbox's read account can't read the whole database: {problem}" ) + app.sign_in_all() # before the first read: sign-in rows are starting state base = store.read() log(f"store: {len(store.tables)} tables; trace: {len(writes)} write request(s)") demo = A.record_demo(store, app, writes, task.params, base) diff --git a/packages/flow/openadapt_flow/verify_draft/sandbox.py b/packages/flow/openadapt_flow/verify_draft/sandbox.py index ea8cd5d368..8f972ce6f4 100644 --- a/packages/flow/openadapt_flow/verify_draft/sandbox.py +++ b/packages/flow/openadapt_flow/verify_draft/sandbox.py @@ -661,13 +661,18 @@ def login_paths(self) -> set[str]: return {a.login.path for a in self.cfg.actors.values() if a.login} def session(self, actor: str) -> Any: - import requests + """The actor's signed-in HTTP client (httpx, a base dependency).""" + + import httpx if actor in self._sessions: return self._sessions[actor] spec = self.cfg.actor(actor) - s = requests.Session() - s.headers.update(_expand(dict(spec.headers))) + s = httpx.Client( + headers=_expand(dict(spec.headers)), + timeout=self.cfg.app.timeout_s, + follow_redirects=False, + ) if spec.login is not None: login = spec.login url = self.cfg.app.base_url.rstrip("/") + login.path @@ -676,8 +681,6 @@ def session(self, actor: str) -> Any: url, data=_expand(login.form) if login.form else None, json=_expand(login.json_body) if login.json_body else None, - allow_redirects=False, - timeout=self.cfg.app.timeout_s, ) if r.status_code >= 400: raise SandboxError(f"actor {actor} could not sign in ({r.status_code})") @@ -693,6 +696,14 @@ def session(self, actor: str) -> Any: self._sessions[actor] = s return s + def sign_in_all(self) -> None: + """Sign every actor in now, before the store is first read, so the + rows a sign-in writes (a session, a last-login time) are part of the + starting state and never land inside a write's window.""" + + for name in self.cfg.actors: + self.session(name) + def send( self, writes: Sequence[Request], @@ -727,10 +738,8 @@ def send( r = s.request( req.method, url, - data=body.encode("utf-8") if isinstance(body, str) else body, + content=body.encode("utf-8") if isinstance(body, str) else body, headers=headers, - allow_redirects=False, - timeout=self.cfg.app.timeout_s, ) statuses.append(r.status_code) return statuses diff --git a/packages/flow/tests/test_verify_draft.py b/packages/flow/tests/test_verify_draft.py index f8fe7dc1f3..50bef43e33 100644 --- a/packages/flow/tests/test_verify_draft.py +++ b/packages/flow/tests/test_verify_draft.py @@ -443,3 +443,42 @@ def ask(question: str, columns: Any) -> dict[str, str]: calls.clear() outcome = _run(mockloan, Fixed(GOOD), rounds=1, ask=lambda q, c: None) assert not outcome.admitted and outcome.decisions == 0 + + +def test_actors_sign_in_before_the_store_is_read( + mockloan: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A sign-in that writes rows (a session, a last-login time) must be + starting state, never inside the demonstration's or a case's window.""" + + from openadapt_flow.verify_draft import sandbox as S + + events: list[str] = [] + real_session, real_read = S.App.session, S.Store.read + + def session(self: Any, actor: str) -> Any: + if actor not in self._sessions: + events.append(f"sign-in:{actor}") + return real_session(self, actor) + + def read(self: Any, tables: Any = None) -> Any: + events.append("read") + return real_read(self, tables) + + monkeypatch.setattr(S.App, "session", session) + monkeypatch.setattr(S.Store, "read", read) + _run(mockloan, Fixed("not: [valid"), rounds=1) + first_read = events.index("read") + assert {"sign-in:agent", "sign-in:other"} <= set(events[:first_read]) + + +@pytest.mark.timeout(300) +def test_a_skip_of_a_table_that_never_moves_is_refused(mockloan: Path) -> None: + skipping = GOOD.replace( + " dialect: sqlite\n", + " dialect: sqlite\n allow_tables:\n - {table: metadata, mode: skip, reason: counters}\n", + ) + outcome = _run(mockloan, Fixed(skipping), rounds=1) + assert not outcome.admitted + problems = [a for a in outcome.admissions[0].attribution if a.problem] + assert any(a.table == "metadata" and "skipped table" in a.problem for a in problems) From fdd364c0d3b567353b64ef4f674a65678885e8f5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:21:36 -0500 Subject: [PATCH 08/14] fix(verify-draft): register the draft results in the public artifact inventory; the benchmark script rejects abbreviated options --- packages/flow/benchmark/verify_draft/run.py | 2 +- packages/flow/public-artifacts.json | 63 +++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/packages/flow/benchmark/verify_draft/run.py b/packages/flow/benchmark/verify_draft/run.py index 1b5408abcb..09274edf2a 100644 --- a/packages/flow/benchmark/verify_draft/run.py +++ b/packages/flow/benchmark/verify_draft/run.py @@ -107,7 +107,7 @@ def twice(pre: Any, post: Any) -> None: def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser() + ap = argparse.ArgumentParser(allow_abbrev=False) ap.add_argument("app", choices=sorted(SETUPS)) ap.add_argument("--out", required=True) ap.add_argument( diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index e61429e282..9bee94bd30 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1132,6 +1132,69 @@ "benchmark/verification_coverage/independent/results/standin-slice/checks.json", "benchmark/verification_coverage/independent/results/standin-slice/rows.json", "benchmark/verifier_baselines/inputs/medplum_tasks.json", + "benchmark/verify_draft/results/directus/draft/contract.yaml", + "benchmark/verify_draft/results/directus/draft/report.json", + "benchmark/verify_draft/results/directus/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/directus/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/directus/draft/rounds/round-2.admission.json", + "benchmark/verify_draft/results/directus/draft/rounds/round-2.yaml", + "benchmark/verify_draft/results/directus/result.json", + "benchmark/verify_draft/results/directus/setup/sandbox.yaml", + "benchmark/verify_draft/results/directus/setup/task.yaml", + "benchmark/verify_draft/results/mockloan/draft/contract.yaml", + "benchmark/verify_draft/results/mockloan/draft/report.json", + "benchmark/verify_draft/results/mockloan/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/mockloan/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/mockloan/result.json", + "benchmark/verify_draft/results/mockloan/setup/sandbox.yaml", + "benchmark/verify_draft/results/mockloan/setup/task.yaml", + "benchmark/verify_draft/results/spend-dev.jsonl", + "benchmark/verify_draft/results/spend.jsonl", + "benchmark/verify_draft/results/v1/mealie/draft/report.json", + "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.admission.json", + "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.yaml", + "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-3.admission.json", + "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-3.yaml", + "benchmark/verify_draft/results/v1/mealie/result.json", + "benchmark/verify_draft/results/v1/mealie/setup/sandbox.yaml", + "benchmark/verify_draft/results/v1/mealie/setup/task.yaml", + "benchmark/verify_draft/results/v1/mockloan/draft/contract.yaml", + "benchmark/verify_draft/results/v1/mockloan/draft/report.json", + "benchmark/verify_draft/results/v1/mockloan/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/v1/mockloan/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/v1/mockloan/result.json", + "benchmark/verify_draft/results/v1/mockloan/setup/sandbox.yaml", + "benchmark/verify_draft/results/v1/mockloan/setup/task.yaml", + "benchmark/verify_draft/results/v1/workbench/draft/contract.yaml", + "benchmark/verify_draft/results/v1/workbench/draft/report.json", + "benchmark/verify_draft/results/v1/workbench/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/v1/workbench/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/v1/workbench/result.json", + "benchmark/verify_draft/results/v1/workbench/setup/sandbox.yaml", + "benchmark/verify_draft/results/v1/workbench/setup/task.yaml", + "benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-2.yaml", + "benchmark/verify_draft/results/void/mealie-run1/draft/rounds/round-3.yaml", + "benchmark/verify_draft/results/void/mealie-run1/setup/sandbox.yaml", + "benchmark/verify_draft/results/void/mealie-run1/setup/task.yaml", + "benchmark/verify_draft/results/void/mealie-run2/draft/report.json", + "benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-2.yaml", + "benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.admission.json", + "benchmark/verify_draft/results/void/mealie-run2/draft/rounds/round-3.yaml", + "benchmark/verify_draft/results/void/mealie-run2/result.json", + "benchmark/verify_draft/results/void/mealie-run2/setup/sandbox.yaml", + "benchmark/verify_draft/results/void/mealie-run2/setup/task.yaml", + "benchmark/verify_draft/results/workbench/draft/contract.yaml", + "benchmark/verify_draft/results/workbench/draft/report.json", + "benchmark/verify_draft/results/workbench/draft/rounds/round-1.admission.json", + "benchmark/verify_draft/results/workbench/draft/rounds/round-1.yaml", + "benchmark/verify_draft/results/workbench/result.json", + "benchmark/verify_draft/results/workbench/setup/sandbox.yaml", + "benchmark/verify_draft/results/workbench/setup/task.yaml", "benchmark/vision_hardening/corpus.json", "benchmark/vision_hardening/results.json", "benchmark/vlm_identity/pairs/collapse_digit_flanked_O0_AC50061_vs_AC5OO61.png", From f09853e5e9f8d09ae54d23224f9964bc43029b5a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:52:38 -0500 Subject: [PATCH 09/14] chore(verify-draft): the public proof carries no model prices The committed results and docs gave per-call and total USD figures. They now give model calls and token counts. The spend ledgers are gone from results/, the benchmark's ledger default moves out of the repository, and run.py drops prices from result.json and the draft report it commits. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../flow/benchmark/verify_draft/PROTOCOL.md | 9 +++--- .../flow/benchmark/verify_draft/RESULTS.md | 32 ++++++++----------- .../flow/benchmark/verify_draft/report.py | 4 +-- .../verify_draft/results/directus.log | 1 - .../results/directus/draft/report.json | 1 - .../verify_draft/results/directus/result.json | 3 -- .../verify_draft/results/mockloan.log | 1 - .../results/mockloan/draft/report.json | 1 - .../verify_draft/results/mockloan/result.json | 2 -- .../verify_draft/results/spend-dev.jsonl | 9 ------ .../verify_draft/results/spend.jsonl | 15 --------- .../verify_draft/results/v1/mealie.log | 1 - .../results/v1/mealie/draft/report.json | 1 - .../results/v1/mealie/result.json | 4 --- .../verify_draft/results/v1/mockloan.log | 1 - .../results/v1/mockloan/draft/report.json | 1 - .../results/v1/mockloan/result.json | 2 -- .../verify_draft/results/v1/workbench.log | 1 - .../results/v1/workbench/draft/report.json | 1 - .../results/v1/workbench/result.json | 2 -- .../void/mealie-run2/draft/report.json | 1 - .../results/void/mealie-run2/result.json | 4 --- .../results/void/mealie-run2/run.log | 1 - .../verify_draft/results/workbench.log | 1 - .../results/workbench/draft/report.json | 1 - .../results/workbench/result.json | 2 -- packages/flow/benchmark/verify_draft/run.py | 18 ++++++++--- packages/flow/public-artifacts.json | 2 -- 30 files changed, 37 insertions(+), 89 deletions(-) delete mode 100644 packages/flow/benchmark/verify_draft/results/spend-dev.jsonl delete mode 100644 packages/flow/benchmark/verify_draft/results/spend.jsonl diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 8e17202d55..0a1ead2cf3 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -167,7 +167,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. A field no demonstration gives is placed at the main table's column of its name, or at the one text column whose name holds its words (never a key column); a create may leave out a text field whose column can't hold NULL and has an empty default, and the contract checks it empty; the `found` twin checks only the task's values, a soft-delete column and yes/no flags, so a record a person entered with other values is found, and a row the write would log beside it is not required; `choose` turns a list of plain values into the demonstrated one-key items, treats an empty list as nothing given, and reads an update's only changes given as null as emptying those fields ([#2418](https://github.com/OpenAdaptAI/OpenAdapt/pull/2418)). Not yet: OpenAPI metadata; a value the app defaults sent explicitly (a currency equal to an app-level default) is still refuted | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions (round 1 was lost because a sign-in fell inside the measured window; fixed after the run, not rerun), 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions (round 1 was lost because a sign-in fell inside the measured window; fixed after the run, not rerun), 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, 2 model calls. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](packages/flow/docs/VERIFY_DRAFT.md), [results](packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/llms-full.txt b/llms-full.txt index aa4ccd3daa..0ea0ab4483 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -607,7 +607,7 @@ improvising or retrying when something is off. | A stop card for a stopped write: the exact record difference and who else wrote, with Undo or Fix that reads back, or Open in the app; cost modelled from published operators and timed machine steps, as pre-registered | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8, blind suite: 16 stops, 14 one-tap with no failed read-back; modelled 42 s per caught harm against 420; one wrong category on a false stop, gone in the re-measure with `void`: 24/24, 15 stops, no wrong category, no failed read-back) | `benchmark/stop_card/`, [PREREG_REVIEW.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/stop_card/PREREG_REVIEW.md) | | Generate `openadapt.verify/v1` contracts from a MySQL, MariaDB or PostgreSQL schema, the kinds of write with their parameter names, and one demonstration write per example: one contract per field set (an update gets one for each set of fields it may change), and `choose` builds any other set of the kind's fields the same way from the same pinned inputs, list parameters by length, a `found` twin for a record already in place, the whole-database frame on every dialect (it compares the contract's own tables too, so an excused column holds only on the rows the write declares, and the recheck sees a late change to a look-alike row), rows the app adds on its own declared by count, a recheck window the person confirms, and `frame.versions` (a lost update) from a version column or the app's audit trail of saves. Equal ids are never taken for a join (a row's own key, the column a path arrived by), a join only equal ids support is a question when a supported place also fits, and a pin needs two rows that agree. Every undecided point is one numbered question; every contract is loaded and dry-read against the live store before it is written; a needed `TRIGGER` grant or view is applied with a flag or the kind is refused. A field no demonstration gives is placed at the main table's column of its name, or at the one text column whose name holds its words (never a key column); a create may leave out a text field whose column can't hold NULL and has an empty default, and the contract checks it empty; the `found` twin checks only the task's values, a soft-delete column and yes/no flags, so a record a person entered with other values is found, and a row the write would log beside it is not required; `choose` turns a list of plain values into the demonstrated one-key items, treats an empty list as nothing given, and reads an update's only changes given as null as emptying those fields ([#2418](https://github.com/OpenAdaptAI/OpenAdapt/pull/2418)). Not yet: OpenAPI metadata; a value the app defaults sent explicitly (a currency equal to an app-level default) is still refuted | [#1672](https://github.com/OpenAdaptAI/OpenAdapt/pull/1672) | Real app (first study, instance copies; questions for a person: Dolibarr 4, Redmine 2, EspoCRM 3, against 11 hand decisions each; every in-scope planted fault stopped (22/22, 19/19, 21/21); correct writes confirmed 32/43, 32/38, 27/40; evidence in the private study repository) | `python -m openadapt_flow.generate.verify_contract`, [GENERATE_CONTRACTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GENERATE_CONTRACTS.md) | | Set up generated contracts with no person answers: answer the generator's questions by fixed rules (its own bookkeeping proposal with time stamps checked against the clock, nothing added), validate them in a sandbox copy of the store beside the app's own (a database or schema the setup makes and drops) by replaying held-out correct writes and planting faults built from each write's recorded diff, never from the contract (missing, wrong value, wrong or look-alike record, duplicate, unrelated edit, a row in another table, a delayed change, a changed bookkeeping cell), and admit a kind only when every held-out write is confirmed and every fault stopped; a kind not admitted has no contract and is listed in `EXCEPTIONS.md`. Not yet: log tables, counters and derived columns, learned excuses, value maps | (this PR) | Unit (real PostgreSQL: one kind admitted with every planted fault stopped, one listed as an exception; a control without the clock check lets the time-stamp fault through). Development apps pending | `python -m openadapt_flow.generate.zero_touch`, [ZERO_TOUCH_DESIGN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/research/ZERO_TOUCH_DESIGN.md) | -| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions (round 1 was lost because a sign-in fell inside the measured window; fixed after the run, not rerun), 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, USD 0.17. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | +| Draft a system's write contract with a model at setup, admit it only by qualification: `openadapt verify draft` gives the pinned model (`claude-opus-5-5`, prompt digest recorded in the contract's `provenance`) the system's description (OpenAPI, GraphQL, FHIR CapabilityStatement, the introspected database schema, or none), one HAR trace with sign-in and secret fields masked, what that write moved in a sandbox, and the task. The draft is admitted only if, on the sandbox, it refutes planted faults (a wrong value in each written column, the wrong row, a duplicate, a sibling record edited, the write reverted after the check, and for an update another user's save overwritten through the app), confirms 5 clean writes and their rechecks, and confirms a two-users-by-two-payloads probe whose attribution of every moved column (values, user, clock, nothing) agrees with its bookkeeping exclusions. Failures go back to the model, at most 3 rounds; a person is asked at most once, only when a planted fault could go only into excluded columns. An admitted contract runs with no model calls; an edit to its check voids the admission (`--check`). Needs an SQL store the command can read and a privileged connection to plant faults | PR ([#2438](https://github.com/OpenAdaptAI/OpenAdapt/pull/2438)) | Real app, lab, synthetic data: Directus 11.5.1, never set up before: admitted in round 2 after 6.0 minutes with 0 person decisions (round 1 was lost because a sign-in fell inside the measured window; fixed after the run, not rerun), 7/7 planted faults refuted in admission and 8/8 held out (a lost update through the app among them), 0 false stops on 10 clean writes, 2 model calls. Mealie 2.8.0, never set up before: refused after 3 rounds in 9.2 minutes, since its store keeps no version, author or save history that could show a lost update. Synthetic MockLoan and workbench: admitted in round 1 in 1.3 to 1.4 minutes, 16/16 held-out faults. The pre-stated 5-minute limit on the untuned app was not met | `openadapt verify draft`, `openadapt_flow/verify_draft/`, [VERIFY_DRAFT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_DRAFT.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/verify_draft/RESULTS.md) | | `void` in an ensure-record contract: values that make a record assert nothing (`status="entered-in-error"`). A record holding one is never the person, is not a duplicate, and a created one needs review; it names values to leave out, never values to keep, and can't name an identity field | Released ([#1657](https://github.com/OpenAdaptAI/OpenAdapt/pull/1657)) | Real app (Medplum 5.2.8: 8 live cases written in advance, 8/8 with the line, 5/8 and one silent pass without it; frozen blind Immunization suite 24/24); adversarial review recorded | `openadapt_flow/ensure_record.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/results/RESULTS.md), [REVIEW_VOID.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/void/REVIEW_VOID.md) | | Check a patient registration on a commercial EHR through its public FHIR sandbox: Epic (open.epic, R4), read through FHIR search and read with SMART backend auth; the frame is the search set, since the sandbox has no AuditEvent or `_history` | Released ([#1656](https://github.com/OpenAdaptAI/OpenAdapt/pull/1656)) | Real app (Epic public sandbox, August 2026 release; blind round 12/13 with none passed as verified, the miss a false refusal fixed in the contract; caught Epic dropping the phone on a 201 create) | `benchmark/commercial_ehr/`, [FINDINGS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/commercial_ehr/FINDINGS.md) | | A public benchmark a vendor reruns with their own agent: `openadapt bench medplum --agent ` runs 37 written-for-it cases (Patient, AllergyIntolerance, Appointment) against a local Medplum through a fault proxy, and scores the agent's claim, a read-back and OpenAdapt's verifier against an end-state oracle | On main ([#1652](https://github.com/OpenAdaptAI/OpenAdapt/pull/1652)) | Real app (Medplum 5.2.8; Claude Sonnet 5.5: OpenAdapt missed 1 of 9 harms with 4 false stops, all corrections that changed the record's identity, against 8 missed by the claim and the read-back; cold run from clone to scorecard 5 min) | [README](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/README.md), [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/RESULTS.md) | diff --git a/packages/flow/benchmark/verify_draft/PROTOCOL.md b/packages/flow/benchmark/verify_draft/PROTOCOL.md index b9ad783332..7eeb462c65 100644 --- a/packages/flow/benchmark/verify_draft/PROTOCOL.md +++ b/packages/flow/benchmark/verify_draft/PROTOCOL.md @@ -58,8 +58,8 @@ synthetic. admission and held out. - **False stops**: clean writes not confirmed, or whose recheck didn't confirm. -- **Model cost**: from each call's token counts at the model's list price, - in the spend ledger (`results/spend.jsonl`). +- **Model calls**: each call and its token counts, in `result.json` + (`model_calls`). Prices stay out of the public results. ## Kill criterion @@ -74,8 +74,9 @@ scored on the held-out faults as well. ## Spend cap -USD 30 in all, enforced by the ledger. A call is refused when the total plus -the worst case of one call would pass it. +A fixed cap in all, enforced by the spend ledger, which is kept outside the +repository. A call is refused when the total plus the worst case of one call +would pass it. ## Addendum, 2026-11-21, before Directus diff --git a/packages/flow/benchmark/verify_draft/RESULTS.md b/packages/flow/benchmark/verify_draft/RESULTS.md index c211f5b557..d591737df0 100644 --- a/packages/flow/benchmark/verify_draft/RESULTS.md +++ b/packages/flow/benchmark/verify_draft/RESULTS.md @@ -9,7 +9,8 @@ browser-free and headless. Raw data for every run, void or not, is under - `draft/rounds/`: every draft and every admission case; - `draft/contract.yaml`: the admitted contracts; - `setup/`: the operator inputs; -- `spend.jsonl` and `spend-dev.jsonl`: every model call. +- `result.json`'s `model_calls`: every model call of the run, with its + token counts. ## Verdict @@ -49,12 +50,12 @@ minutes on the two local apps, with one round each. ## Per-app table (reported runs) -| App | Tuned on? | Description | Setup minutes | Person decisions | Drafts admitted / rejected | Planted faults caught, admission | Planted faults caught, held out | False stops, admission clean writes | False stops, held-out clean writes | Model USD | +| App | Tuned on? | Description | Setup minutes | Person decisions | Drafts admitted / rejected | Planted faults caught, admission | Planted faults caught, held out | False stops, admission clean writes | False stops, held-out clean writes | Model calls | |---|---|---|---|---|---|---|---|---|---|---| -| MockLoan (create) | yes | `db` | 1.4 | 0 | 1 / 0 | 8/8 | 10/10 | 0/5 | 0/5 | 0.05 | -| Workbench, MockMed profile (update) | yes | `db` | 1.3 | 0 | 1 / 0 | 6/6 | 6/6 | 0/5 | 0/5 | 0.08 | -| Mealie v2.8.0 (update), first valid run | no | OpenAPI | 9.2 | 0 | 0 / 3 | best draft 6/8 | not run (nothing admitted) | best draft 0/5 | - | 0.58 | -| Directus 11.5.1 (update) | no | OpenAPI | 6.0 | 0 | 1 / 1 | 7/7 | 8/8 | 0/5 | 0/5 | 0.17 | +| MockLoan (create) | yes | `db` | 1.4 | 0 | 1 / 0 | 8/8 | 10/10 | 0/5 | 0/5 | 1 | +| Workbench, MockMed profile (update) | yes | `db` | 1.3 | 0 | 1 / 0 | 6/6 | 6/6 | 0/5 | 0/5 | 1 | +| Mealie v2.8.0 (update), first valid run | no | OpenAPI | 9.2 | 0 | 0 / 3 | best draft 6/8 | not run (nothing admitted) | best draft 0/5 | - | 3 | +| Directus 11.5.1 (update) | no | OpenAPI | 6.0 | 0 | 1 / 1 | 7/7 | 8/8 | 0/5 | 0/5 | 2 | How to read the columns: @@ -63,15 +64,10 @@ How to read the columns: - Each admitted contract also confirmed every write in its attribution probe: 5 writes each (2 users x 2 payloads, plus the first write repeated). -- Model cost per contract is USD 0.05 to 0.17 for the admitted ones, and - USD 0.58 for Mealie's refusal. +- Each admitted contract took 1 or 2 model calls; Mealie's refusal took 3. -The benchmark spent USD 2.52 in all: - -- USD 1.93 on the reported and void runs (`spend.jsonl`); -- USD 0.59 on development on the tuned apps (`spend-dev.jsonl`). - -The cap was USD 30. +The benchmark made 24 model calls in all: 15 in the reported and void runs, +and 9 in development on the tuned apps. ## What each case showed @@ -141,11 +137,11 @@ refuted all 8 applicable faults: ## Earlier runs (kept, not reported in the table) -| Run | What happened | Minutes | Model USD | +| Run | What happened | Minutes | Model calls | |---|---|---|---| -| Mealie run 1, void | Operator setup error: the read-only role had no `SELECT` on the sequences, so no baseline could be taken. Stopped after round 2. The command now checks the read account once before any model call. | - | 0.51 | -| Mealie run 3, after the fixes below | Refused after 3 rounds. The best draft caught 6 of 7 faults, missing only the lost update. | 4.0 | 0.44 | -| MockLoan and workbench, prompt 1 (`results/v1/`) | Admitted in round 1 with the same numbers as the reported runs. | 1.4 and 1.2 | 0.04 and 0.06 | +| Mealie run 1, void | Operator setup error: the read-only role had no `SELECT` on the sequences, so no baseline could be taken. Stopped after round 2. The command now checks the read account once before any model call. | - | 3 | +| Mealie run 3, after the fixes below | Refused after 3 rounds. The best draft caught 6 of 7 faults, missing only the lost update. | 4.0 | 3 | +| MockLoan and workbench, prompt 1 (`results/v1/`) | Admitted in round 1 with the same numbers as the reported runs. | 1.4 and 1.2 | 1 and 1 | Mealie run 2 exposed three faults in the qualifier. They were fixed before Directus, and the addendum lists them: diff --git a/packages/flow/benchmark/verify_draft/report.py b/packages/flow/benchmark/verify_draft/report.py index 325d1190a2..fcf1fa749e 100644 --- a/packages/flow/benchmark/verify_draft/report.py +++ b/packages/flow/benchmark/verify_draft/report.py @@ -27,7 +27,7 @@ def row(r: dict) -> str: return ( f"| {r['app']}{' (untuned)' if r['untuned'] else ''} | {r['describe']} | {r['setup_minutes']:.1f} | " f"{r['person_decisions']} | {r['drafts_admitted']} / {r['drafts_rejected']} | {caught} | {held} | " - f"{clean_adm} | {clean_held} | {r['model_usd']:.2f} |" + f"{clean_adm} | {clean_held} | {len(r.get('model_calls') or [])} |" ) @@ -35,7 +35,7 @@ def main(names: list[str]) -> int: print( "| App | Description | Setup minutes | Person decisions | Drafts admitted / rejected | " "Planted faults caught (admission) | Planted faults caught (held out) | " - "False stops (admission clean writes) | False stops (held-out clean writes) | Model USD |" + "False stops (admission clean writes) | False stops (held-out clean writes) | Model calls |" ) print("|---|---|---|---|---|---|---|---|---|---|") for name in names or sorted( diff --git a/packages/flow/benchmark/verify_draft/results/directus.log b/packages/flow/benchmark/verify_draft/results/directus.log index 7c6c18f8e1..37e504f0fa 100644 --- a/packages/flow/benchmark/verify_draft/results/directus.log +++ b/packages/flow/benchmark/verify_draft/results/directus.log @@ -23,7 +23,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", - "model_usd": 0.1717, "rounds": [ { "admitted": false, diff --git a/packages/flow/benchmark/verify_draft/results/directus/draft/report.json b/packages/flow/benchmark/verify_draft/results/directus/draft/report.json index 6a6444e649..4faee17dfe 100644 --- a/packages/flow/benchmark/verify_draft/results/directus/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/directus/draft/report.json @@ -3,7 +3,6 @@ "rounds": 2, "person_decisions": 0, "seconds": 359.9, - "model_usd": 0.1717, "reason": "admitted", "contract": "benchmark/verify_draft/results/directus/draft/contract.yaml", "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/directus/result.json b/packages/flow/benchmark/verify_draft/results/directus/result.json index d63b0d0138..8031fdc106 100644 --- a/packages/flow/benchmark/verify_draft/results/directus/result.json +++ b/packages/flow/benchmark/verify_draft/results/directus/result.json @@ -19,7 +19,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", - "model_usd": 0.1717, "model_calls": [ { "at": 1795249874.283477, @@ -30,7 +29,6 @@ "output_tokens": 3260, "cache_read_tokens": 2172, "cache_write_tokens": 0, - "usd": 0.092682, "seconds": 27.95, "request_id": "", "stop_reason": "end_turn" @@ -44,7 +42,6 @@ "output_tokens": 2144, "cache_read_tokens": 2172, "cache_write_tokens": 0, - "usd": 0.079034, "seconds": 16.08, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/results/mockloan.log b/packages/flow/benchmark/verify_draft/results/mockloan.log index 9f9782afc3..fe8d119003 100644 --- a/packages/flow/benchmark/verify_draft/results/mockloan.log +++ b/packages/flow/benchmark/verify_draft/results/mockloan.log @@ -20,7 +20,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", - "model_usd": 0.0477, "rounds": [ { "admitted": true, diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json b/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json index 038e12387b..fb72d1eabf 100644 --- a/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/mockloan/draft/report.json @@ -3,7 +3,6 @@ "rounds": 1, "person_decisions": 0, "seconds": 83.2, - "model_usd": 0.0477, "reason": "admitted", "contract": "benchmark/verify_draft/results/mockloan/draft/contract.yaml", "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/mockloan/result.json b/packages/flow/benchmark/verify_draft/results/mockloan/result.json index cf6a939ad8..badb21a556 100644 --- a/packages/flow/benchmark/verify_draft/results/mockloan/result.json +++ b/packages/flow/benchmark/verify_draft/results/mockloan/result.json @@ -17,7 +17,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", - "model_usd": 0.0477, "model_calls": [ { "at": 1795249605.1276119, @@ -28,7 +27,6 @@ "output_tokens": 1726, "cache_read_tokens": 0, "cache_write_tokens": 2172, - "usd": 0.047712, "seconds": 15.98, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/results/spend-dev.jsonl b/packages/flow/benchmark/verify_draft/results/spend-dev.jsonl deleted file mode 100644 index 266d826c32..0000000000 --- a/packages/flow/benchmark/verify_draft/results/spend-dev.jsonl +++ /dev/null @@ -1,9 +0,0 @@ -{"at": 1795244796.7490969, "label": "mockloan", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 583, "output_tokens": 1613, "cache_read_tokens": 0, "cache_write_tokens": 1944, "usd": 0.044312, "seconds": 16.32, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245057.916192, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 3275, "cache_read_tokens": 1944, "cache_write_tokens": 0, "usd": 0.068933, "seconds": 29.2, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245120.244375, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 3340, "output_tokens": 3541, "cache_read_tokens": 1944, "cache_write_tokens": 0, "usd": 0.084569, "seconds": 33.19, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245169.217639, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 5746, "output_tokens": 2399, "cache_read_tokens": 1944, "cache_write_tokens": 0, "usd": 0.071353, "seconds": 20.15, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245355.956809, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 3009, "cache_read_tokens": 0, "cache_write_tokens": 2042, "usd": 0.073434, "seconds": 27.06, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245403.5369248, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 3256, "output_tokens": 2025, "cache_read_tokens": 2042, "cache_write_tokens": 0, "usd": 0.053932, "seconds": 17.36, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245453.816083, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 5237, "output_tokens": 2468, "cache_read_tokens": 2042, "cache_write_tokens": 0, "usd": 0.070716, "seconds": 20.62, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245605.089545, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 2669, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.067199, "seconds": 24.05, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795245692.510769, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 2531, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.054095, "seconds": 22.76, "request_id": "", "stop_reason": "end_turn"} diff --git a/packages/flow/benchmark/verify_draft/results/spend.jsonl b/packages/flow/benchmark/verify_draft/results/spend.jsonl deleted file mode 100644 index 41d21c8e7f..0000000000 --- a/packages/flow/benchmark/verify_draft/results/spend.jsonl +++ /dev/null @@ -1,15 +0,0 @@ -{"at": 1795246327.806889, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19917, "output_tokens": 2673, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.143903, "seconds": 25.77, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795246389.4471989, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 30447, "output_tokens": 2925, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.180719, "seconds": 24.11, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795246409.924798, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 32873, "output_tokens": 2743, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.186783, "seconds": 20.47, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795246641.254219, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19914, "output_tokens": 2641, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.132907, "seconds": 25.64, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795246895.488529, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 21852, "output_tokens": 9619, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.280219, "seconds": 92.65, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795246918.697357, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 25057, "output_tokens": 3114, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.162939, "seconds": 23.2, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795247669.287714, "label": "mockloan", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 583, "output_tokens": 1575, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.044607, "seconds": 14.8, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795247675.958372, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 2382, "cache_read_tokens": 0, "cache_write_tokens": 2155, "usd": 0.061459, "seconds": 20.73, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795247848.794942, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 19909, "output_tokens": 2429, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.128647, "seconds": 22.47, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795247862.9125051, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 21727, "output_tokens": 1766, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.122659, "seconds": 13.98, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795248054.955477, "label": "mealie", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 23470, "output_tokens": 4549, "cache_read_tokens": 2155, "cache_write_tokens": 0, "usd": 0.185291, "seconds": 45.48, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795249605.1276119, "label": "mockloan", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 583, "output_tokens": 1726, "cache_read_tokens": 0, "cache_write_tokens": 2172, "usd": 0.047712, "seconds": 15.98, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795249617.893177, "label": "workbench", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 761, "output_tokens": 3252, "cache_read_tokens": 0, "cache_write_tokens": 2172, "usd": 0.078944, "seconds": 28.29, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795249874.283477, "label": "directus", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 6762, "output_tokens": 3260, "cache_read_tokens": 2172, "cache_write_tokens": 0, "usd": 0.092682, "seconds": 27.95, "request_id": "", "stop_reason": "end_turn"} -{"at": 1795250072.8052962, "label": "directus", "request_model": "claude-opus-5-5", "response_model": "claude-opus-5-5", "input_tokens": 8930, "output_tokens": 2144, "cache_read_tokens": 2172, "cache_write_tokens": 0, "usd": 0.079034, "seconds": 16.08, "request_id": "", "stop_reason": "end_turn"} diff --git a/packages/flow/benchmark/verify_draft/results/v1/mealie.log b/packages/flow/benchmark/verify_draft/results/v1/mealie.log index 5df9ad8be2..4812f2a5cc 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/mealie.log +++ b/packages/flow/benchmark/verify_draft/results/v1/mealie.log @@ -30,7 +30,6 @@ frame.database.allow_tables.3.contents unchanged "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: lost update: the target moved more than one version in the window, and only one save is the agent's\n[FAILED] stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.4366, "rounds": [ { "admitted": false, diff --git a/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/report.json b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/report.json index 30d9f1b6ff..d020bd6eee 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/v1/mealie/draft/report.json @@ -3,7 +3,6 @@ "rounds": 3, "person_decisions": 0, "seconds": 240.9, - "model_usd": 0.4366, "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: lost update: the target moved more than one version in the window, and only one save is the agent's\n[FAILED] stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)", "contract": null, "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/v1/mealie/result.json b/packages/flow/benchmark/verify_draft/results/v1/mealie/result.json index 8687c5b23e..ffa1bafe71 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/mealie/result.json +++ b/packages/flow/benchmark/verify_draft/results/v1/mealie/result.json @@ -19,7 +19,6 @@ "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: lost update: the target moved more than one version in the window, and only one save is the agent's\n[FAILED] stopped after the first clean write was not confirmed: fix that first (no fault was planted this round)", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.4366, "model_calls": [ { "at": 1795247848.794942, @@ -30,7 +29,6 @@ "output_tokens": 2429, "cache_read_tokens": 2155, "cache_write_tokens": 0, - "usd": 0.128647, "seconds": 22.47, "request_id": "", "stop_reason": "end_turn" @@ -44,7 +42,6 @@ "output_tokens": 1766, "cache_read_tokens": 2155, "cache_write_tokens": 0, - "usd": 0.122659, "seconds": 13.98, "request_id": "", "stop_reason": "end_turn" @@ -58,7 +55,6 @@ "output_tokens": 4549, "cache_read_tokens": 2155, "cache_write_tokens": 0, - "usd": 0.185291, "seconds": 45.48, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/results/v1/mockloan.log b/packages/flow/benchmark/verify_draft/results/v1/mockloan.log index edc9031477..35332013ec 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/mockloan.log +++ b/packages/flow/benchmark/verify_draft/results/v1/mockloan.log @@ -20,7 +20,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.0446, "rounds": [ { "admitted": true, diff --git a/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/report.json b/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/report.json index 07dd09fa52..42b10bc0a9 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/v1/mockloan/draft/report.json @@ -3,7 +3,6 @@ "rounds": 1, "person_decisions": 0, "seconds": 81.9, - "model_usd": 0.0446, "reason": "admitted", "contract": "benchmark/verify_draft/results/mockloan/draft/contract.yaml", "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/v1/mockloan/result.json b/packages/flow/benchmark/verify_draft/results/v1/mockloan/result.json index 705faaf021..a020f4e1a1 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/mockloan/result.json +++ b/packages/flow/benchmark/verify_draft/results/v1/mockloan/result.json @@ -17,7 +17,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.0446, "model_calls": [ { "at": 1795247669.287714, @@ -28,7 +27,6 @@ "output_tokens": 1575, "cache_read_tokens": 0, "cache_write_tokens": 2155, - "usd": 0.044607, "seconds": 14.8, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/results/v1/workbench.log b/packages/flow/benchmark/verify_draft/results/v1/workbench.log index 342f29a47e..2dcbd76b7e 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/workbench.log +++ b/packages/flow/benchmark/verify_draft/results/v1/workbench.log @@ -22,7 +22,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.0615, "rounds": [ { "admitted": true, diff --git a/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/report.json b/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/report.json index 10e1af9e8f..836f4b7d1e 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/v1/workbench/draft/report.json @@ -3,7 +3,6 @@ "rounds": 1, "person_decisions": 0, "seconds": 72.6, - "model_usd": 0.0615, "reason": "admitted", "contract": "benchmark/verify_draft/results/workbench/draft/contract.yaml", "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/v1/workbench/result.json b/packages/flow/benchmark/verify_draft/results/v1/workbench/result.json index 9235a95956..0d238edb51 100644 --- a/packages/flow/benchmark/verify_draft/results/v1/workbench/result.json +++ b/packages/flow/benchmark/verify_draft/results/v1/workbench/result.json @@ -19,7 +19,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.0615, "model_calls": [ { "at": 1795247675.958372, @@ -30,7 +29,6 @@ "output_tokens": 2382, "cache_read_tokens": 0, "cache_write_tokens": 2155, - "usd": 0.061459, "seconds": 20.73, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json index 754a0bede5..086d7632ca 100644 --- a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/draft/report.json @@ -3,7 +3,6 @@ "rounds": 3, "person_decisions": 0, "seconds": 551.8, - "model_usd": 0.5761, "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-2: the write with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-3: the write with payload 3. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-4: the write with payload 4. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-5: the write with payload 5. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:agent:p1: the write by agent with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:agent:p2: the write by agent with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:other:p1: the write by other with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] probe attribution:other:p2: the write by other with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)", "contract": null, "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json index b8f9bbfb94..39f0da8223 100644 --- a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/result.json @@ -19,7 +19,6 @@ "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-2: the write with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-3: the write with payload 3. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-4: the write with payload 4. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-5: the write with payload 5. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 recor", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.5761, "model_calls": [ { "at": 1795246641.254219, @@ -30,7 +29,6 @@ "output_tokens": 2641, "cache_read_tokens": 2155, "cache_write_tokens": 0, - "usd": 0.132907, "seconds": 25.64, "request_id": "", "stop_reason": "end_turn" @@ -44,7 +42,6 @@ "output_tokens": 9619, "cache_read_tokens": 2155, "cache_write_tokens": 0, - "usd": 0.280219, "seconds": 92.65, "request_id": "", "stop_reason": "end_turn" @@ -58,7 +55,6 @@ "output_tokens": 3114, "cache_read_tokens": 2155, "cache_write_tokens": 0, - "usd": 0.162939, "seconds": 23.2, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log index 7e26ba9ad7..00daf39c4b 100644 --- a/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log +++ b/packages/flow/benchmark/verify_draft/results/void/mealie-run2/run.log @@ -27,7 +27,6 @@ frame.versions "reason": "refused after 3 round(s): [FAILED] clean clean-1: the write with payload 1. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-2: the write with payload 2. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-3: the write with payload 3. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-4: the write with payload 4. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 record(s) outside the declared write moved (removed); 8 of them no actor explains. Moved: nutrition removed None; settings removed None; ingredients removed None; instructions removed None; recipe_instructions removed [] (unattributed)\n[FAILED] clean clean-5: the write with payload 5. Expected confirmed, got REFUTED. Reasons: the target's versions aren't whole numbers and no author is read, so the saves in the window can't be counted; 8 recor", "model": "claude-opus-5-5", "prompt_sha256": "sha256:738a1230c4d9449f3f23487d338fce9fc8f35779f3511bf2093fc4f7c6252840", - "model_usd": 0.5761, "rounds": [ { "admitted": false, diff --git a/packages/flow/benchmark/verify_draft/results/workbench.log b/packages/flow/benchmark/verify_draft/results/workbench.log index 319bf781e3..b716af6291 100644 --- a/packages/flow/benchmark/verify_draft/results/workbench.log +++ b/packages/flow/benchmark/verify_draft/results/workbench.log @@ -22,7 +22,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", - "model_usd": 0.0789, "rounds": [ { "admitted": true, diff --git a/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json b/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json index 33bfd3ea95..c1649a5101 100644 --- a/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json +++ b/packages/flow/benchmark/verify_draft/results/workbench/draft/report.json @@ -3,7 +3,6 @@ "rounds": 1, "person_decisions": 0, "seconds": 79.4, - "model_usd": 0.0789, "reason": "admitted", "contract": "benchmark/verify_draft/results/workbench/draft/contract.yaml", "questions": [], diff --git a/packages/flow/benchmark/verify_draft/results/workbench/result.json b/packages/flow/benchmark/verify_draft/results/workbench/result.json index 95f9ea2a45..b5ee241eee 100644 --- a/packages/flow/benchmark/verify_draft/results/workbench/result.json +++ b/packages/flow/benchmark/verify_draft/results/workbench/result.json @@ -19,7 +19,6 @@ "reason": "admitted", "model": "claude-opus-5-5", "prompt_sha256": "sha256:c33fbf890663c5314f9afb16035a491c6526217054cfacda14685bd0caf0d796", - "model_usd": 0.0789, "model_calls": [ { "at": 1795249617.893177, @@ -30,7 +29,6 @@ "output_tokens": 3252, "cache_read_tokens": 0, "cache_write_tokens": 2172, - "usd": 0.078944, "seconds": 28.29, "request_id": "", "stop_reason": "end_turn" diff --git a/packages/flow/benchmark/verify_draft/run.py b/packages/flow/benchmark/verify_draft/run.py index 09274edf2a..938222ca62 100644 --- a/packages/flow/benchmark/verify_draft/run.py +++ b/packages/flow/benchmark/verify_draft/run.py @@ -5,7 +5,9 @@ 1. The operator setup (``apps.py``), timed on its own. 2. ``openadapt verify draft`` (``openadapt_flow.verify_draft.draft.run``) - with the pinned model: setup minutes, rounds, person decisions, cost. + with the pinned model: setup minutes, rounds, person decisions, model + calls and tokens. The spend ledger (with prices) stays outside the + committed results. 3. If a contract is admitted, a held-out check with no model: a second qualification run on harness-chosen values (other clean writes, the faults planted on other rows with other values), plus app-level faults @@ -111,7 +113,8 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("app", choices=sorted(SETUPS)) ap.add_argument("--out", required=True) ap.add_argument( - "--spend-ledger", default="benchmark/verify_draft/results/spend.jsonl" + "--spend-ledger", + default=str(Path.home() / ".openadapt" / "verify-draft" / "spend.jsonl"), ) ap.add_argument("--spend-cap-usd", type=float, default=30.0) args = ap.parse_args(argv) @@ -134,6 +137,11 @@ def main(argv: list[str] | None = None) -> int: log=lambda s: print(f"[{args.app}] {s}", file=sys.stderr, flush=True), ) minutes = (time.monotonic() - started) / 60 + report_path = out / "draft" / "report.json" + if report_path.is_file(): # the committed proof carries no prices + report = json.loads(report_path.read_text(encoding="utf-8")) + report.pop("model_usd", None) + report_path.write_text(json.dumps(report, indent=1), encoding="utf-8") rounds = [ { "admitted": a.admitted, @@ -179,8 +187,10 @@ def main(argv: list[str] | None = None) -> int: "reason": outcome.reason[:2000], "model": M.MODEL, "prompt_sha256": M.prompt_sha256(), - "model_usd": round(outcome.usd, 4), - "model_calls": [e for e in ledger.entries], + # Calls and tokens only: the public proof carries no prices. + "model_calls": [ + {k: v for k, v in e.items() if k != "usd"} for e in ledger.entries + ], "rounds": rounds, "notes": run.notes, } diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index c5a4972b7b..9c1240a145 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1165,8 +1165,6 @@ "benchmark/verify_draft/results/mockloan/result.json", "benchmark/verify_draft/results/mockloan/setup/sandbox.yaml", "benchmark/verify_draft/results/mockloan/setup/task.yaml", - "benchmark/verify_draft/results/spend-dev.jsonl", - "benchmark/verify_draft/results/spend.jsonl", "benchmark/verify_draft/results/v1/mealie/draft/report.json", "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-1.yaml", "benchmark/verify_draft/results/v1/mealie/draft/rounds/round-2.admission.json", From b982f64a7a03c4cdac55927fedc11260ace2ceb8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:52:39 -0500 Subject: [PATCH 10/14] fix(verify-draft): a missing observation never admits a contract fail-open class: absent-evidence-as-success. - A stale save the app refused counted as lost-update protection for any HTTP error. Now only a 409 or 412 that left the other user's save in the store is credited; an outage or an expired session stays untestable. - A sandbox with no second user silently skipped the actor axis of the attribution probe, so a create was admitted on three writes instead of five. The missing axis is now an untestable case, and admission refuses. --- .../flow/openadapt_flow/verify_draft/admit.py | 45 +++++++++++-- packages/flow/tests/test_verify_draft.py | 67 +++++++++++++++++++ 2 files changed, 107 insertions(+), 5 deletions(-) diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py index bac445194b..2e5d9ce376 100644 --- a/packages/flow/openadapt_flow/verify_draft/admit.py +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -560,6 +560,8 @@ def __init__( #: ``table.column`` a person said is bookkeeping (the one question). self.bookkeeping = set(bookkeeping) self.masked: list[dict[str, str]] = [] + #: The HTTP statuses of the last write the app refused in :meth:`run`. + self.refused_statuses: list[int] = [] os.environ.setdefault("OPENADAPT_LOCAL_SEAL", "off") # -- one write under the contract @@ -637,6 +639,7 @@ def run( if any(s >= 400 for s in statuses): # For a clean write: the values were invalid (the caller # skips them). For anything else the case can't be built. + self.refused_statuses = list(statuses) case.applicable = False case.untestable = case.group != "clean" case.note = f"the app refused the write (HTTP {max(statuses)})" @@ -1055,25 +1058,44 @@ def undo(pre: Rows, post: Rows) -> None: ) return [case] + other_saved: list[Rows] = [] + def first_save() -> Optional[str]: st = self.app.send( demo.writes, "other", swap_map(demo.params, other_values) ) if any(s >= 400 for s in st): return f"the other user's save was refused (HTTP {max(st)})" + other_saved.append(self.store.read_moved(demo.base)) return None case.detail = ( "the other user saves the record, then the agent's save overwrites it" ) + self.refused_statuses = [] self.run(contract, case, values=values, before=first_save) + refused = [s for s in self.refused_statuses if s >= 400] if case.note.startswith("the app refused"): - # The app itself refuses a save from a stale copy: nothing to - # catch, a true not-applicable. - case.untestable = False - case.note = ( - "the app refused the stale save: it prevents lost updates itself" + # fail-open class: absent-evidence-as-success. Only a conflict + # status that left the other user's save in the store shows + # the app prevents lost updates itself. An outage or an + # expired session (503, 401) observed nothing: untestable. + kept = bool(other_saved) and ( + bool(moves(demo.base, other_saved[0])) + and not moves(other_saved[0], self.store.read_moved(demo.base)) ) + if refused and set(refused) <= {409, 412} and kept: + case.untestable = False + case.note = ( + "the app refused the stale save with a conflict and kept " + "the other user's save: it prevents lost updates itself" + ) + else: + case.untestable = True + case.note = ( + f"the stale save failed (HTTP {max(refused or [0])}) " + "without a conflict that kept the other user's save" + ) return [case] raise ValueError(f"unknown fault {name}") @@ -1117,6 +1139,19 @@ def _attribute( return [], [] runs: dict[tuple[str, int], list[Move]] = {} cases = [] + if "other" not in self.sandbox.actors: + # fail-open class: absent-evidence-as-success. Without a second + # user the actor axis is never probed, so nothing shows which + # moves follow the actor: untestable, never a smaller pass. + missing = Case( + "probe", + "attribution:other", + "the writes by a second user", + "confirmed", + ) + missing.untestable = True + missing.note = "the sandbox has no second user (actors.other)" + cases.append(missing) # Each actor with each payload, plus the first one again: what moves # between two identical writes moves on its own (a clock, a new id). plan = [(a, i) for a in actors for i in (0, 1)] + [(actors[0], 2)] diff --git a/packages/flow/tests/test_verify_draft.py b/packages/flow/tests/test_verify_draft.py index 50bef43e33..4b0a254058 100644 --- a/packages/flow/tests/test_verify_draft.py +++ b/packages/flow/tests/test_verify_draft.py @@ -415,6 +415,73 @@ def test_untestable_is_never_a_pass() -> None: assert adm.only_untestable() and "not the contract's fault" in adm.feedback() +@pytest.mark.parametrize( + ("status", "kept", "credited"), + [ + (409, True, True), + (412, True, True), + (503, True, False), # an outage observed nothing + (401, True, False), # an expired session observed nothing + (409, False, False), # a conflict that lost the other user's save + ], +) +def test_a_refused_stale_save_is_credited_only_for_a_kept_conflict( + status: int, kept: bool, credited: bool +) -> None: + from types import SimpleNamespace + + from openadapt_flow.verify_draft.sandbox import Move + + base = {"t": {1: {"v": "a"}}} + saved = {"t": {1: {"v": "other"}}} + state = {"rows": base} + q = object.__new__(A.Qualifier) + q.sandbox = SimpleNamespace(actors={"agent": {}, "other": {}}) + q.demo = A.Demo( + writes=[], + params={"v": "a"}, + base=base, + after={"t": {1: {"v": "b"}}}, + main=Move("t", 1, "changed", ["v"], {"v": "a"}, {"v": "b"}), + param_columns={"v": "v"}, + ) + + def send(writes: Any, actor: str, swaps: Any) -> list[int]: + state["rows"] = saved # the other user's save lands + return [200] + + q.app = SimpleNamespace(send=send) + q.store = SimpleNamespace(read_moved=lambda _base: state["rows"]) + q.refused_statuses = [] + + def run(contract: Any, case: A.Case, *, values: Any, before: Any) -> None: + assert before() is None + if not kept: + state["rows"] = {"t": {1: {"v": "agent"}}} + q.refused_statuses = [status] + case.applicable = False + case.untestable = True + case.note = f"the app refused the write (HTTP {status})" + + q.run = run # type: ignore[method-assign] + (case,) = q._fault({}, "lost_update", {"v": "b"}, [{"v": "other"}]) + A.Qualifier._judge(case) + assert case.untestable is (not credited) + assert case.passed is credited + + +def test_a_single_user_sandbox_never_admits(mockloan: Path) -> None: + sandbox = yaml.safe_load((mockloan / "sandbox.yaml").read_text()) + sandbox["actors"].pop("other") + (mockloan / "sandbox.yaml").write_text(yaml.safe_dump(sandbox)) + outcome = _run(mockloan, Fixed(GOOD), rounds=1) + assert not outcome.admitted + adm = outcome.admissions[-1] + (missing,) = [c for c in adm.cases if c.name == "attribution:other"] + assert missing.untestable and not missing.passed + assert adm.only_untestable() + + def test_one_question_at_most(mockloan: Path, monkeypatch: pytest.MonkeyPatch) -> None: """A masked column is asked about once; the answer is a decision, and 'bookkeeping' lets the same draft be qualified again.""" From 1e4d8e716b11d489d2cb5d21d62043baa0ff6606 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:27:17 -0500 Subject: [PATCH 11/14] fix(cli): verify draft shows its help when the installed engine lacks it The launcher CI runs against the released engine, which has no verify_draft module, so 'openadapt verify draft --help' exited 1. It now goes through the same optional-engine entry as wrap and hooks: pure help when the module is absent, exit 2 for a run, and a broken installed dependency still fails loudly. --- openadapt/cli.py | 16 ++++++++++------ tests/test_optional_engine_commands.py | 9 +++++---- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/openadapt/cli.py b/openadapt/cli.py index 0f6fbd70db..d0b7f73b66 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1848,12 +1848,16 @@ def verify_draft(ctx: click.Context) -> None: model calls. `--help` lists every option. """ _require_supported_python() - try: - from openadapt_flow.verify_draft.draft import main as draft_main - except ImportError: - click.echo("Error: the OpenAdapt engine is not installed.", err=True) - click.echo("Reinstall with: pip install --upgrade openadapt", err=True) - sys.exit(1) + draft_main = _optional_engine_entrypoint( + ctx, ("openadapt_flow.verify_draft.draft",) + ) + if draft_main is None: + click.echo( + "Error: this openadapt-flow installation has no verify draft command.", + err=True, + ) + click.echo("Upgrade with: pip install --upgrade openadapt", err=True) + sys.exit(2) sys.exit(int(draft_main(list(ctx.args)) or 0)) diff --git a/tests/test_optional_engine_commands.py b/tests/test_optional_engine_commands.py index 896064c75f..a5e273320d 100644 --- a/tests/test_optional_engine_commands.py +++ b/tests/test_optional_engine_commands.py @@ -11,6 +11,7 @@ ("wrap", ("openadapt_flow.wrap.cli",), []), ("agent", ("openadapt_agent.cli",), []), ("seal", ("openadapt_agent.seal_cli", "openadapt_agent.cli"), ["seal"]), + ("verify draft", ("openadapt_flow.verify_draft.draft",), []), ) @@ -31,7 +32,7 @@ def load(name): raise ModuleNotFoundError(name=missing) monkeypatch.setattr(cli, "import_module", load) - result = CliRunner().invoke(cli.main, [command, help_flag]) + result = CliRunner().invoke(cli.main, [*command.split(), help_flag]) assert result.exit_code == 0, result.output assert f"Usage: main {command}" in result.output @@ -45,7 +46,7 @@ def load(name): raise ModuleNotFoundError(name=modules[0]) monkeypatch.setattr(cli, "import_module", load) - result = CliRunner().invoke(cli.main, [command, *arguments]) + result = CliRunner().invoke(cli.main, [*command.split(), *arguments]) assert result.exit_code != 0 assert result.stdout == "" @@ -66,7 +67,7 @@ def load(name): return SimpleNamespace(main=main) monkeypatch.setattr(cli, "import_module", load) - result = CliRunner().invoke(cli.main, [command, *arguments]) + result = CliRunner().invoke(cli.main, [*command.split(), *arguments]) assert result.exit_code == 3 assert imports == list(modules) assert calls == [[*prefix, *arguments]] @@ -84,7 +85,7 @@ def load(name): raise error monkeypatch.setattr(cli, "import_module", load) - result = CliRunner().invoke(cli.main, [command, "--help"]) + result = CliRunner().invoke(cli.main, [*command.split(), "--help"]) assert result.exit_code != 0 assert result.exception is error assert result.stdout == "" From bc409d1f262e562617515c90ff7dedd8287ee7e5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 10:34:50 -0500 Subject: [PATCH 12/14] test(cli): refresh root CLI surface snapshot for #2438 --- tests/fixtures/cli_surface.json | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/fixtures/cli_surface.json b/tests/fixtures/cli_surface.json index 35ac156fe8..b0022d84c7 100644 --- a/tests/fixtures/cli_surface.json +++ b/tests/fixtures/cli_surface.json @@ -15,7 +15,8 @@ "openadapt setup": "Usage: openadapt setup [OPTIONS]\n\n Add OpenAdapt to Claude Code, Cursor, Codex and Gemini CLI.\n\n For each one installed, register the OpenAdapt MCP server and install a skill that tells the agent\n how to turn an app task into a tool it can call again. By default the agent teaches read-only\n tasks in web apps. With --app and --verify it teaches saves in that one app, on the web, the\n desktop, or over RDP or Citrix. Prints every change. Running it again changes nothing that is\n already set up.\n\nOptions:\n --dry-run List what setup would change, and change nothing.\n --undo Reverse what earlier setup runs changed.\n --client [claude|cursor|codex|gemini]\n Set up only this client (repeat for more). Default: every one\n found.\n --app FILE deploy.yaml naming one app (web, desktop, RDP or Citrix). The\n agent then teaches saves in that app, each read back with\n --verify.\n --verify FILE With --app: the verify.yaml that reads the app's system of record.\n --authorization FILE With --app: a person's signed teach authorization (openadapt-flow\n teach-authorization). Without one, nothing the agent teaches is\n admitted.\n --help Show this message and exit.\n\n Also available as: setup clients Operations: clients, connect, deploy, doctor, version", "openadapt teach": "Usage: openadapt teach [OPTIONS]\n\n Run the canonical demonstration compiler and governed runtime.\n\n Every argument passes to openadapt-flow unchanged. This keeps the launcher command list, help,\n options, validation, and exit codes identical to the installed engine version.\n\nOptions:\n --help Show this message and exit.", "openadapt undo": "Usage: openadapt undo [OPTIONS]\n\n Run the canonical demonstration compiler and governed runtime.\n\n Every argument passes to openadapt-flow unchanged. This keeps the launcher command list, help,\n options, validation, and exit codes identical to the installed engine version.\n\nOptions:\n --help Show this message and exit.", - "openadapt verify": "Usage: openadapt verify [OPTIONS] COMMAND [ARGS]...\n\n Verify writes against the system of record, for any agent.\n\n Around each write your agent makes, it gets a verified receipt or a refusal, never an unverified\n success. Python agents use the SDK (`from openadapt.verify import ...`); any MCP client uses\n `openadapt verify serve`.\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n ledger Writes whose outcome isn't known yet, held so they aren't sent twice.\n serve Serve verify_contracts, verify_begin, verify_check and verify_recheck over MCP (stdio).", + "openadapt verify": "Usage: openadapt verify [OPTIONS] COMMAND [ARGS]...\n\n Verify writes against the system of record, for any agent.\n\n Around each write your agent makes, it gets a verified receipt or a refusal, never an unverified\n success. Python agents use the SDK (`from openadapt.verify import ...`); any MCP client uses\n `openadapt verify serve`.\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n draft Draft a write contract with a model; admit it only if OpenAdapt qualifies it on a...\n ledger Writes whose outcome isn't known yet, held so they aren't sent twice.\n serve Serve verify_contracts, verify_begin, verify_check and verify_recheck over MCP (stdio).", + "openadapt verify draft": "Usage: openadapt verify draft [OPTIONS]\n\n Draft a write contract with a model; admit it only if OpenAdapt qualifies it on a sandbox.\n\n `openadapt verify draft --describe openapi.json --trace demo.har --task task.yaml --sandbox\n sandbox.yaml --out DIR`. The model (key from ANTHROPIC_API_KEY) works at setup only; an admitted\n contract runs with no model calls. `--help` lists every option.", "openadapt verify ledger": "Usage: openadapt verify ledger [OPTIONS] COMMAND [ARGS]...\n\n Writes whose outcome isn't known yet, held so they aren't sent twice.\n\n Every verified write goes through the ledger. A write that may have landed, or was refuted, is\n held: no worker sends it again until a read-back resolves it (`reconcile`) or a person checks the\n record (`release`). The ledger holds no record values.\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n list Show held and open writes: key, state, when it began, outcome.\n reconcile Read held writes back and resolve the ones the store now settles.\n release Release a held write after a person checked the record.", "openadapt verify ledger list": "Usage: openadapt verify ledger list [OPTIONS]\n\n Show held and open writes: key, state, when it began, outcome.\n\n Also each provisional CONFIRMED whose recheck is still owed, with its due time, so a recheck isn't\n lost when the server that holds it restarts.\n\nOptions:\n --ledger DIRECTORY Ledger folder (must match the configured protected journal, if set).\n --help Show this message and exit.", "openadapt verify ledger reconcile": "Usage: openadapt verify ledger reconcile [OPTIONS] [KEY]\n\n Read held writes back and resolve the ones the store now settles.\n\nOptions:\n --contracts DIRECTORY Folder of write contracts (.yaml) the writes were made under.\n [required]\n --ledger DIRECTORY Ledger folder (must match the configured protected journal, if set).\n --help Show this message and exit.", @@ -255,6 +256,7 @@ }, "openadapt verify": { "commands": { + "draft": false, "ledger": false, "serve": false }, @@ -262,6 +264,12 @@ "hidden": false, "params": [] }, + "openadapt verify draft": { + "commands": {}, + "group": false, + "hidden": false, + "params": [] + }, "openadapt verify ledger": { "commands": { "list": false, From b699a741f7fb74e1428685060a56d9f170740ef1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 04:53:42 -0500 Subject: [PATCH 13/14] chore(flow): eliminate verdict fold hits in verify_draft admit and inputs --- .../flow/openadapt_flow/verify_draft/admit.py | 48 ++++++++++++------- .../openadapt_flow/verify_draft/inputs.py | 6 +-- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py index 2e5d9ce376..0cf60bd43f 100644 --- a/packages/flow/openadapt_flow/verify_draft/admit.py +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -52,6 +52,7 @@ from pathlib import Path from typing import Any, Callable, Mapping, Optional, Sequence +from openadapt_flow.verifier import Outcome from openadapt_flow.verify_draft.sandbox import ( App, Move, @@ -149,6 +150,11 @@ r"pass(word)?|secret|token|api[-_]?key|hash|salt|(^|_)(otp|tfa)(_|$)", re.I ) _IDENTIFIER = re.compile(r"(^|_)(id|key|no|number|code|slug|mrn|ref|uuid)$", re.I) +_EXPECT_CONFIRMED = "confirmed" +_CONFIRMED_LABEL = Outcome.CONFIRMED.value +_ERROR_LABEL = "ERROR" +_OK_RECHECKS = ("", _CONFIRMED_LABEL, "NONE") +_BROKEN_LABELS = ("", _ERROR_LABEL, "NO_BASELINE") class DraftProblem(ValueError): @@ -655,7 +661,7 @@ def run( case.moved = list( ((result.evidence or {}).get("frame") or {}).get("moves") or [] )[:20] - if rechecks and result.outcome.value == "CONFIRMED": + if rechecks and result.outcome.value == _CONFIRMED_LABEL: if result.recheck is None: case.recheck = "NONE" case.reasons.append( @@ -677,8 +683,19 @@ def run( return pre, post except DraftProblem: raise - except Exception as exc: # noqa: BLE001 - a broken case is reported, not admitted - case.outcome = case.outcome or "ERROR" + except ( + _NotApplicable, + _Untestable, + VerifierError, + WriteBlocked, + OSError, + RuntimeError, + ValueError, + TypeError, + LookupError, + ArithmeticError, + ) as exc: + case.outcome = case.outcome or _ERROR_LABEL case.reasons.append(f"{type(exc).__name__}: {exc}") return None finally: @@ -692,19 +709,17 @@ def _judge(case: Case) -> None: if not case.applicable: case.passed = True return - if case.expect == "confirmed": + if case.expect == _EXPECT_CONFIRMED: # No recheck scheduled is the late-revert case's failure, not a # false stop on a clean write. - case.passed = case.outcome == "CONFIRMED" and case.recheck in ( - "", - "CONFIRMED", - "NONE", + case.passed = ( + case.outcome == _CONFIRMED_LABEL and case.recheck in _OK_RECHECKS ) else: final = case.recheck or case.outcome case.passed = ( - case.outcome not in ("", "ERROR", "NO_BASELINE") - and final != "CONFIRMED" + case.outcome not in _BROKEN_LABELS + and final != _CONFIRMED_LABEL and final != "NONE" ) @@ -1032,7 +1047,7 @@ def undo(pre: Rows, post: Rows) -> None: self.store.update(m.table, m.key, {c: m.b[c] for c in m.columns}) self.run(contract, case, values=values, revert=undo, rechecks=True) - if case.outcome == "CONFIRMED" and not case.recheck: + if case.outcome == _CONFIRMED_LABEL and not case.recheck: case.recheck = "NONE" return [case] @@ -1122,7 +1137,7 @@ def guarded(pre: Rows, post: Rows) -> None: self.run(contract, case, values=values, fault=guarded) finally: if not case.applicable or case.untestable: - case.outcome = case.outcome if case.outcome not in ("ERROR",) else "" + case.outcome = case.outcome if case.outcome != _ERROR_LABEL else "" case.reasons = [ r for r in case.reasons @@ -1195,17 +1210,18 @@ def _attribute( if is_ex and cause == "payload" and col != "+": a.problem = "excluded, but it moves with the values written: the exclusion hides the write" out.append(a) - moved = {(a.table, a.column) for a in out} + observed_cells = {(a.table, a.column) for a in out} + observed_tables = {t for t, _ in observed_cells} for table, masked_cols in mask.items(): for col in masked_cols: if col == "*": - unexcused = not any(t == table for t, _ in moved) + unexcused = table not in observed_tables what = "a skipped table" elif col == "+": - unexcused = (table, "+") not in moved + unexcused = (table, "+") not in observed_cells what = "an append-only table" else: - unexcused = (table, col) not in moved + unexcused = (table, col) not in observed_cells what = "excluded" if unexcused: out.append( diff --git a/packages/flow/openadapt_flow/verify_draft/inputs.py b/packages/flow/openadapt_flow/verify_draft/inputs.py index 36d729f56f..c530fd29e1 100644 --- a/packages/flow/openadapt_flow/verify_draft/inputs.py +++ b/packages/flow/openadapt_flow/verify_draft/inputs.py @@ -72,18 +72,18 @@ def load_task(path: str | Path) -> Task: def _load_doc(path: Path) -> Any: + import yaml + raw = path.read_text(encoding="utf-8") try: return json.loads(raw) except ValueError: pass try: - import yaml - doc = yaml.safe_load(raw) if isinstance(doc, (dict, list)): return doc - except Exception: # noqa: BLE001 - SDL is neither + except (yaml.YAMLError, ValueError): pass return raw From c5d1b3dd9db17c8e83efd31a7110a147dc542b42 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 05:22:28 -0500 Subject: [PATCH 14/14] fix(flow): address review findings in verify_draft masking, verdict site, and DB error capture --- packages/flow/docs/FAIL_CLOSED.md | 3 + .../flow/openadapt_flow/verify_draft/admit.py | 274 +++++++++++------- .../openadapt_flow/verify_draft/inputs.py | 89 ++++-- .../failopen/sites/verify_draft_admit.py | 126 ++++++++ packages/flow/tests/test_verify_draft.py | 145 +++++++++ 5 files changed, 508 insertions(+), 129 deletions(-) create mode 100644 packages/flow/tests/failopen/sites/verify_draft_admit.py diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 236df580f5..d6cbefcb5a 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -291,6 +291,9 @@ Done: - [x] `receipt_record._tally_lines` (C2 C3): fix: a line check nobody listed keeps the run from VERIFIED and counts as not checked. - [x] `tx/wire_tap.relay_redirect_location` (C6): registered after #2470. +- [x] `verify_draft.judge_case` (C3 C5): admission cases settle on the verdict + kernel via allow-listed outcome maps; untestable, error, or unknown codes + never hold. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/verify_draft/admit.py b/packages/flow/openadapt_flow/verify_draft/admit.py index 0cf60bd43f..2b52deb29c 100644 --- a/packages/flow/openadapt_flow/verify_draft/admit.py +++ b/packages/flow/openadapt_flow/verify_draft/admit.py @@ -52,7 +52,21 @@ from pathlib import Path from typing import Any, Callable, Mapping, Optional, Sequence +from openadapt_flow.verdict import ( + Errored, + FailClosed, + Obligations, + Observed, + Result, + Settlement, + Status, + Subject, + observe, + settle, +) +from openadapt_flow.verdict_sites import verdict_site from openadapt_flow.verifier import Outcome +from openadapt_flow.verify_draft.inputs import SECRET_NAME_RE from openadapt_flow.verify_draft.sandbox import ( App, Move, @@ -146,15 +160,8 @@ "server_set", } ) -_SECRET_COLUMN = re.compile( - r"pass(word)?|secret|token|api[-_]?key|hash|salt|(^|_)(otp|tfa)(_|$)", re.I -) +_SECRET_COLUMN = SECRET_NAME_RE _IDENTIFIER = re.compile(r"(^|_)(id|key|no|number|code|slug|mrn|ref|uuid)$", re.I) -_EXPECT_CONFIRMED = "confirmed" -_CONFIRMED_LABEL = Outcome.CONFIRMED.value -_ERROR_LABEL = "ERROR" -_OK_RECHECKS = ("", _CONFIRMED_LABEL, "NONE") -_BROKEN_LABELS = ("", _ERROR_LABEL, "NO_BASELINE") class DraftProblem(ValueError): @@ -541,6 +548,74 @@ def _perturb(value: Any) -> Any: return s + " X" +@verdict_site("verify_draft.judge_case", classes="C3 C5") +def judge_case(case: Case) -> Settlement: + """Settle one admission case against its expected verifier outcome. + + An untestable case, an empty/error/no-baseline outcome, or any unknown + outcome or expectation code settles as ``NOT_CHECKED`` and never passes. + """ + subject = Subject("case", case.name or "case") + if case.untestable: + return settle( + Obligations.fix([subject], source="verify_draft"), + [Result(subject, Status.NOT_CHECKED, reason="untestable")], + ) + if not case.applicable: + return settle( + Obligations.fix([subject], source="verify_draft"), + [Result.held(subject, Observed("not_applicable"), reason="not_applicable")], + ) + if case.expect == "confirmed": + obligations = [subject] + results = [ + Result.from_code( + subject, + case.outcome, + held=frozenset({"CONFIRMED"}), + refuted=frozenset({"REFUTED"}), + ) + ] + if case.recheck: + recheck_subject = Subject("recheck", case.name or "case") + obligations.append(recheck_subject) + results.append( + Result.from_code( + recheck_subject, + case.recheck, + held=frozenset({"CONFIRMED", "NONE"}), + refuted=frozenset({"REFUTED"}), + ) + ) + return settle(Obligations.fix(obligations, source="verify_draft"), results) + if case.expect == "refuted": + final_subject = Subject("final", case.name or "case") + final_code = case.recheck or case.outcome + return settle( + Obligations.fix([subject, final_subject], source="verify_draft"), + [ + Result.from_code( + subject, + case.outcome, + held=frozenset( + {"CONFIRMED", "REFUTED", "UNCERTAIN", "INDETERMINATE"} + ), + refuted=frozenset(), + ), + Result.from_code( + final_subject, + final_code, + held=frozenset({"REFUTED", "UNCERTAIN", "INDETERMINATE"}), + refuted=frozenset({"CONFIRMED", "NONE"}), + ), + ], + ) + return settle( + Obligations.fix([subject], source="verify_draft"), + [Result(subject, Status.NOT_CHECKED, reason=f"unknown expect {case.expect!r}")], + ) + + class Qualifier: """Runs one draft through the admission suite on the sandbox.""" @@ -614,114 +689,99 @@ def run( ) started = time.monotonic() - try: - data = self._fast(contract) - c = Contract.from_dict(data, name="draft") - params = self._params(values, actor) - self.store.restore(self.demo.base) - ledger = Ledger(MemoryLedger()) + draft_problem: list[DraftProblem] = [] + + def _execute() -> Optional[tuple[Rows, Rows]]: try: - pending = begin_write( - c, - params, - actor=Actor("agent", f"verify-draft-{actor}"), - ledger=ledger, - write_key=uuid.uuid4().hex, - workdir=self.workdir, - ) - except (WriteBlocked, VerifierError) as exc: - case.outcome = "NO_BASELINE" - case.reasons = [str(exc)] - return None - if before is not None: - note = before() - if note: - case.untestable = True # the setup step itself failed - case.note = note - return None - statuses = self.app.send( - self.demo.writes, actor, swap_map(self.demo.params, values) - ) - if any(s >= 400 for s in statuses): - # For a clean write: the values were invalid (the caller - # skips them). For anything else the case can't be built. - self.refused_statuses = list(statuses) - case.applicable = False - case.untestable = case.group != "clean" - case.note = f"the app refused the write (HTTP {max(statuses)})" - return None - pre = self.demo.base - post = self.store.read_moved(pre) - if fault is not None: - fault(pre, post) - post = self.store.read_moved(pre) - result = verify_write(pending, seal=False) - case.outcome = result.outcome.value - case.reasons = list(result.reasons) - case.moved = list( - ((result.evidence or {}).get("frame") or {}).get("moves") or [] - )[:20] - if rechecks and result.outcome.value == _CONFIRMED_LABEL: - if result.recheck is None: - case.recheck = "NONE" - case.reasons.append( - "no recheck was scheduled: set frame.database.recheck_after_s" - ) - else: - if revert is not None: - revert(pre, post) - rr = recheck( + data = self._fast(contract) + c = Contract.from_dict(data, name="draft") + params = self._params(values, actor) + self.store.restore(self.demo.base) + ledger = Ledger(MemoryLedger()) + try: + pending = begin_write( c, - result, - params=params, + params, actor=Actor("agent", f"verify-draft-{actor}"), - wait=True, ledger=ledger, + write_key=uuid.uuid4().hex, + workdir=self.workdir, ) - case.recheck = str(getattr(rr.outcome, "value", rr.outcome)) - case.reasons += list(rr.reasons) - return pre, post - except DraftProblem: - raise - except ( - _NotApplicable, - _Untestable, - VerifierError, - WriteBlocked, - OSError, - RuntimeError, - ValueError, - TypeError, - LookupError, - ArithmeticError, - ) as exc: - case.outcome = case.outcome or _ERROR_LABEL - case.reasons.append(f"{type(exc).__name__}: {exc}") + except (WriteBlocked, VerifierError) as exc: + case.outcome = "NO_BASELINE" + case.reasons = [str(exc)] + return None + if before is not None: + note = before() + if note: + case.untestable = True # the setup step itself failed + case.note = note + return None + statuses = self.app.send( + self.demo.writes, actor, swap_map(self.demo.params, values) + ) + if any(s >= 400 for s in statuses): + # For a clean write: the values were invalid (the caller + # skips them). For anything else the case can't be built. + self.refused_statuses = list(statuses) + case.applicable = False + case.untestable = case.group != "clean" + case.note = f"the app refused the write (HTTP {max(statuses)})" + return None + pre = self.demo.base + post = self.store.read_moved(pre) + if fault is not None: + fault(pre, post) + post = self.store.read_moved(pre) + result = verify_write(pending, seal=False) + case.outcome = result.outcome.value + case.reasons = list(result.reasons) + case.moved = list( + ((result.evidence or {}).get("frame") or {}).get("moves") or [] + )[:20] + if rechecks and result.outcome is Outcome.CONFIRMED: + if result.recheck is None: + case.recheck = "NONE" + case.reasons.append( + "no recheck was scheduled: set frame.database.recheck_after_s" + ) + else: + if revert is not None: + revert(pre, post) + rr = recheck( + c, + result, + params=params, + actor=Actor("agent", f"verify-draft-{actor}"), + wait=True, + ledger=ledger, + ) + case.recheck = str(getattr(rr.outcome, "value", rr.outcome)) + case.reasons += list(rr.reasons) + return pre, post + except DraftProblem as exc: + draft_problem.append(exc) + raise FailClosed(str(exc)) from exc + + try: + obs = observe(_execute) + if isinstance(obs, Errored): + case.outcome = case.outcome or "ERROR" + case.reasons.append(f"{obs.exc_type}: {obs.reason}") + return None + if isinstance(obs, Observed): + return obs.value # type: ignore[return-value] return None + except FailClosed: + if draft_problem: + raise draft_problem[0] from None + raise finally: case.seconds = round(time.monotonic() - started, 2) @staticmethod def _judge(case: Case) -> None: - if case.untestable: - case.passed = False - return - if not case.applicable: - case.passed = True - return - if case.expect == _EXPECT_CONFIRMED: - # No recheck scheduled is the late-revert case's failure, not a - # false stop on a clean write. - case.passed = ( - case.outcome == _CONFIRMED_LABEL and case.recheck in _OK_RECHECKS - ) - else: - final = case.recheck or case.outcome - case.passed = ( - case.outcome not in _BROKEN_LABELS - and final != _CONFIRMED_LABEL - and final != "NONE" - ) + case.passed = judge_case(case).passes # -- the suite @@ -1047,7 +1107,7 @@ def undo(pre: Rows, post: Rows) -> None: self.store.update(m.table, m.key, {c: m.b[c] for c in m.columns}) self.run(contract, case, values=values, revert=undo, rechecks=True) - if case.outcome == _CONFIRMED_LABEL and not case.recheck: + if case.outcome == Outcome.CONFIRMED.value and not case.recheck: case.recheck = "NONE" return [case] @@ -1137,7 +1197,7 @@ def guarded(pre: Rows, post: Rows) -> None: self.run(contract, case, values=values, fault=guarded) finally: if not case.applicable or case.untestable: - case.outcome = case.outcome if case.outcome != _ERROR_LABEL else "" + case.outcome = "" case.reasons = [ r for r in case.reasons diff --git a/packages/flow/openadapt_flow/verify_draft/inputs.py b/packages/flow/openadapt_flow/verify_draft/inputs.py index c530fd29e1..277a4249a4 100644 --- a/packages/flow/openadapt_flow/verify_draft/inputs.py +++ b/packages/flow/openadapt_flow/verify_draft/inputs.py @@ -25,7 +25,14 @@ #: Longest description text sent to the model. MAX_DESCRIPTION_CHARS = 40_000 -_SECRET = re.compile(r"pass(word)?|secret|token|api[-_]?key|session|csrf|auth", re.I) +#: Shared secret-looking field/header/column name pattern (also imported by admit.py). +SECRET_NAME_RE = re.compile( + r"pass(word)?|secret|token|api[-_]?key|hash|salt|session|csrf|auth" + r"|credential|bearer|refresh|private[-_]?key|access[-_]?key" + r"|(^|[^a-z0-9])(cred|pin|otp|tfa|jwt)([^a-z0-9]|$)", + re.I, +) +_SECRET = SECRET_NAME_RE _SECRET_HEADERS = frozenset( { "authorization", @@ -239,39 +246,81 @@ def writes( return [r for r in trace if r.method not in _READS and r.path not in skip_paths] -def _mask_json(value: Any) -> Any: +def _mask_json(value: Any, *, mask_scalars: bool = False) -> Any: if isinstance(value, dict): return { - k: ( - "***" - if _SECRET.search(str(k)) and not isinstance(v, (dict, list)) - else _mask_json(v) + k: _mask_json( + v, + mask_scalars=mask_scalars or bool(SECRET_NAME_RE.search(str(k))), ) for k, v in value.items() } if isinstance(value, list): - return [_mask_json(v) for v in value] - return value + return [_mask_json(v, mask_scalars=mask_scalars) for v in value] + return "***" if mask_scalars else value + + +def _mask_multipart(body: str, mime: str) -> str: + from email.parser import BytesParser + from email.policy import default + + raw = f"Content-Type: {mime}\r\nMIME-Version: 1.0\r\n\r\n".encode( + "utf-8" + ) + body.encode("utf-8", errors="replace") + msg = BytesParser(policy=default).parsebytes(raw) + if not msg.is_multipart(): + return "" + fields: list[dict[str, str]] = [] + for part in msg.iter_parts(): + name = str(part.get_param("name", header="content-disposition") or "") + filename = part.get_filename() + if filename is not None: + fields.append({"name": name, "filename": str(filename), "value": "***"}) + continue + if not name or SECRET_NAME_RE.search(name): + fields.append({"name": name, "value": "***"}) + continue + payload = part.get_content() + text_val = payload if isinstance(payload, str) else "" + fields.append({"name": name, "value": text_val[:500]}) + if not fields: + return "" + return json.dumps({"multipart_fields": fields})[:2000] def _mask_body(body: Optional[str], mime: str) -> Optional[str]: if body is None: return None - if "json" in mime: + mime_low = (mime or "").lower() + if "json" in mime_low: try: - return json.dumps(_mask_json(json.loads(body))) + return json.dumps(_mask_json(json.loads(body)))[:2000] except ValueError: return "***" - if "x-www-form-urlencoded" in mime: + if "x-www-form-urlencoded" in mime_low: from urllib.parse import parse_qsl, urlencode return urlencode( [ - (k, "***" if _SECRET.search(k) else v) + (k, "***" if SECRET_NAME_RE.search(k) else v) for k, v in parse_qsl(body, keep_blank_values=True) ] - ) - return body[:2000] + )[:2000] + if "multipart/form-data" in mime_low: + return _mask_multipart(body, mime) + return "" + + +def _mask_response(response: Optional[str], *, response_chars: int) -> Optional[str]: + if response is None: + return None + stripped = response.lstrip() + if stripped[:1] in "{[": + try: + return json.dumps(_mask_json(json.loads(response)))[:response_chars] or None + except ValueError: + return "" + return "" def masked(req: Request, *, response_chars: int = 1500) -> dict[str, Any]: @@ -283,24 +332,20 @@ def masked(req: Request, *, response_chars: int = 1500) -> dict[str, Any]: parts = urlsplit(req.url) query = urlencode( [ - (k, "***" if _SECRET.search(k) else v) + (k, "***" if SECRET_NAME_RE.search(k) else v) for k, v in parse_qsl(parts.query, keep_blank_values=True) ] ) - response = req.response - if response is not None: - response = _mask_body( - response, "json" if response.lstrip()[:1] in "{[" else "text" - ) + response = _mask_response(req.response, response_chars=response_chars) return { "method": req.method, "url": urlunsplit(("", "", parts.path, query, "")), "headers": { k: v for k, v in req.headers.items() - if k.lower() not in _SECRET_HEADERS and not _SECRET.search(k) + if k.lower() not in _SECRET_HEADERS and not SECRET_NAME_RE.search(k) }, "body": _mask_body(req.body, req.mime), "status": req.status, - "response": (response or "")[:response_chars] or None, + "response": response, } diff --git a/packages/flow/tests/failopen/sites/verify_draft_admit.py b/packages/flow/tests/failopen/sites/verify_draft_admit.py new file mode 100644 index 0000000000..cc0541959c --- /dev/null +++ b/packages/flow/tests/failopen/sites/verify_draft_admit.py @@ -0,0 +1,126 @@ +"""verify_draft.judge_case (C3 C5): admission cases settle on the verdict kernel. + +An untestable case, an empty/error/no-baseline outcome, or an unlisted +outcome or expectation code must settle as NOT_CHECKED and never pass. +""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.verdict import Status +from openadapt_flow.verify_draft.admit import Case, judge_case +from tests.failopen.harness import CodeCase, Seed, SiteSpec, register + + +def _run(ev: dict[str, Any]) -> Any: + case = Case( + group=ev.get("group", "clean"), + name=ev.get("name", "c1"), + detail="d", + expect=ev["expect"], + outcome=ev["outcome"], + recheck=ev.get("recheck", ""), + applicable=ev.get("applicable", True), + untestable=ev.get("untestable", False), + ) + return judge_case(case) + + +def _level(out: Any) -> Status: + if out.passes: + return Status.HELD + if out.refuted: + return Status.REFUTED + return Status.NOT_CHECKED + + +def _codes() -> list[CodeCase]: + return [ + CodeCase( + evidence={"expect": "confirmed", "outcome": "MYSTERY_CODE", "recheck": ""}, + may_have_changed=True, + forbidden=lambda out: out.passes, + label="unknown outcome on confirmed case", + unknown=True, + ), + CodeCase( + evidence={ + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "MYSTERY_RECHECK", + }, + may_have_changed=True, + forbidden=lambda out: out.passes, + label="unknown recheck on confirmed case", + unknown=True, + ), + CodeCase( + evidence={"expect": "refuted", "outcome": "MYSTERY_CODE", "recheck": ""}, + may_have_changed=True, + forbidden=lambda out: out.passes, + label="unknown outcome on refuted case", + unknown=True, + ), + CodeCase( + evidence={ + "expect": "unknown_expect", + "outcome": "CONFIRMED", + "recheck": "", + }, + may_have_changed=True, + forbidden=lambda out: out.passes, + label="unknown expect mode", + unknown=True, + ), + CodeCase( + evidence={ + "expect": "confirmed", + "outcome": "CONFIRMED", + "recheck": "CONFIRMED", + "untestable": True, + }, + may_have_changed=True, + forbidden=lambda out: out.passes, + label="untestable case never holds", + ), + ] + + +register( + SiteSpec( + id="verify_draft.judge_case", + classes="C3 C5", + target="openadapt_flow.verify_draft.admit:judge_case", + run=_run, + is_pass=lambda out: out.passes, + level=_level, + seeds=lambda: [ + Seed( + {"expect": "confirmed", "outcome": "CONFIRMED", "recheck": "CONFIRMED"}, + True, + ), + Seed( + {"expect": "refuted", "outcome": "REFUTED", "recheck": ""}, + True, + ), + Seed( + {"expect": "refuted", "outcome": "CONFIRMED", "recheck": "REFUTED"}, + True, + ), + Seed( + {"expect": "confirmed", "outcome": "REFUTED", "recheck": ""}, + False, + ), + Seed( + {"expect": "refuted", "outcome": "CONFIRMED", "recheck": "NONE"}, + False, + ), + Seed( + {"expect": "refuted", "outcome": "ERROR", "recheck": ""}, + False, + ), + ], + codes=_codes, + ) +) diff --git a/packages/flow/tests/test_verify_draft.py b/packages/flow/tests/test_verify_draft.py index 4b0a254058..ef03a13f14 100644 --- a/packages/flow/tests/test_verify_draft.py +++ b/packages/flow/tests/test_verify_draft.py @@ -549,3 +549,148 @@ def test_a_skip_of_a_table_that_never_moves_is_refused(mockloan: Path) -> None: assert not outcome.admitted problems = [a for a in outcome.admissions[0].attribution if a.problem] assert any(a.table == "metadata" and "skipped table" in a.problem for a in problems) + + +def test_masked_redacts_all_secret_shapes() -> None: + """Every secret shape probed in review is masked before reaching a model.""" + from openadapt_flow.verify_draft.inputs import masked + from openadapt_flow.verify_draft.sandbox import Request + + # 1. JSON list under a secret key + r1 = masked( + Request( + method="POST", + url="https://app.test/api/auth", + headers={}, + body='{"token": ["tok-alpha", "tok-beta"], "user": "ada"}', + mime="application/json", + status=200, + response='{"ok": true}', + ) + ) + assert "tok-alpha" not in (r1["body"] or "") + assert "tok-beta" not in (r1["body"] or "") + assert '"ada"' in (r1["body"] or "") + + # 2. credential, pin, otp, jwt keys + r2 = masked( + Request( + method="POST", + url="https://app.test/api/login", + headers={}, + body='{"credential": "c-val", "pin": "4321", "otp": "998877", "jwt": "eyJ.secret.sig", "title": "note"}', + mime="application/json", + status=200, + response=None, + ) + ) + for leak in ("c-val", "4321", "998877", "eyJ.secret.sig"): + assert leak not in (r2["body"] or "") + assert '"note"' in (r2["body"] or "") + + # 3. multipart/form-data password + boundary = "----TestBoundary7MA4YWxkTrZu0gW" + mp_body = ( + f"--{boundary}\r\n" + 'Content-Disposition: form-data; name="username"\r\n\r\n' + "ada\r\n" + f"--{boundary}\r\n" + 'Content-Disposition: form-data; name="password"\r\n\r\n' + "super-secret-pw\r\n" + f"--{boundary}--\r\n" + ) + r3 = masked( + Request( + method="POST", + url="https://app.test/login", + headers={}, + body=mp_body, + mime=f"multipart/form-data; boundary={boundary}", + status=200, + response=None, + ) + ) + assert "super-secret-pw" not in (r3["body"] or "") + assert "ada" in (r3["body"] or "") + + # 4. text/plain body replaced with placeholder + r4 = masked( + Request( + method="POST", + url="https://app.test/raw", + headers={}, + body="Bearer raw-secret-token-123", + mime="text/plain", + status=200, + response=None, + ) + ) + assert "raw-secret-token-123" not in (r4["body"] or "") + assert r4["body"] == "" + + # 5. HTML response with csrf_token input replaced with placeholder + r5 = masked( + Request( + method="GET", + url="https://app.test/form", + headers={}, + body=None, + mime="", + status=200, + response='
', + ) + ) + assert "csrf-secret-999" not in (r5["response"] or "") + assert r5["response"] == "" + + # 6. Secret inside a JSON response list (refresh) + r6 = masked( + Request( + method="POST", + url="https://app.test/sessions", + headers={}, + body=None, + mime="", + status=200, + response='[{"id": 1, "refresh": "ref-secret-xyz"}]', + ) + ) + assert "ref-secret-xyz" not in (r6["response"] or "") + assert '"***"' in (r6["response"] or "") + + +def test_qualifier_run_records_sqlite_driver_error_as_error_case( + mockloan: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A DB driver error (e.g. sqlite3.OperationalError) becomes an ERROR case + rather than aborting the whole qualification report.""" + import sqlite3 + + from openadapt_flow.verify_draft import admit as A + from openadapt_flow.verify_draft import inputs as I + from openadapt_flow.verify_draft import sandbox as S + + cfg = S.load_sandbox(mockloan / "sandbox.yaml") + task = I.load_task(mockloan / "task.yaml") + store = S.Store(cfg.store) + app = S.App(cfg) + writes = I.writes( + I.load_trace(mockloan / "trace.har"), skip_paths=app.login_paths() + ) + base = store.read() + demo = A.record_demo(store, app, writes, task.params, base) + contract = A.prepare(GOOD, cfg) + + q = A.Qualifier(cfg, store, app, demo) + case = A.Case("clean", "clean-1", "db fault", "confirmed") + + def boom(_base: Any) -> Any: + raise sqlite3.OperationalError("database is locked") + + monkeypatch.setattr(store, "read_moved", boom) + got = q.run(contract, case, values=demo.params) + assert got is None + assert case.outcome == "ERROR" + assert any("OperationalError" in r for r in case.reasons) + q._judge(case) + assert case.passed is False