From fdecf7e79a592833e5eb83cb449b05311cc8eeeb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:22:57 -0500 Subject: [PATCH 01/21] feat(plan): dry-run, idempotent apply, verified undo and receipts for external writes --- openadapt/cli.py | 21 + packages/flow/openadapt_flow/__main__.py | 4 + .../flow/openadapt_flow/txplan/__init__.py | 4 + .../flow/openadapt_flow/txplan/__main__.py | 5 + .../flow/openadapt_flow/txplan/adapters.py | 687 +++++++++++++++ packages/flow/openadapt_flow/txplan/cli.py | 174 ++++ packages/flow/openadapt_flow/txplan/engine.py | 801 ++++++++++++++++++ packages/flow/openadapt_flow/txplan/spec.py | 273 ++++++ packages/flow/openadapt_flow/txplan/state.py | 263 ++++++ packages/flow/tests/test_txplan.py | 464 ++++++++++ packages/flow/tests/txplan_servers.py | 183 ++++ 11 files changed, 2879 insertions(+) create mode 100644 packages/flow/openadapt_flow/txplan/__init__.py create mode 100644 packages/flow/openadapt_flow/txplan/__main__.py create mode 100644 packages/flow/openadapt_flow/txplan/adapters.py create mode 100644 packages/flow/openadapt_flow/txplan/cli.py create mode 100644 packages/flow/openadapt_flow/txplan/engine.py create mode 100644 packages/flow/openadapt_flow/txplan/spec.py create mode 100644 packages/flow/openadapt_flow/txplan/state.py create mode 100644 packages/flow/tests/test_txplan.py create mode 100644 packages/flow/tests/txplan_servers.py diff --git a/openadapt/cli.py b/openadapt/cli.py index 11b9ee09c3..50bcdc287d 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1880,6 +1880,27 @@ def hooks(command_ctx: click.Context) -> None: sys.exit(int(hooks_main(list(command_ctx.args)) or 0)) +@main.command( + "plan", + context_settings={ + "ignore_unknown_options": True, + "allow_extra_args": True, + "help_option_names": [], + }, +) +@click.pass_context +def plan(command_ctx: click.Context) -> None: + """Dry-run a batch of writes to external systems, then apply, undo or release it.""" + _require_supported_python() + plan_main = _optional_engine_entrypoint(command_ctx, ("openadapt_flow.txplan.cli",)) + if plan_main is None: + click.echo( + "Error: this openadapt-flow installation has no plan command.", err=True + ) + sys.exit(2) + sys.exit(int(plan_main(list(command_ctx.args)) or 0)) + + @main.command( "wrap", context_settings={ diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index d39e08efdb..5b6350a3a7 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13222,6 +13222,10 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _add_hooks_parser(sub) + from openadapt_flow.txplan.cli import add_parser as _add_plan_parser + + _add_plan_parser(sub) + from openadapt_flow.cli_fleet import register_fleet_parser register_fleet_parser(sub) diff --git a/packages/flow/openadapt_flow/txplan/__init__.py b/packages/flow/openadapt_flow/txplan/__init__.py new file mode 100644 index 0000000000..dca0be99cc --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/__init__.py @@ -0,0 +1,4 @@ +"""External transaction safety for agent writes: plan, apply, undo, release. + +See ``docs/TRANSACTIONS.md`` and :mod:`openadapt_flow.txplan.engine`. +""" diff --git a/packages/flow/openadapt_flow/txplan/__main__.py b/packages/flow/openadapt_flow/txplan/__main__.py new file mode 100644 index 0000000000..702b30df9b --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/__main__.py @@ -0,0 +1,5 @@ +import sys + +from openadapt_flow.txplan.cli import main + +sys.exit(main()) diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py new file mode 100644 index 0000000000..66a538fadc --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -0,0 +1,687 @@ +"""Read, list, write and compensate, one adapter per kind of system. + +Every adapter speaks in *records*: plain dicts keyed by a record id that is a +string. A *frame* is every record a system shows in the scope a plan touches +(a REST collection, every table of a database, a mailbox), keyed by +``"/"``. A frame diff is what the plan's dry run predicts and +what the read-back after apply and after undo measures. + +* :class:`RestAdapter`: JSON over HTTP. No standard dry run exists, so the + prediction is computed from the baseline and the planned fields (the + ``computed`` dry run), with declared server-set and derived fields. +* :class:`SqlAdapter`: SQLite, MySQL/MariaDB or PostgreSQL over DB-API. The + dry run is a **staged transaction**: the planned statements run inside a + transaction, every table is read before and after inside it, and the + transaction is rolled back. Triggers and cascades show up in the diff. +* :class:`MailAdapter`: SMTP out, a Mailpit API to read back. A send is + irreversible, so it waits in the holdback queue; the Message-ID is derived + from the idempotency key, so a release after a crash finds the message it + already sent instead of sending a second. +""" + +from __future__ import annotations + +import base64 +import datetime as _dt +import decimal +import hashlib +import importlib +import json +import os +import re +import time +from typing import Any, Callable, Mapping, Optional, Sequence + +from openadapt_flow.txplan.spec import ( + Collection, + MailSystem, + RestSystem, + SqlSystem, + TxSpecError, +) + +Record = dict[str, Any] +Frame = dict[str, str] # "/" -> digest of the normalized record + + +class AdapterError(RuntimeError): + """A read or a write failed. For a write, delivery is unknown.""" + + +# -- values -------------------------------------------------------------------- + + +def tag(value: Any) -> Any: + """A JSON form of a database value that decodes to the same type.""" + if isinstance(value, (bytes, bytearray, memoryview)): + return {"$t": "bytes", "v": base64.b64encode(bytes(value)).decode()} + if isinstance(value, decimal.Decimal): + return {"$t": "dec", "v": str(value)} + if isinstance(value, _dt.datetime): + return {"$t": "dt", "v": value.isoformat()} + if isinstance(value, _dt.date): + return {"$t": "date", "v": value.isoformat()} + if isinstance(value, _dt.timedelta): + return {"$t": "td", "v": value.total_seconds()} + return value + + +def untag(value: Any) -> Any: + if isinstance(value, dict) and set(value) == {"$t", "v"}: + kind, raw = value["$t"], value["v"] + if kind == "bytes": + return base64.b64decode(raw) + if kind == "dec": + return decimal.Decimal(raw) + if kind == "dt": + return _dt.datetime.fromisoformat(raw) + if kind == "date": + return _dt.date.fromisoformat(raw) + if kind == "td": + return _dt.timedelta(seconds=raw) + return value + + +def digest(value: Any) -> str: + raw = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str) + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:24] + + +def same(a: Any, b: Any) -> bool: + """Equal as values (``1`` and ``1.0`` are equal; ``"1"`` and ``1`` aren't; a + datetime equals its ISO text).""" + a, b = untag(a), untag(b) + if isinstance(a, (_dt.date, _dt.datetime)) or isinstance(b, (_dt.date, _dt.datetime)): + def text(v: Any) -> str: + return v.isoformat() if isinstance(v, (_dt.date, _dt.datetime)) else str(v).replace(" ", "T") + + return text(a) == text(b) + if isinstance(a, bool) or isinstance(b, bool): + return a is b or a == b and type(a) is type(b) + if isinstance(a, (int, float, decimal.Decimal)) and isinstance(b, (int, float, decimal.Decimal)): + return decimal.Decimal(str(a)) == decimal.Decimal(str(b)) + return json.dumps(a, sort_keys=True, default=str) == json.dumps(b, sort_keys=True, default=str) + + +# -- diffs --------------------------------------------------------------------- + + +def diff_frames( + before: Mapping[str, Mapping[str, str]], after: Mapping[str, Mapping[str, str]] +) -> dict[str, Any]: + """What moved between two frames of column digests: ids added and removed, + and the changed columns of each id present in both.""" + added = sorted(set(after) - set(before)) + removed = sorted(set(before) - set(after)) + changed: dict[str, list[str]] = {} + for rid in set(before) & set(after): + a, b = before[rid], after[rid] + cols = sorted(c for c in set(a) | set(b) if a.get(c) != b.get(c)) + if cols: + changed[rid] = cols + return {"added": added, "removed": removed, "changed": dict(sorted(changed.items()))} + + +def column_digests(record: Mapping[str, Any], drop: Sequence[str] = ()) -> dict[str, str]: + return {k: digest(tag(v)) for k, v in record.items() if k not in drop} + + +# -- REST ---------------------------------------------------------------------- + + +class RestAdapter: + kind = "rest" + dry_run = "computed" + + def __init__(self, system: RestSystem, client: Any = None) -> None: + import httpx + + self.system = system + headers = {"Accept": "application/json"} + if system.auth is not None: + secret = os.environ.get(system.auth.value_env, "") + if not secret: + raise TxSpecError(f"system {system.name}: ${system.auth.value_env} is not set") + headers[system.auth.header] = system.auth.prefix + secret + self.http = client or httpx.Client( + base_url=system.url(), headers=headers, timeout=system.timeout_s + ) + + @staticmethod + def _fill(path: str, values: Mapping[str, Any]) -> str: + def one(m: re.Match[str]) -> str: + name = m.group(1) + if name not in values or values[name] in (None, ""): + raise AdapterError(f"the path needs {name}") + return str(values[name]) + + return re.sub(r"\{([a-z_][a-z0-9_]*)\}", one, path) + + def _call( + self, + method: str, + path: str, + body: Any = None, + *, + params: Optional[Mapping[str, Any]] = None, + key: Optional[str] = None, + ) -> Any: + headers = {} + if key and self.system.idempotency_header: + headers[self.system.idempotency_header] = key + try: + resp = self.http.request(method, path, json=body, params=params, headers=headers) + except Exception as exc: # noqa: BLE001 - transport failure: delivery unknown + raise AdapterError(f"{method} failed: {type(exc).__name__}") from exc + if resp.status_code == 404 and method == "GET": + return None + if resp.status_code >= 400: + raise AdapterError(f"{method} returned {resp.status_code}") + if not resp.content: + return {} + try: + return resp.json() + except ValueError: + return {} + + def coll(self, name: Optional[str]) -> Collection: + return self.system.collection(name) + + def normalize(self, coll: Collection, record: Mapping[str, Any]) -> Record: + return {k: v for k, v in record.items() if k not in coll.server_fields} + + def read(self, collection: Optional[str], rid: str) -> Optional[Record]: + coll = self.coll(collection) + got = self._call(coll.read.method, self._fill(coll.read.path, {"id": rid})) + if got is None: + return None + if not isinstance(got, dict): + raise AdapterError("a read did not return an object") + return got + + def frame(self, collection: Optional[str]) -> dict[str, dict[str, str]]: + coll = self.coll(collection) + route = coll.list + out: dict[str, dict[str, str]] = {} + page = 1 + while True: + params: dict[str, Any] = {} + if route.page_param: + params[route.page_param] = page + if route.per_page_param: + params[route.per_page_param] = route.per_page + got = self._call(route.method, route.path, params=params) + items = got if isinstance(got, list) else (got or {}).get("items", []) + if not isinstance(items, list): + raise AdapterError("a list did not return a list") + fresh = 0 + for item in items: + rid = f"{coll.name}/{item.get(coll.id_field)}" + if rid not in out: + fresh += 1 + out[rid] = column_digests(self.normalize(coll, item)) + if not route.page_param or len(items) < route.per_page or not fresh: + return out + page += 1 + if page > 10_000: + raise AdapterError("the list never ended") + + def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + coll = self.coll(write.get("collection")) + fields = dict(write.get("fields") or {}) + op = write["op"] + if op == "create": + return {"added": {coll.name: 1}, "changed": {}, "removed": [], "derived": {}} + rid = f"{coll.name}/{write['id']}" + if op == "delete": + return {"added": {}, "changed": {}, "removed": [rid], "derived": {}} + base = baseline or {} + cols = sorted( + k for k, v in fields.items() if k not in coll.server_fields and not same(base.get(k), v) + ) + derived = sorted({d for c in cols for d in coll.derived.get(c, [])} - set(cols)) + return { + "added": {}, + "changed": {rid: cols} if cols else {}, + "removed": [], + "derived": {rid: derived} if derived else {}, + } + + def _body(self, coll: Collection, route: Any, base: Optional[Record], fields: Mapping[str, Any]) -> Record: + if route.replace and base is not None: + body = {k: v for k, v in base.items() if k not in coll.server_fields} + body.update(fields) + return body + return dict(fields) + + def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) -> dict[str, Any]: + coll = self.coll(write.get("collection")) + op = write["op"] + fields = dict(write.get("fields") or {}) + route = getattr(coll, op, None) + if route is None: + raise AdapterError(f"{coll.name} declares no {op}") + values = {**(baseline or {}), **fields, "id": write.get("id")} + got = self._call( + route.method, + self._fill(route.path, values), + None if op == "delete" else self._body(coll, route, baseline, fields), + key=key, + ) + if op == "create": + rid = (got or {}).get(route.id_from or coll.id_field) + if rid in (None, ""): + raise AdapterError("the create returned no id") + return {"id": str(rid)} + return {"id": str(write["id"])} + + def compensate( + self, write: Mapping[str, Any], baseline: Optional[Record], result: Mapping[str, Any], key: str + ) -> None: + coll = self.coll(write.get("collection")) + op = write["op"] + rid = str(result.get("id") or write.get("id")) + if op == "create": + route = coll.delete + if route is None: + raise AdapterError(f"{coll.name} declares no delete, so a create can't be undone") + self._call(route.method, self._fill(route.path, {"id": rid}), key=key + ":undo") + return + if op == "update": + route = coll.update + assert route is not None and baseline is not None + changed = list(write.get("fields") or {}) + restore = ( + {k: v for k, v in baseline.items() if k not in coll.server_fields} + if route.replace + else {k: baseline.get(k) for k in changed} + ) + self._call( + route.method, self._fill(route.path, {**baseline, "id": rid}), restore, key=key + ":undo" + ) + return + raise AdapterError(f"no exact undo for a REST {op}") + + def expected_after( + self, write: Mapping[str, Any], baseline: Optional[Record] + ) -> Optional[dict[str, Any]]: + """The planned fields, for the record read-back after apply.""" + if write["op"] == "delete": + return None + coll = self.coll(write.get("collection")) + return {k: v for k, v in (write.get("fields") or {}).items() if k not in coll.server_fields} + + def frame_id(self, write: Mapping[str, Any], result: Mapping[str, Any]) -> str: + return f"{write.get('collection')}/{result.get('id') or write.get('id')}" + + +# -- SQL ----------------------------------------------------------------------- + + +class SqlAdapter: + kind = "sql" + dry_run = "staged_transaction" + + def __init__(self, system: SqlSystem, root: Any = None) -> None: + self.system = system + self.root = root + self.ph = "?" if system.dialect == "sqlite" else "%s" + self.q = "`" if system.dialect == "mysql" else '"' + + # connection ------------------------------------------------------------- + + def connect(self) -> Any: + s = self.system + if s.dialect == "sqlite": + import sqlite3 + from pathlib import Path + + path = Path(str(s.path)) + if not path.is_absolute() and self.root is not None: + path = Path(self.root) / path + con = sqlite3.connect(str(path), isolation_level=None) + return con + module = importlib.import_module(str(s.driver)) + args = dict(s.connect_args) + if s.password_env: + pw = os.environ.get(s.password_env) + if pw is None: + raise TxSpecError(f"system {s.name}: ${s.password_env} is not set") + args["password"] = pw + con = module.connect(**args) + if hasattr(con, "autocommit") and callable(getattr(con, "autocommit")): + con.autocommit(False) # pymysql + return con + + def read_mapping(self) -> dict[str, Any]: + """The read connection in ``frame.database.read`` form, for the verifier.""" + s = self.system + if s.dialect == "sqlite": + from pathlib import Path + + path = Path(str(s.path)) + if not path.is_absolute() and self.root is not None: + path = Path(self.root) / path + return {"sqlite_database": str(path)} + return { + "sql_driver": s.driver, + "sql_connect_args": dict(s.connect_args), + **({"sql_password_env": s.password_env} if s.password_env else {}), + } + + def _begin(self, cur: Any) -> None: + cur.execute("BEGIN" if self.system.dialect != "mysql" else "START TRANSACTION") + + def _ident(self, name: str) -> str: + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_$]{0,63}", name): + raise AdapterError(f"bad identifier {name!r}") + return f"{self.q}{name}{self.q}" + + # reading ---------------------------------------------------------------- + + def _tables(self, cur: Any) -> list[str]: + d = self.system.dialect + if d == "sqlite": + cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") + elif d == "mysql": + cur.execute( + "SELECT table_name FROM information_schema.tables " + "WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'" + ) + else: + cur.execute("SELECT tablename FROM pg_tables WHERE schemaname = current_schema()") + names = sorted(str(r[0]) for r in cur.fetchall()) + return [n for n in names if n not in self.system.frame_ignore_tables] + + def _pk(self, cur: Any, table: str) -> list[str]: + if table in self.system.tables: + return [self.system.tables[table]] + d = self.system.dialect + if d == "sqlite": + cur.execute(f"PRAGMA table_info({self._ident(table)})") + cols = sorted((r[5], r[1]) for r in cur.fetchall() if r[5]) + return [c for _, c in cols] + if d == "mysql": + cur.execute( + "SELECT column_name FROM information_schema.key_column_usage WHERE " + "table_schema = DATABASE() AND table_name = %s AND constraint_name = 'PRIMARY' " + "ORDER BY ordinal_position", + (table,), + ) + else: + cur.execute( + "SELECT a.attname FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid " + "AND a.attnum = ANY(i.indkey) WHERE i.indrelid = %s::regclass AND i.indisprimary", + (table,), + ) + return [str(r[0]) for r in cur.fetchall()] + + def _ignored(self, table: str, col: str) -> bool: + rules = self.system.frame_ignore_columns + return f"{table}.{col}" in rules or f"*.{col}" in rules + + def _rows(self, cur: Any, table: str) -> tuple[list[str], list[tuple[Any, ...]]]: + cur.execute(f"SELECT * FROM {self._ident(table)}") + cols = [str(d[0]) for d in cur.description] + return cols, list(cur.fetchall()) + + def frame_cur(self, cur: Any) -> dict[str, dict[str, str]]: + out: dict[str, dict[str, str]] = {} + total = 0 + for table in self._tables(cur): + pk = self._pk(cur, table) + cols, rows = self._rows(cur, table) + total += len(rows) + if total > self.system.max_frame_rows: + raise AdapterError("the database has more rows than max_frame_rows") + seen: dict[str, int] = {} + for row in rows: + rec = dict(zip(cols, row)) + digs = {c: digest(tag(v)) for c, v in rec.items() if not self._ignored(table, c)} + if pk and all(c in rec for c in pk): + rid = "|".join(str(rec[c]) for c in pk) + else: # no key: the whole row is its identity + base = digest(digs) + seen[base] = seen.get(base, 0) + 1 + rid = f"~{base}#{seen[base]}" + out[f"{table}/{rid}"] = digs + return out + + def frame(self, collection: Optional[str] = None) -> dict[str, dict[str, str]]: + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + return self.frame_cur(cur) + finally: + con.rollback() + finally: + con.close() + + def _read_cur(self, cur: Any, table: str, rid: str) -> Optional[Record]: + key = self.system.tables.get(table) + if key is None: + raise AdapterError(f"table {table} is not declared") + cur.execute( + f"SELECT * FROM {self._ident(table)} WHERE {self._ident(key)} = {self.ph}", (rid,) + ) + cols = [str(d[0]) for d in cur.description] + rows = cur.fetchall() + if len(rows) > 1: + raise AdapterError(f"{table}.{key} is not unique") + return {c: tag(v) for c, v in zip(cols, rows[0])} if rows else None + + def read(self, collection: Optional[str], rid: str) -> Optional[Record]: + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + return self._read_cur(cur, str(collection), rid) + finally: + con.rollback() + finally: + con.close() + + def normalize(self, coll: Any, record: Mapping[str, Any]) -> Record: + return dict(record) + + # writing ---------------------------------------------------------------- + + def _exec(self, cur: Any, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + table = str(write["collection"]) + key = self.system.tables.get(table) + if key is None: + raise AdapterError(f"table {table} is not declared") + op = write["op"] + fields = {k: untag(v) for k, v in (write.get("fields") or {}).items()} + t = self._ident(table) + if op == "create": + cols = list(fields) + sql = ( + f"INSERT INTO {t} ({', '.join(self._ident(c) for c in cols)}) " + f"VALUES ({', '.join([self.ph] * len(cols))})" + ) + if self.system.dialect == "postgresql": + sql += f" RETURNING {self._ident(key)}" + cur.execute(sql, tuple(fields[c] for c in cols)) + if self.system.dialect == "postgresql": + rid = cur.fetchone()[0] + else: + rid = fields.get(key, cur.lastrowid) + if cur.rowcount != 1: + raise AdapterError("the insert did not add one row") + return {"id": str(rid)} + rid = str(write["id"]) + if op == "update": + sets = ", ".join(f"{self._ident(c)} = {self.ph}" for c in fields) + cur.execute( + f"UPDATE {t} SET {sets} WHERE {self._ident(key)} = {self.ph}", + (*fields.values(), rid), + ) + elif op == "delete": + cur.execute(f"DELETE FROM {t} WHERE {self._ident(key)} = {self.ph}", (rid,)) + else: + raise AdapterError(f"no SQL {op}") + if cur.rowcount != 1 and not (op == "update" and self.system.dialect == "mysql"): + raise AdapterError(f"the {op} touched {cur.rowcount} rows, not one") + return {"id": rid} + + def stage( + self, writes: Sequence[Mapping[str, Any]], baselines: Sequence[Optional[Record]] + ) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """Run the writes inside a transaction, read every table before and + after inside it, and roll back. Returns the frame diff and each + write's staged result.""" + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + before = self.frame_cur(cur) + results = [self._exec(cur, w, b) for w, b in zip(writes, baselines)] + after = self.frame_cur(cur) + finally: + con.rollback() + finally: + con.close() + return diff_frames(before, after), results + + def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + raise NotImplementedError("SQL plans are staged as one transaction") + + def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) -> dict[str, Any]: + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + result = self._exec(cur, write, baseline) + except Exception: + con.rollback() + raise + con.commit() + return result + finally: + con.close() + + def compensate( + self, write: Mapping[str, Any], baseline: Optional[Record], result: Mapping[str, Any], key: str + ) -> None: + op = write["op"] + rid = str(result.get("id") or write.get("id")) + if op == "create": + inverse = {"op": "delete", "collection": write["collection"], "id": rid} + elif op == "update": + assert baseline is not None + inverse = { + "op": "update", + "collection": write["collection"], + "id": rid, + "fields": {k: baseline.get(k) for k in (write.get("fields") or {})}, + } + elif op == "delete": + assert baseline is not None + inverse = {"op": "create", "collection": write["collection"], "fields": dict(baseline)} + else: + raise AdapterError(f"no SQL undo for {op}") + self.apply(inverse, None, key + ":undo") + + def expected_after( + self, write: Mapping[str, Any], baseline: Optional[Record] + ) -> Optional[dict[str, Any]]: + if write["op"] == "delete": + return None + return {k: tag(untag(v)) for k, v in (write.get("fields") or {}).items()} + + def frame_id(self, write: Mapping[str, Any], result: Mapping[str, Any]) -> str: + return f"{write['collection']}/{result.get('id') or write.get('id')}" + + +# -- mail ---------------------------------------------------------------------- + + +class MailAdapter: + kind = "mail" + dry_run = "holdback" + + def __init__(self, system: MailSystem, client: Any = None) -> None: + import httpx + + self.system = system + self.http = client or httpx.Client(base_url=system.mailbox.url(), timeout=20.0) + + @staticmethod + def message_id(key: str) -> str: + return f"<{key}@openadapt.tx>" + + def _messages(self) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + start = 0 + while True: + resp = self.http.get("/api/v1/messages", params={"start": start, "limit": 250}) + if resp.status_code >= 400: + raise AdapterError(f"the mailbox returned {resp.status_code}") + page = resp.json().get("messages") or [] + out += page + if len(page) < 250: + return out + start += len(page) + + def frame(self, collection: Optional[str] = None) -> dict[str, dict[str, str]]: + out: dict[str, dict[str, str]] = {} + counts: dict[str, int] = {} + for m in self._messages(): + mid = str(m.get("MessageID") or m.get("ID")) + counts[mid] = counts.get(mid, 0) + 1 + out[f"message/{mid}#{counts[mid]}"] = { + "subject": digest(m.get("Subject")), + "to": digest(sorted(a.get("Address", "") for a in m.get("To") or [])), + } + return out + + def count(self, key: str) -> int: + mid = self.message_id(key).strip("<>") + return sum(1 for m in self._messages() if str(m.get("MessageID", "")).strip("<>") == mid) + + def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + return {"added": {}, "changed": {}, "removed": [], "derived": {}, "queued": 1} + + def send(self, write: Mapping[str, Any], key: str, *, smtp_factory: Optional[Callable[..., Any]] = None) -> None: + import smtplib + from email.message import EmailMessage + + fields = dict(write.get("fields") or {}) + msg = EmailMessage() + msg["From"] = self.system.sender + to = fields.get("to") + msg["To"] = ", ".join(to) if isinstance(to, list) else str(to) + msg["Subject"] = str(fields.get("subject", "")) + msg["Message-ID"] = self.message_id(key) + msg["X-OpenAdapt-Key"] = key + msg.set_content(str(fields.get("body", ""))) + factory = smtp_factory or smtplib.SMTP + try: + with factory(self.system.smtp.host, self.system.smtp.port, timeout=20) as smtp: + smtp.send_message(msg) + except Exception as exc: # noqa: BLE001 - delivery unknown + raise AdapterError(f"SMTP failed: {type(exc).__name__}") from exc + + def wait_count(self, key: str, want: int, timeout_s: float = 10.0) -> int: + deadline = time.monotonic() + timeout_s + n = self.count(key) + while n < want and time.monotonic() < deadline: + time.sleep(0.2) + n = self.count(key) + return n + + +def adapter_for(system: Any, root: Any = None) -> Any: + if isinstance(system, RestSystem): + return RestAdapter(system) + if isinstance(system, SqlSystem): + return SqlAdapter(system, root) + if isinstance(system, MailSystem): + return MailAdapter(system) + raise TxSpecError(f"unknown system kind {type(system).__name__}") diff --git a/packages/flow/openadapt_flow/txplan/cli.py b/packages/flow/openadapt_flow/txplan/cli.py new file mode 100644 index 0000000000..d5de556154 --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/cli.py @@ -0,0 +1,174 @@ +"""``openadapt plan``: dry-run, apply and undo a batch of writes to external systems. + + openadapt plan create --tx openadapt.tx.yaml --task T-1 writes.json + openadapt plan show PLAN + openadapt plan approve PLAN # a person, at a terminal + openadapt plan apply PLAN + openadapt plan undo PLAN + openadapt plan release PLAN # irreversible writes after holdback + openadapt plan cancel PLAN # drop held writes before release + openadapt plan status + +``create`` reads every record the batch touches, predicts the diff (a staged +transaction for a database, a computed shadow for a REST API, the holdback +queue for email) and prints what would change. ``approve`` binds to that exact +plan digest, once. ``apply`` refuses a plan whose records moved since, and +each write carries an idempotency key derived from the task and the record, +never from the payload: a retried or regenerated write with a different +payload is refused. ``undo`` compensates each write and proves it by reading +every record and the whole frame back. See ``docs/TRANSACTIONS.md``. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Optional, Sequence + + +def add_parser(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "plan", + help="Dry-run a batch of writes to external systems, then apply it, undo it or release it", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + allow_abbrev=False, + ) + _fill(p) + p.set_defaults(func=cmd_plan) + + +def _fill(p: argparse.ArgumentParser) -> None: + verbs = p.add_subparsers(dest="plan_verb", required=True) + + def common(q: argparse.ArgumentParser, tx: bool = True) -> None: + if tx: + q.add_argument("--tx", default="openadapt.tx.yaml", help="the tx file (default: ./openadapt.tx.yaml)") + q.add_argument("--state", help="the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)") + q.add_argument("--json", action="store_true", help="print JSON") + + q = verbs.add_parser("create", help="read the baseline and print the predicted diff") + q.add_argument("--task", required=True, help="the task this batch belongs to (OpenAdapt's id, not the model's)") + q.add_argument("writes", help="a JSON file: a list of writes, or {\"writes\": [...]}; - for stdin") + common(q) + for verb, text in ( + ("show", "print a plan"), + ("apply", "apply an approved plan"), + ("undo", "undo an applied plan and prove it by read-back"), + ("release", "release held irreversible writes whose holdback passed"), + ("cancel", "cancel held writes before release"), + ): + q = verbs.add_parser(verb, help=text) + q.add_argument("plan", help="a plan digest or its prefix") + common(q, tx=verb not in ("show", "cancel")) + q = verbs.add_parser("approve", help="approve one plan digest, once (a person at a terminal)") + q.add_argument("plan") + q.add_argument("--as", dest="approver", default=None, help="who approves (default: $USER)") + q.add_argument( + "--automation", + action="store_true", + help="record the approval as automation (lab runs; the receipt then says agent)", + ) + common(q, tx=False) + q = verbs.add_parser("status", help="list held writes and ledger entries") + common(q, tx=False) + + +def _ctx(args: argparse.Namespace, need_spec: bool = True): # type: ignore[no-untyped-def] + from openadapt_flow.txplan.engine import Ctx + from openadapt_flow.txplan.spec import load_spec + from openadapt_flow.txplan.state import State + + state = State(Path(args.state) if args.state else None) + spec = load_spec(Path(args.tx)) if need_spec else None + return Ctx(spec=spec, state=state) # type: ignore[arg-type] + + +def cmd_plan(args: argparse.Namespace) -> int: + from openadapt_flow.txplan import engine + from openadapt_flow.txplan.adapters import AdapterError + from openadapt_flow.txplan.spec import TxSpecError + from openadapt_flow.txplan.state import StateError + + verb = args.plan_verb + try: + ctx = _ctx(args, need_spec=verb in ("create", "apply", "undo", "release")) + if verb == "status": + out = { + "held": ctx.state.held(), + "ledger": {e.key: e.status for e in ctx.state.entries()}, + } + print(json.dumps(out, indent=2, sort_keys=True)) + return 0 + if verb == "create": + raw = sys.stdin.read() if args.writes == "-" else Path(args.writes).read_text(encoding="utf-8") + data = json.loads(raw) + writes = data.get("writes") if isinstance(data, dict) else data + plan = engine.make_plan(ctx, args.task, writes or []) + if args.json: + print(json.dumps({k: v for k, v in plan.items() if k != "anomaly_details"}, indent=2, sort_keys=True)) + else: + print("\n".join(engine.summary_lines(plan))) + print(f"approve: openadapt plan approve {plan['digest'][:16]}") + return 0 + digest = ctx.state.find_plan(args.plan) + if verb == "show": + plan, priv = engine.load_plan(ctx.state, digest) + plan["anomaly_details"] = priv.get("anomalies", []) + print(json.dumps(plan, indent=2, sort_keys=True) if args.json else "\n".join(engine.summary_lines(plan))) + return 0 + if verb == "approve": + if args.automation: + decided_by = "automation" + else: + if not (sys.stdin.isatty() and sys.stdout.isatty()): + print("approve needs a person at a terminal (or --automation for a lab run)", file=sys.stderr) + return 2 + plan, priv = engine.load_plan(ctx.state, digest) + plan["anomaly_details"] = priv.get("anomalies", []) + print("\n".join(engine.summary_lines(plan))) + typed = input(f"Type the first 8 characters of the plan digest ({digest[:4]}...) to approve: ") + if typed.strip() != digest[:8]: + print("not approved", file=sys.stderr) + return 1 + decided_by = "human" + approver = args.approver or os.environ.get("USER") or "unknown" + engine.approve_plan(ctx.state, digest, approver=approver, decided_by=decided_by) + print(f"approved plan {digest[:12]} once") + return 0 + fn = {"apply": engine.apply_plan, "undo": engine.undo_plan, "release": engine.release}.get(verb) + if verb == "cancel": + n = engine.cancel(ctx, digest) + print(f"cancelled {n} held write(s)") + return 0 + assert fn is not None + result = fn(ctx, digest) + print(json.dumps({k: result[k] for k in ("outcome", "tx", "run_dir")}, indent=2, sort_keys=True)) + return 0 if result["outcome"] in ("VERIFIED", "ROLLED_BACK", "COMPLETED_UNVERIFIED") else 1 + except engine.TxRefused as exc: + print(f"refused: {exc.code}" + (f" ({exc.detail})" if exc.detail else ""), file=sys.stderr) + if exc.report: + print(json.dumps(exc.report, indent=2, sort_keys=True)) + return 3 + except (TxSpecError, StateError, AdapterError, OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="openadapt plan", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + allow_abbrev=False, + ) + _fill(parser) + args = parser.parse_args(list(argv) if argv is not None else None) + return cmd_plan(args) + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py new file mode 100644 index 0000000000..3b266e9c2e --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -0,0 +1,801 @@ +"""Plan, apply, undo and release a batch of writes to external systems. + +``make_plan`` reads every record the batch touches (the baseline) and the +frame around it, predicts the diff with the system's own staged transaction +or a computed shadow, and gives the plan a digest. A person approves that +digest once. ``apply_plan`` refuses a plan whose frame moved since, consumes +the approval, then makes each write under its idempotency key and reads it +back. ``undo_plan`` compensates each applied write, latest first, and proves +the undo by reading every record and the whole frame back to the baseline. +Irreversible writes (email, a delete the API can't reverse) wait in a +cancelable holdback queue until ``release``. + +Each phase writes ``report.json`` (digests and counts, never record values) +and a signed ``record/run/v1`` receipt. Record values live only in the +owner-only state folder. +""" + +from __future__ import annotations + +import os +import secrets +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.txplan.adapters import ( + AdapterError, + MailAdapter, + SqlAdapter, + adapter_for, + column_digests, + diff_frames, + same, +) +from openadapt_flow.txplan.spec import Collection, MailSystem, RestSystem, SqlSystem, TxSpec +from openadapt_flow.txplan.state import ( + State, + StateError, + iso, + now, + read_json, + sha256, + write_private, +) + +PLAN_SCHEMA = "openadapt.tx-plan/v1" +REPORT_SCHEMA = "openadapt.tx-report/v1" +OPS = ("create", "update", "delete", "send") +#: Test hook: exit right after the Nth send, before its outcome is recorded. +CRASH_ENV = "OPENADAPT_TX_CRASH_AFTER_SEND" + + +class TxRefused(RuntimeError): + def __init__(self, code: str, detail: str = "", report: Optional[dict] = None) -> None: + super().__init__(f"{code}: {detail}" if detail else code) + self.code = code + self.detail = detail + self.report = report + + +# -- helpers ------------------------------------------------------------------- + + +def _scope(write: Mapping[str, Any], system: Any) -> str: + """The frame a write belongs to: a REST collection, a whole database, a mailbox.""" + if isinstance(system, RestSystem): + return f"{system.name}:{write.get('collection')}" + return f"{system.name}:*" + + +def _coll(system: Any, write: Mapping[str, Any]) -> Optional[Collection]: + return system.collection(write.get("collection")) if isinstance(system, RestSystem) else None + + +def _irreversible(system: Any, write: Mapping[str, Any]) -> bool: + if isinstance(system, MailSystem): + return True + coll = _coll(system, write) + return bool(coll is not None and write["op"] == "delete" and not coll.delete_reversible) + + +def _norm(system: Any, write: Mapping[str, Any], record: Optional[Mapping[str, Any]]) -> Optional[dict]: + if record is None: + return None + coll = _coll(system, write) + drop = list(coll.server_fields) if coll is not None else [] + if isinstance(system, SqlSystem): + table = str(write.get("collection")) + drop += [ + r.split(".", 1)[1] + for r in system.frame_ignore_columns + if r.startswith(f"{table}.") or r.startswith("*.") + ] + return column_digests(record, drop) + + +def _empty_prediction() -> dict[str, Any]: + return {"added": {}, "changed": {}, "removed": [], "derived": {}} + + +def _merge(into: dict[str, Any], more: Mapping[str, Any]) -> None: + for coll, n in more.get("added", {}).items(): + into["added"][coll] = into["added"].get(coll, 0) + n + for rid, cols in more.get("changed", {}).items(): + into["changed"][rid] = sorted(set(into["changed"].get(rid, [])) | set(cols)) + for rid, cols in more.get("derived", {}).items(): + into["derived"][rid] = sorted(set(into["derived"].get(rid, [])) | set(cols)) + into["removed"] = sorted(set(into["removed"]) | set(more.get("removed", []))) + + +def _staged_to_prediction(diff: Mapping[str, Any]) -> dict[str, Any]: + added: dict[str, int] = {} + for rid in diff["added"]: + table = rid.split("/", 1)[0] + added[table] = added.get(table, 0) + 1 + return { + "added": added, + "changed": dict(diff["changed"]), + "removed": list(diff["removed"]), + "derived": {}, + } + + +def compare(predicted: Mapping[str, Any], actual: Mapping[str, Any]) -> dict[str, Any]: + """Missed effects (the read-back found what the dry run didn't predict) and + false diffs (the dry run predicted what the read-back didn't find), each + counted per record.""" + missed: list[str] = [] + false: list[str] = [] + got_added: dict[str, int] = {} + for rid in actual["added"]: + coll = rid.split("/", 1)[0] + got_added[coll] = got_added.get(coll, 0) + 1 + for coll in set(got_added) | set(predicted["added"]): + extra = got_added.get(coll, 0) - predicted["added"].get(coll, 0) + missed += [f"{coll}/+new"] * max(0, extra) + false += [f"{coll}/+new"] * max(0, -extra) + for rid, cols in actual["changed"].items(): + allowed = set(predicted["changed"].get(rid, [])) | set(predicted["derived"].get(rid, [])) + if set(cols) - allowed: + missed.append(rid) + for rid, cols in predicted["changed"].items(): + if set(cols) - set(actual["changed"].get(rid, [])): + false.append(rid) + missed += [r for r in actual["removed"] if r not in predicted["removed"]] + false += [r for r in predicted["removed"] if r not in actual["removed"]] + return {"missed": sorted(missed), "false": sorted(false)} + + +@dataclass +class Ctx: + spec: TxSpec + state: State + adapters: dict[str, Any] = field(default_factory=dict) + + def adapter(self, name: str) -> Any: + if name not in self.adapters: + self.adapters[name] = adapter_for(self.spec.system(name), self.spec.root) + return self.adapters[name] + + def frames(self, scopes: Sequence[str]) -> dict[str, dict[str, dict[str, str]]]: + out = {} + for scope in sorted(set(scopes)): + name, coll = scope.split(":", 1) + out[scope] = self.adapter(name).frame(None if coll == "*" else coll) + return out + + +def _spec_sha(spec: TxSpec) -> str: + return sha256(spec.model_dump(mode="json")) + + +# -- receipts ------------------------------------------------------------------ + + +def _approval_block(approval: Optional[Mapping[str, Any]], digest: str) -> dict[str, Any]: + block: dict[str, Any] = {"schema": "openadapt.approval-mode-item/v1", "mode": "each_item", "approvals": []} + if approval: + block["approvals"].append( + { + "decision": "approved", + "decided_by": approval.get("decided_by", "human"), + "approver_id": approval.get("approver_id"), + "request_sha256": digest, + } + ) + return block + + +def _write_run( + state: State, + digest: str, + phase: str, + *, + outcome: str, + results: list[dict[str, Any]], + tx: Mapping[str, Any], + approval: Optional[Mapping[str, Any]], + started: float, + sign: bool = True, +) -> Path: + run_id = f"tx-{phase}-{digest[:12]}-{secrets.token_hex(3)}" + run_dir = state.root / "runs" / run_id + run_dir.mkdir(parents=True, mode=0o700) + writes = [r for r in results if r.get("effect_contract_hashes")] + confirmed = sum(1 for r in writes if r.get("effect_verified") is True) + report = { + "schema_version": REPORT_SCHEMA, + "workflow_name": f"tx-{phase}", + "run_id": run_id, + "started_at": iso(started), + "finished_at": iso(now()), + "plan_sha256": digest, + "execution_outcome": outcome, + "success": outcome in ("VERIFIED", "ROLLED_BACK"), + "model_calls": 0, + "results": results, + "approval": _approval_block(approval, digest), + "outcome_envelope": { + "required_contracts": {"effect": len(writes), "authorization": 1 if approval else 0}, + "passed_contracts": {"effect": confirmed, "authorization": 1 if approval else 0}, + }, + "tx": dict(tx), + } + write_private(run_dir / "report.json", report) + os.chmod(run_dir / "report.json", 0o644) + if sign: + try: + from openadapt_flow.offline_seal import seal_home, signer_for + from openadapt_flow.receipt_record import write_receipt_record + + write_receipt_record(run_dir, signer=signer_for(seal_home())) + except Exception as exc: # noqa: BLE001 - the outcome stands without it + write_private(run_dir / "receipt.error.json", {"error": f"{type(exc).__name__}: {exc}"}) + return run_dir + + +def _line( + *, ok: bool, verified: Optional[bool], irreversible: bool, payload: str, code: str +) -> dict[str, Any]: + return { + "ok": ok, + "effect_verified": verified, + "effect_approved_unverified": verified is None, + "actuation": "api", + "risk": "irreversible" if irreversible else "reversible", + "effect_contract_hashes": [payload], + "effect_field_checks": verified is not None, + "postconditions_ok": None, + "tx_code": code, + } + + +# -- plan ---------------------------------------------------------------------- + + +def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: + if not isinstance(w, Mapping): + raise TxRefused("bad_write", f"write {n} is not an object") + extra = set(w) - {"system", "collection", "op", "id", "fields", "label"} + if extra: + raise TxRefused("bad_write", f"write {n} has unknown keys {sorted(extra)}") + system = spec.system(str(w.get("system"))) + op = w.get("op") + if op not in OPS: + raise TxRefused("bad_write", f"write {n}: op must be one of {OPS}") + if isinstance(system, MailSystem) != (op == "send"): + raise TxRefused("bad_write", f"write {n}: {op} doesn't fit a {system.kind} system") + if isinstance(system, RestSystem): + coll = system.collection(w.get("collection")) + if getattr(coll, op) is None: + raise TxRefused("bad_write", f"write {n}: {coll.name} declares no {op}") + if isinstance(system, SqlSystem) and w.get("collection") not in system.tables: + raise TxRefused("bad_write", f"write {n}: table {w.get('collection')!r} is not declared") + if op in ("update", "delete") and w.get("id") in (None, ""): + raise TxRefused("bad_write", f"write {n}: {op} needs id") + if op in ("create", "send") and w.get("id") not in (None, ""): + raise TxRefused("bad_write", f"write {n}: {op} takes no id (the slot is its ordinal)") + if op != "delete" and not isinstance(w.get("fields"), Mapping): + raise TxRefused("bad_write", f"write {n}: {op} needs fields") + return { + "system": system.name, + "collection": w.get("collection") or ("outbox" if op == "send" else None), + "op": op, + "id": None if w.get("id") is None else str(w["id"]), + "fields": dict(w.get("fields") or {}), + "label": str(w.get("label") or "")[:80], + } + + +def _anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], baselines: Sequence[Any]) -> list[dict[str, Any]]: + found: list[dict[str, Any]] = [] + for rule in spec.anomalies: + if rule.max_writes is not None and len(writes) > rule.max_writes: + found.append({"label": rule.label, "write": None, "detail": f"{len(writes)} writes"}) + continue + for n, (w, base) in enumerate(zip(writes, baselines)): + if rule.op is not None and w["op"] != rule.op: + continue + fields = w.get("fields") or {} + if rule.field is not None: + if rule.field not in fields: + continue + value = fields[rule.field] + if rule.above is not None: + try: + if not float(value) > rule.above: + continue + except (TypeError, ValueError): + continue + if rule.clears and not ((base or {}).get(rule.field) not in (None, "") and value in (None, "")): + continue + elif rule.clears: + if not any( + (base or {}).get(k) not in (None, "") and v in (None, "") for k, v in fields.items() + ): + continue + found.append( + {"label": rule.label, "write": n, "detail": rule.field or w["op"], + "value": fields.get(rule.field) if rule.field else None} + ) + return found + + +def _slots(writes: Sequence[Mapping[str, Any]]) -> list[str]: + seen: dict[tuple[str, str, str], int] = {} + out = [] + for w in writes: + if w["op"] in ("update", "delete"): + out.append(f"id:{w['id']}") + continue + k = (w["system"], str(w["collection"]), w["op"]) + seen[k] = seen.get(k, 0) + 1 + out.append(f"{w['op']}#{seen[k]}") + return out + + +def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + """Read the baselines, predict the diff and return the plan (not yet approved).""" + started = now() + if not task or len(task) > 128: + raise TxRefused("bad_task", "the task id must be 1-128 characters") + spec, state = ctx.spec, ctx.state + writes = [_check_write(spec, n, w) for n, w in enumerate(raw)] + if not writes: + raise TxRefused("empty_plan", "a plan needs at least one write") + slots = _slots(writes) + for w, slot in zip(writes, slots): + if w["op"] in ("update", "delete"): + dup = [x for x in writes if x is not w and x["system"] == w["system"] + and x["collection"] == w["collection"] and x["id"] == w["id"]] + if dup: + raise TxRefused("bad_write", "a plan writes each record once") + w["slot"] = slot + w["key"] = state.key_for( + task=task, system=w["system"], collection=str(w["collection"]), op=w["op"], slot=slot + ) + w["payload_sha256"] = sha256({"op": w["op"], "fields": w["fields"], "id": w["id"]}) + w["irreversible"] = _irreversible(spec.system(w["system"]), w) + # The ledger first: a key already used under another payload is a replay. + replays = [] + for n, w in enumerate(writes): + entry = state.entry(w["key"]) + w["ledger"] = "free" + if entry is not None and entry.status not in ("undone", "cancelled"): + w["ledger"] = "replay" if entry.payload == w["payload_sha256"] else "replay_mismatch" + replays.append({"write": n, "status": w["ledger"], "prior_plan": entry.plan[:12]}) + baselines: list[Optional[dict]] = [] + for w in writes: + base = None + if w["op"] in ("update", "delete"): + base = ctx.adapter(w["system"]).read(w["collection"], w["id"]) + if base is None and w["ledger"] == "free": + raise TxRefused("record_missing", f"{w['system']} {w['collection']} {w['id']}") + baselines.append(base) + scopes = [_scope(w, spec.system(w["system"])) for w in writes] + frames = ctx.frames(scopes) + predicted: dict[str, dict[str, Any]] = {s: _empty_prediction() for s in set(scopes)} + dry_run: dict[str, str] = {} + queued = 0 + staged: dict[str, list[int]] = {} + for n, (w, base, scope) in enumerate(zip(writes, baselines, scopes)): + adapter = ctx.adapter(w["system"]) + dry_run[w["system"]] = adapter.dry_run + if w["ledger"] != "free": + continue + if isinstance(adapter, SqlAdapter): + staged.setdefault(w["system"], []).append(n) + elif w["irreversible"]: + queued += 1 + else: + _merge(predicted[scope], adapter.predict(w, base)) + for name, idx in staged.items(): + diff, results = ctx.adapter(name).stage([writes[i] for i in idx], [baselines[i] for i in idx]) + _merge(predicted[f"{name}:*"], _staged_to_prediction(diff)) + summary: dict[str, int] = {} + for w in writes: + verb = {"create": "created", "update": "updated", "delete": "deleted", "send": "queued"}[w["op"]] + if w["irreversible"] and w["op"] == "delete": + verb = "deleted after holdback" + k = f"{w['system']}.{w['collection']} {verb}" + summary[k] = summary.get(k, 0) + 1 + anomalies = _anomalies(spec, writes, baselines) + for r in replays: + if r["status"] == "replay_mismatch": + anomalies.append( + {"label": "replays an applied write with a different payload", "write": r["write"], "detail": "replay_mismatch"} + ) + for scope, pred in predicted.items(): + name = scope.split(":", 1)[0] + if isinstance(spec.system(name), SqlSystem): + declared = set(spec.system(name).tables) # type: ignore[union-attr] + other = {rid.split("/", 1)[0] for rid in pred["changed"]} | set(pred["added"]) | { + rid.split("/", 1)[0] for rid in pred["removed"] + } + if other - declared: + anomalies.append( + {"label": "side effects in undeclared tables", "write": None, "detail": str(len(other - declared))} + ) + core = { + "schema_version": PLAN_SCHEMA, + "task": task, + "spec_sha256": _spec_sha(spec), + "created_at": iso(started), + "nonce": secrets.token_hex(8), + "holdback_s": spec.holdback_s, + "writes": [ + {k: w[k] for k in ("system", "collection", "op", "id", "slot", "key", "payload_sha256", "irreversible", "ledger")} + for w in writes + ], + "baseline_sha256": [None if b is None else sha256(b) for b in baselines], + "frame_sha256": {s: sha256(f) for s, f in frames.items()}, + "predicted": predicted, + "queued": queued, + "dry_run": dry_run, + "summary": summary, + "anomalies": [{k: a[k] for k in ("label", "write")} for a in anomalies], + } + digest = sha256(core) + pdir = state.plan_dir(digest) + write_private(pdir / "plan.json", {**core, "digest": digest}) + write_private( + pdir / "private.json", + {"writes": writes, "baselines": baselines, "frames": frames, "anomalies": anomalies}, + ) + tx = { + "phase": "plan", + "writes": len(writes), + "queued": queued, + "replays": sum(1 for r in replays if r["status"] == "replay"), + "replay_mismatches": sum(1 for r in replays if r["status"] == "replay_mismatch"), + "anomalies": len(anomalies), + "dry_run": sorted(set(dry_run.values())), + } + run = _write_run( + state, digest, "plan", outcome="COMPLETED_UNVERIFIED", results=[], tx=tx, approval=None, started=started + ) + return {**core, "digest": digest, "run_dir": str(run), "anomaly_details": anomalies} + + +def load_plan(state: State, digest: str) -> tuple[dict[str, Any], dict[str, Any]]: + pdir = state.plan_dir(digest) + if not (pdir / "plan.json").exists(): + raise TxRefused("plan_not_found", digest[:12]) + return read_json(pdir / "plan.json"), read_json(pdir / "private.json") + + +def approve_plan(state: State, digest: str, *, approver: str, decided_by: str) -> dict[str, Any]: + load_plan(state, digest) + return state.approve(digest, approver=approver, decided_by=decided_by) + + +# -- apply --------------------------------------------------------------------- + + +def _readback(ctx: Ctx, w: Mapping[str, Any], base: Any, result: Mapping[str, Any]) -> tuple[Optional[bool], Optional[dict]]: + adapter = ctx.adapter(w["system"]) + if isinstance(adapter, MailAdapter): + return None, None + rid = str(result.get("id") or w.get("id")) + got = adapter.read(w["collection"], rid) + if w["op"] == "delete": + return got is None, None + if got is None: + return False, None + want = adapter.expected_after(w, base) or {} + ok = all(same(got.get(k), v) for k, v in want.items()) + return ok, got + + +def apply_plan(ctx: Ctx, digest: str) -> dict[str, Any]: + started = now() + state, spec = ctx.state, ctx.spec + with state.lock(): + plan, priv = load_plan(state, digest) + writes, baselines = priv["writes"], priv["baselines"] + tx: dict[str, Any] = {"phase": "apply", "writes": len(writes)} + + def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: + tx["refused"] = code + run = _write_run( + state, digest, "apply", outcome="HALTED", results=[], tx=tx, + approval=approval or state.approval_record(digest), started=started, + ) + return TxRefused(code, detail, {"run_dir": str(run), "tx": tx}) + + if plan["spec_sha256"] != _spec_sha(spec): + raise refuse("spec_changed", "the tx file changed since the plan") + # Every key before any send: a mismatched replay refuses the whole plan. + for n, w in enumerate(writes): + entry = state.entry(w["key"]) + if entry is not None and entry.status not in ("undone", "cancelled") and entry.payload != w["payload_sha256"]: + tx["blocked_double_effects"] = tx.get("blocked_double_effects", 0) + 1 + if tx.get("blocked_double_effects"): + raise refuse( + "replay_mismatch", + f"{tx['blocked_double_effects']} write(s) reuse a key already applied with a different payload", + ) + # The frame must be what the plan read: anything else is a stale plan. + now_frames = ctx.frames(list(priv["frames"])) + moved = [s for s, f in now_frames.items() if sha256(f) != plan["frame_sha256"].get(s)] + if moved: + raise refuse("plan_stale", f"{len(moved)} scope(s) changed since the plan") + try: + approval = state.consume_approval(digest) + except StateError as exc: + raise refuse(exc.code, exc.detail) from exc + + results: list[dict[str, Any]] = [] + images: dict[str, Any] = {} + sent = 0 + stop: Optional[str] = None + crash_after = int(os.environ.get(CRASH_ENV, "0") or 0) + for w, base in zip(writes, baselines): + key, payload = w["key"], w["payload_sha256"] + entry = state.entry(key) + if stop: + results.append(_line(ok=False, verified=None, irreversible=w["irreversible"], payload=payload, code="not_sent")) + continue + if entry is not None and entry.status not in ("undone", "cancelled"): + if entry.status in ("applied", "held", "released"): + tx["replays"] = tx.get("replays", 0) + 1 + results.append(_line(ok=True, verified=None, irreversible=w["irreversible"], payload=payload, code="replay_not_sent")) + continue + # begun / uncertain / undo_begun: an earlier attempt may have landed. + verified, got = ( + _readback(ctx, w, base, {"id": w["id"]}) if w["op"] == "update" else (None, None) + ) + if verified: + state.record(key, "applied", plan=digest, payload=payload, result={"id": w["id"]}, by="read_back") + images[key] = {"result": {"id": w["id"]}, "after": _norm(spec.system(w["system"]), w, got)} + results.append(_line(ok=True, verified=True, irreversible=False, payload=payload, code="adopted_by_read_back")) + continue + state.record(key, "uncertain", plan=digest, payload=payload, reason="open_attempt") + stop = "open_attempt" + tx["held_uncertain"] = tx.get("held_uncertain", 0) + 1 + results.append(_line(ok=False, verified=None, irreversible=w["irreversible"], payload=payload, code="held_uncertain")) + continue + state.record(key, "begun", plan=digest, payload=payload, op=w["op"], slot=w["slot"]) + if w["irreversible"]: + release_at = now() + float(plan["holdback_s"]) + state.hold(key, {"key": key, "plan": digest, "write": plan["writes"].index( + next(x for x in plan["writes"] if x["key"] == key)), "release_at": release_at}) + state.record(key, "held", plan=digest, payload=payload, release_at=release_at) + tx["held"] = tx.get("held", 0) + 1 + results.append(_line(ok=True, verified=None, irreversible=True, payload=payload, code="held")) + continue + try: + result = ctx.adapter(w["system"]).apply(w, base, key) + except AdapterError as exc: + state.record(key, "uncertain", plan=digest, payload=payload, reason=str(exc)[:120]) + stop = "send_failed" + results.append(_line(ok=False, verified=None, irreversible=False, payload=payload, code="send_failed")) + continue + sent += 1 + if crash_after and sent >= crash_after: + os._exit(70) + state.record(key, "applied", plan=digest, payload=payload, result=result) + verified, got = _readback(ctx, w, base, result) + images[key] = {"result": result, "after": _norm(spec.system(w["system"]), w, got)} + results.append(_line(ok=bool(verified), verified=verified, irreversible=False, payload=payload, + code="confirmed" if verified else "refuted")) + after = ctx.frames(list(priv["frames"])) + missed: list[str] = [] + false: list[str] = [] + for scope in priv["frames"]: + actual = diff_frames(priv["frames"][scope], after[scope]) + got = compare(plan["predicted"][scope], actual) + missed += got["missed"] + false += got["false"] + tx.update( + { + "sent": sent, + "confirmed": sum(1 for r in results if r["tx_code"] == "confirmed"), + "refuted": sum(1 for r in results if r["tx_code"] == "refuted"), + "missed_effects": len(missed), + "false_diffs": len(false), + "stopped": stop, + } + ) + write_private(state.plan_dir(digest) / "applied.json", {"images": images, "frames_after": after}) + ok = not stop and not missed and not tx["refuted"] + outcome = "VERIFIED" if ok and not tx.get("held") else ("COMPLETED_UNVERIFIED" if ok else "RECONCILIATION_REQUIRED") + run = _write_run(state, digest, "apply", outcome=outcome, results=results, tx=tx, approval=approval, started=started) + return {"outcome": outcome, "tx": tx, "run_dir": str(run), "missed": missed, "false": false} + + +# -- undo ---------------------------------------------------------------------- + + +def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: + started = now() + state, spec = ctx.state, ctx.spec + with state.lock(): + plan, priv = load_plan(state, digest) + applied_path = state.plan_dir(digest) / "applied.json" + if not applied_path.exists(): + raise TxRefused("not_applied", digest[:12]) + images = read_json(applied_path)["images"] + writes, baselines = priv["writes"], priv["baselines"] + results: list[dict[str, Any]] = [] + per_write: dict[str, str] = {} + tx: dict[str, Any] = {"phase": "undo", "writes": len(writes)} + for w, base in reversed(list(zip(writes, baselines))): + key = w["key"] + entry = state.entry(key) + system = spec.system(w["system"]) + if entry is None or entry.plan != digest: + per_write[key] = "not_this_plan" + continue + if entry.status == "held": + state.unhold(key) + state.record(key, "cancelled", plan=digest, payload=entry.payload) + per_write[key] = "cancelled" + continue + if entry.status == "released": + per_write[key] = "irreversible_released" + continue + if entry.status == "undone": + per_write[key] = "already_undone" + continue + if entry.status != "applied": + per_write[key] = "unresolved" + continue + result = entry.result or {"id": w.get("id")} + adapter = ctx.adapter(w["system"]) + rid = str(result.get("id") or w.get("id")) + current = adapter.read(w["collection"], rid) + want = (images.get(key) or {}).get("after") + if w["op"] != "delete" and (want is None or _norm(system, w, current) != want): + per_write[key] = "changed_since_apply" + continue + state.record(key, "undo_begun", plan=digest, payload=entry.payload) + try: + adapter.compensate(w, base, result, key) + except AdapterError as exc: + state.record(key, "uncertain", plan=digest, payload=entry.payload, reason=f"undo: {exc}"[:120]) + per_write[key] = "undo_failed" + continue + back = adapter.read(w["collection"], rid if w["op"] != "delete" else str(w["id"])) + if w["op"] == "create": + ok = back is None + else: + ok = back is not None and _norm(system, w, back) == _norm(system, w, base) + state.record(key, "undone", plan=digest, payload=entry.payload, read_back=ok) + per_write[key] = "undone" if ok else "undo_refuted" + # The whole frame back to the baseline: the records and the collateral. + after = ctx.frames(list(priv["frames"])) + leftover: list[str] = [] + for scope in priv["frames"]: + d = diff_frames(priv["frames"][scope], after[scope]) + leftover += d["added"] + d["removed"] + list(d["changed"]) + own = {} + for w in writes: + e = state.entry(w["key"]) + rid = f"{w['collection']}/{(e.result.get('id') if e else None) or w.get('id')}" + own[rid] = w["key"] + collateral = [r for r in leftover if r not in own] + for r in leftover: + if r in own and per_write.get(own[r]) == "undone": + per_write[own[r]] = "frame_differs" + counted = [k for k, v in per_write.items() if v in ("undone", "undo_refuted", "frame_differs", "changed_since_apply", "undo_failed", "unresolved")] + verified = [k for k in counted if per_write[k] == "undone" and not collateral] + for w in writes: + code = per_write.get(w["key"]) + if code in (None, "not_this_plan", "cancelled", "already_undone"): + continue + results.append( + _line( + ok=w["key"] in verified, + verified=(w["key"] in verified) if code != "irreversible_released" else None, + irreversible=w["irreversible"], + payload=w["payload_sha256"], + code=code, + ) + ) + tx.update( + { + "undo_supported": len(counted), + "undo_verified": len(verified), + "cancelled": sum(1 for v in per_write.values() if v == "cancelled"), + "irreversible_released": sum(1 for v in per_write.values() if v == "irreversible_released"), + "collateral_changes": len(collateral), + "codes": {c: sum(1 for v in per_write.values() if v == c) for c in sorted(set(per_write.values()))}, + } + ) + ok = len(verified) == len(counted) and not collateral + outcome = "ROLLED_BACK" if ok else "RECONCILIATION_REQUIRED" + approval = state.approval_record(digest) + run = _write_run(state, digest, "undo", outcome=outcome, results=results, tx=tx, approval=approval, started=started) + return {"outcome": outcome, "tx": tx, "run_dir": str(run), "collateral": collateral} + + +# -- holdback ------------------------------------------------------------------ + + +def cancel(ctx: Ctx, digest: str) -> int: + state = ctx.state + n = 0 + with state.lock(): + for item in state.held(): + if item["plan"] != digest: + continue + entry = state.entry(item["key"]) + state.unhold(item["key"]) + state.record(item["key"], "cancelled", plan=digest, payload=entry.payload if entry else "") + n += 1 + return n + + +def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, Any]: + """Release the plan's held writes whose holdback has passed.""" + started = now() + state, spec = ctx.state, ctx.spec + at = now() if at is None else at + with state.lock(): + plan, priv = load_plan(state, digest) + writes = {w["key"]: (w, b) for w, b in zip(priv["writes"], priv["baselines"])} + results = [] + tx: dict[str, Any] = {"phase": "release", "released": 0, "waiting": 0, "adopted": 0, "double": 0} + for item in state.held(): + if item["plan"] != digest: + continue + if item["release_at"] > at: + tx["waiting"] += 1 + continue + key = item["key"] + w, base = writes[key] + adapter = ctx.adapter(w["system"]) + state.record(key, "release_begun", plan=digest, payload=w["payload_sha256"]) + verified: Optional[bool] + if isinstance(adapter, MailAdapter): + before = adapter.count(key) + if before == 0: + try: + adapter.send(w, key) + except AdapterError: + state.record(key, "uncertain", plan=digest, payload=w["payload_sha256"], reason="smtp") + results.append(_line(ok=False, verified=None, irreversible=True, payload=w["payload_sha256"], code="send_failed")) + continue + else: + tx["adopted"] += 1 + n = adapter.wait_count(key, 1) + tx["double"] += int(n > 1) + verified = n == 1 + else: + adapter.apply(w, base, key) + verified, _ = _readback(ctx, w, base, {"id": w.get("id")}) + state.unhold(key) + state.record(key, "released", plan=digest, payload=w["payload_sha256"], read_back=verified) + tx["released"] += 1 + results.append(_line(ok=bool(verified), verified=verified, irreversible=True, payload=w["payload_sha256"], + code="released" if verified else "release_refuted")) + outcome = "VERIFIED" if results and all(r["effect_verified"] for r in results) else ( + "COMPLETED_UNVERIFIED" if not results else "RECONCILIATION_REQUIRED") + run = _write_run(state, digest, "release", outcome=outcome, results=results, tx=tx, + approval=state.approval_record(digest), started=started) + return {"outcome": outcome, "tx": tx, "run_dir": str(run)} + + +def summary_lines(plan: Mapping[str, Any]) -> list[str]: + """The plan as a person reads it (terminal only: may show values).""" + lines = [f"plan {plan['digest'][:12]} for task {plan['task']}"] + for what, n in sorted(plan["summary"].items()): + lines.append(f" {n} {what}") + if plan.get("queued"): + lines.append(f" irreversible writes wait {plan['holdback_s']:.0f}s in a cancelable holdback queue") + for system, how in sorted(plan["dry_run"].items()): + lines.append(f" {system}: diff from {how.replace('_', ' ')}") + for scope, pred in sorted(plan["predicted"].items()): + added = sum(pred["added"].values()) + lines.append( + f" {scope}: predicted {added} added, {len(pred['changed'])} changed, {len(pred['removed'])} removed" + ) + details = plan.get("anomaly_details") or plan["anomalies"] + lines.append(f" {len(details)} anomal{'y' if len(details) == 1 else 'ies'}") + for a in details: + where = "" if a.get("write") is None else f" (write {a['write']})" + value = "" if a.get("value") is None else f": {a.get('detail')} = {a['value']}" + lines.append(f" ! {a['label']}{value}{where}") + return lines diff --git a/packages/flow/openadapt_flow/txplan/spec.py b/packages/flow/openadapt_flow/txplan/spec.py new file mode 100644 index 0000000000..0b9f38f95c --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/spec.py @@ -0,0 +1,273 @@ +"""``openadapt.tx.yaml``: the external systems a plan may write, and how. + +A plan is a batch of writes to systems outside this computer. Each system +says how OpenAdapt reads a record, lists a collection (the frame), makes each +kind of write, and undoes it:: + + schema_version: openadapt.tx/v1 + holdback_s: 120 # irreversible writes wait this long + anomalies: + - {field: amount, above: 10000, label: large amount} + - {op: delete, label: delete} + - {max_writes: 500, label: large batch} + systems: + - name: tasks + kind: rest + base_url_env: TASKS_URL + auth: {header: Authorization, prefix: "Bearer ", value_env: TASKS_TOKEN} + collections: + - name: task + id_field: id + list: {path: /api/v1/tasks/all, page_param: page, per_page: 50} + read: {path: "/api/v1/tasks/{id}"} + create: {method: PUT, path: "/api/v1/projects/{project_id}/tasks"} + update: {method: POST, path: "/api/v1/tasks/{id}", replace: true} + delete: {method: DELETE, path: "/api/v1/tasks/{id}"} + server_fields: [updated] + derived: {done: [done_at]} + - name: crm + kind: sql + dialect: mysql + driver: pymysql + connect_args: {host: 127.0.0.1, port: 3306, user: crm, database: crm} + password_env: CRM_DB_PASSWORD + tables: {customers: id} + - name: outbox + kind: mail + smtp: {host: 127.0.0.1, port: 1025} + mailbox: {kind: mailpit, base_url: "http://127.0.0.1:8025"} + +Engine code never names an app: everything app-specific is in this file. +""" + +from __future__ import annotations + +import os +import re +from pathlib import Path +from typing import Literal, Optional + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator + +TX_SCHEMA = "openadapt.tx/v1" +_NAME = r"^[a-z][a-z0-9_-]{0,47}$" +_TEMPLATE = re.compile(r"\{([a-z_][a-z0-9_]*)\}") + + +class TxSpecError(ValueError): + """The tx file is missing, unreadable or invalid.""" + + +class _Closed(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class Auth(_Closed): + header: str = "Authorization" + prefix: str = "" + #: The secret comes from this environment variable; never from the file. + value_env: str + + +class Route(_Closed): + method: str = "GET" + path: str + #: update only: the server replaces the whole record, so OpenAdapt sends + #: the baseline merged with the planned fields (and the full baseline on undo). + replace: bool = False + #: list only: pagination. + page_param: Optional[str] = None + per_page_param: Optional[str] = "per_page" + per_page: int = Field(default=50, ge=1, le=1000) + #: create only: the field of the response that holds the new record's id. + id_from: Optional[str] = None + + @model_validator(mode="after") + def _upper(self) -> "Route": + self.method = self.method.upper() + return self + + def placeholders(self) -> list[str]: + return _TEMPLATE.findall(self.path) + + +class Collection(_Closed): + name: str = Field(pattern=_NAME) + id_field: str = "id" + list: Route + read: Route + create: Optional[Route] = None + update: Optional[Route] = None + delete: Optional[Route] = None + #: Fields the server sets on any write (a timestamp, a version). They are + #: left out of every comparison. Declare them before a measured run. + server_fields: list[str] = Field(default_factory=list) + #: Fields the server sets as a consequence of a planned field: changing + #: ``done`` also changes ``done_at``. A plan shows them as expected changes + #: with an unknown value; a change to one without its cause is a miss. + derived: dict[str, list[str]] = Field(default_factory=dict) + #: A delete that the API can't reverse exactly (the record gets a new id + #: when recreated) is irreversible: it waits in the holdback queue. + delete_reversible: bool = False + + +class RestSystem(_Closed): + name: str = Field(pattern=_NAME) + kind: Literal["rest"] + base_url: Optional[str] = None + base_url_env: Optional[str] = None + auth: Optional[Auth] = None + #: Send ``Idempotency-Key`` (or this header) with each write, for servers + #: that honor it. The ledger is the guard either way. + idempotency_header: Optional[str] = None + timeout_s: float = Field(default=20.0, gt=0, le=300) + collections: list[Collection] = Field(min_length=1) + + @model_validator(mode="after") + def _check(self) -> "RestSystem": + if not (self.base_url or self.base_url_env): + raise ValueError(f"system {self.name}: needs base_url or base_url_env") + names = [c.name for c in self.collections] + if len(set(names)) != len(names): + raise ValueError(f"system {self.name}: collection names repeat") + return self + + def url(self) -> str: + if self.base_url: + return self.base_url.rstrip("/") + value = os.environ.get(str(self.base_url_env), "") + if not value: + raise TxSpecError(f"system {self.name}: ${self.base_url_env} is not set") + return value.rstrip("/") + + def collection(self, name: Optional[str]) -> Collection: + for c in self.collections: + if c.name == name: + return c + raise TxSpecError(f"system {self.name}: no collection {name!r}") + + +class SqlSystem(_Closed): + name: str = Field(pattern=_NAME) + kind: Literal["sql"] + dialect: Literal["sqlite", "mysql", "postgresql"] + #: sqlite: the file (relative to the tx file). + path: Optional[str] = None + #: mysql / postgresql: a DB-API module and its connect() arguments. + driver: Optional[str] = None + connect_args: dict[str, object] = Field(default_factory=dict) + password_env: Optional[str] = None + #: The tables a plan may write, each with its key column. + tables: dict[str, str] = Field(min_length=1) + #: Tables whose rows the frame doesn't compare (a session table, a cache). + #: Declare them before a measured run. + frame_ignore_tables: list[str] = Field(default_factory=list) + #: Columns the frame doesn't compare, as ``table.column`` (``*.tms``). + frame_ignore_columns: list[str] = Field(default_factory=list) + max_frame_rows: int = Field(default=200_000, ge=1) + + @model_validator(mode="after") + def _check(self) -> "SqlSystem": + if self.dialect == "sqlite" and not self.path: + raise ValueError(f"system {self.name}: sqlite needs path") + if self.dialect != "sqlite" and not self.driver: + raise ValueError(f"system {self.name}: {self.dialect} needs driver") + ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$") + for table, key in self.tables.items(): + if not (ident.match(table) and ident.match(key)): + raise ValueError(f"system {self.name}: bad table or key {table}.{key}") + return self + + +class Smtp(_Closed): + host: str + port: int = Field(ge=1, le=65535) + + +class Mailbox(_Closed): + #: Where sent mail can be read back: a Mailpit API. + kind: Literal["mailpit"] + base_url: Optional[str] = None + base_url_env: Optional[str] = None + + def url(self) -> str: + if self.base_url: + return self.base_url.rstrip("/") + value = os.environ.get(str(self.base_url_env or ""), "") + if not value: + raise TxSpecError("mailbox: base_url or base_url_env must be set") + return value.rstrip("/") + + +class MailSystem(_Closed): + name: str = Field(pattern=_NAME) + kind: Literal["mail"] + smtp: Smtp + mailbox: Mailbox + sender: str = "openadapt@localhost" + + +class Anomaly(_Closed): + label: str = Field(min_length=1, max_length=60) + field: Optional[str] = None + above: Optional[float] = None + op: Optional[Literal["create", "update", "delete", "send"]] = None + #: A field set from a non-empty value to an empty one. + clears: bool = False + max_writes: Optional[int] = Field(default=None, ge=1) + + @model_validator(mode="after") + def _check(self) -> "Anomaly": + if self.above is not None and self.field is None: + raise ValueError(f"anomaly {self.label}: above needs field") + if not any([self.field, self.op, self.max_writes, self.clears]): + raise ValueError(f"anomaly {self.label}: says nothing to check") + return self + + +System = RestSystem | SqlSystem | MailSystem + + +class TxSpec(_Closed): + schema_version: Literal["openadapt.tx/v1"] + #: Seconds an irreversible write (an email, a delete the API can't undo) + #: waits, cancelable, before it is released. + holdback_s: float = Field(default=120.0, ge=0, le=86_400) + anomalies: list[Anomaly] = Field(default_factory=list) + systems: list[System] = Field(min_length=1) # type: ignore[valid-type] + source: Optional[Path] = Field(default=None, exclude=True) + + @model_validator(mode="after") + def _check(self) -> "TxSpec": + names = [s.name for s in self.systems] + if len(set(names)) != len(names): + raise ValueError("system names repeat") + return self + + @property + def root(self) -> Path: + return self.source.parent if self.source is not None else Path.cwd() + + def system(self, name: str) -> System: # type: ignore[valid-type] + for s in self.systems: + if s.name == name: + return s + raise TxSpecError(f"no system {name!r} in the tx file") + + +def load_spec(path: Path) -> TxSpec: + import yaml + + path = Path(path) + if not path.is_file(): + raise TxSpecError(f"{path} is not a file") + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError) as exc: + raise TxSpecError(f"cannot read {path}: {exc}") from exc + try: + spec = TxSpec.model_validate(data) + except ValidationError as exc: + raise TxSpecError(f"{path} is not a valid {TX_SCHEMA} file: {exc}") from exc + spec.source = path.resolve() + return spec diff --git a/packages/flow/openadapt_flow/txplan/state.py b/packages/flow/openadapt_flow/txplan/state.py new file mode 100644 index 0000000000..34f9579ae6 --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/state.py @@ -0,0 +1,263 @@ +"""Durable state for plans: the idempotency ledger, approvals and the holdback queue. + +Everything here lives in a state folder outside the agent's workspace +(``~/.openadapt/tx`` by default, ``OPENADAPT_TX_STATE`` to move it). A +checkpoint restore of the workspace, a ``git reset`` or a rewound agent +therefore can't roll the ledger back: that is what makes a replay visible. + +**Idempotency key.** Each write's key is an HMAC, under a secret kept in the +state folder, of the task, the system, the collection, the operation and the +record *slot*: the record's id for an update or delete, and the ordinal of the +create (or send) within the task for a new record. None of those come from the +payload, so a model that regenerates the payload after a crash or a rewind +gets the same key. The ledger stores the payload digest and the plan digest +under the key, and a second write under the key with a different payload is +refused (``replay_mismatch``). The same payload is a replay: the stored result +is returned and nothing is sent. The plan digest is bound, not keyed: keying on +it would let a re-plan mint a fresh key. + +**Approvals** bind to one plan digest and are single-use: apply consumes one +before its first send, so a consumed approval can't authorize a second apply. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import hmac +import json +import os +import secrets +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterator, Mapping, Optional + +STATE_ENV = "OPENADAPT_TX_STATE" + + +def canonical(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str).encode( + "utf-8" + ) + + +def sha256(value: Any) -> str: + return hashlib.sha256(canonical(value)).hexdigest() + + +def now() -> float: + return time.time() + + +def iso(at: float) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)) + + +def _private_dir(path: Path) -> Path: + path.mkdir(parents=True, exist_ok=True, mode=0o700) + with contextlib.suppress(OSError): + os.chmod(path, 0o700) + return path + + +def write_private(path: Path, payload: Any) -> None: + """Write JSON owner-only, atomically.""" + _private_dir(path.parent) + tmp = path.with_name(path.name + f".{os.getpid()}.tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + os.write(fd, (json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n").encode()) + os.fsync(fd) + finally: + os.close(fd) + os.replace(tmp, path) + + +def read_json(path: Path) -> Any: + return json.loads(path.read_text(encoding="utf-8")) + + +class StateError(RuntimeError): + def __init__(self, code: str, detail: str = "") -> None: + super().__init__(f"{code}: {detail}" if detail else code) + self.code = code + self.detail = detail + + +@dataclass +class Entry: + """What the ledger knows about one key.""" + + key: str + status: str # begun | applied | uncertain | held | released | cancelled | undo_begun | undone + plan: str + payload: str + events: list[dict[str, Any]] + + @property + def result(self) -> dict[str, Any]: + for event in reversed(self.events): + if event.get("result"): + return dict(event["result"]) + return {} + + +class State: + """One state folder.""" + + def __init__(self, root: Optional[Path] = None) -> None: + if root is None: + env = os.environ.get(STATE_ENV) + root = Path(env) if env else Path.home() / ".openadapt" / "tx" + self.root = _private_dir(Path(root).expanduser()) + for sub in ("ledger", "plans", "approvals", "runs", "holdback"): + _private_dir(self.root / sub) + + # -- secret and keys ----------------------------------------------------- + + def secret(self) -> bytes: + path = self.root / "secret" + if not path.exists(): + fd = None + with contextlib.suppress(FileExistsError): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + os.write(fd, secrets.token_hex(32).encode()) + os.fsync(fd) + if fd is not None: + os.close(fd) + return bytes.fromhex(path.read_text().strip()) + + def key_for( + self, *, task: str, system: str, collection: str, op: str, slot: str + ) -> str: + body = canonical( + {"task": task, "system": system, "collection": collection, "op": op, "slot": slot} + ) + return "ik-" + hmac.new(self.secret(), body, hashlib.sha256).hexdigest()[:40] + + # -- the lock ------------------------------------------------------------ + + @contextlib.contextmanager + def lock(self) -> Iterator[None]: + """One applier per state folder at a time (an OS lock the kernel drops + when the process dies).""" + fd = os.open(self.root / "lock", os.O_RDWR | os.O_CREAT, 0o600) + try: + if os.name == "nt": # pragma: no cover - Windows + import msvcrt + + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) # closing drops the lock + + # -- the ledger ---------------------------------------------------------- + + def _ledger_path(self, key: str) -> Path: + if not key.startswith("ik-") or not key[3:].isalnum(): + raise StateError("bad_key", key) + return self.root / "ledger" / f"{key}.jsonl" + + def record(self, key: str, event: str, **fields: Any) -> None: + """Append one event, durably, before the caller acts on it.""" + line = json.dumps({"event": event, "at": now(), **fields}, sort_keys=True, default=str) + fd = os.open(self._ledger_path(key), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + try: + os.write(fd, (line + "\n").encode()) + os.fsync(fd) + finally: + os.close(fd) + + def entry(self, key: str) -> Optional[Entry]: + path = self._ledger_path(key) + if not path.exists(): + return None + events = [json.loads(x) for x in path.read_text().splitlines() if x.strip()] + if not events: + return None + begun = next((e for e in reversed(events) if e["event"] == "begun"), events[0]) + return Entry( + key=key, + status=events[-1]["event"], + plan=str(begun.get("plan", "")), + payload=str(begun.get("payload", "")), + events=events, + ) + + def entries(self) -> list[Entry]: + out = [] + for path in sorted((self.root / "ledger").glob("ik-*.jsonl")): + found = self.entry(path.stem) + if found is not None: + out.append(found) + return out + + # -- plans --------------------------------------------------------------- + + def plan_dir(self, digest: str) -> Path: + if len(digest) != 64 or not all(c in "0123456789abcdef" for c in digest): + raise StateError("bad_digest", digest) + return self.root / "plans" / digest + + def find_plan(self, prefix: str) -> str: + prefix = prefix.removeprefix("pl-") + hits = [p.name for p in (self.root / "plans").iterdir() if p.name.startswith(prefix)] + if len(hits) != 1: + raise StateError("plan_not_found" if not hits else "plan_ambiguous", prefix) + return hits[0] + + # -- approvals ----------------------------------------------------------- + + def approve(self, digest: str, *, approver: str, decided_by: str) -> dict[str, Any]: + path = self.root / "approvals" / f"{digest}.json" + if path.exists() or (self.root / "approvals" / f"{digest}.consumed.json").exists(): + raise StateError("already_approved", digest[:12]) + record = { + "plan": digest, + "approver_id": approver, + "decided_by": decided_by, + "approved_at": iso(now()), + "nonce": secrets.token_hex(8), + } + write_private(path, record) + return record + + def consume_approval(self, digest: str) -> dict[str, Any]: + """Take the plan's approval, once. A second apply finds none.""" + path = self.root / "approvals" / f"{digest}.json" + used = self.root / "approvals" / f"{digest}.consumed.json" + if used.exists(): + raise StateError("approval_consumed", digest[:12]) + if not path.exists(): + raise StateError("not_approved", digest[:12]) + try: + os.link(path, used) # atomic: only one caller wins + except FileExistsError as exc: + raise StateError("approval_consumed", digest[:12]) from exc + record = read_json(path) + path.unlink() + return dict(record) + + def approval_record(self, digest: str) -> Optional[dict[str, Any]]: + for name in (f"{digest}.json", f"{digest}.consumed.json"): + path = self.root / "approvals" / name + if path.exists(): + return dict(read_json(path)) + return None + + # -- holdback ------------------------------------------------------------ + + def hold(self, key: str, item: Mapping[str, Any]) -> None: + write_private(self.root / "holdback" / f"{key}.json", dict(item)) + + def held(self) -> list[dict[str, Any]]: + return [read_json(p) for p in sorted((self.root / "holdback").glob("ik-*.json"))] + + def unhold(self, key: str) -> None: + with contextlib.suppress(FileNotFoundError): + (self.root / "holdback" / f"{key}.json").unlink() diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py new file mode 100644 index 0000000000..507794263e --- /dev/null +++ b/packages/flow/tests/test_txplan.py @@ -0,0 +1,464 @@ +"""``openadapt plan``: dry-run diff, idempotent retry, verified undo, receipts. + +Real SQLite files, and real HTTP and SMTP servers on loopback +(``txplan_servers``). The ACRFence tests reproduce the semantic-rollback +action-replay attack (arXiv:2603.20625): after a restore, the agent +regenerates the same write with a different payload. The control arm shows +the duplicate lands without the guard; the guarded arm shows it is refused. +""" + +from __future__ import annotations + +import json +import os +import shutil +import sqlite3 +import subprocess +import sys +from pathlib import Path +from typing import Any, Iterator + +import pytest +import yaml + +pytest.importorskip("cryptography") + +from openadapt_flow.txplan import engine # noqa: E402 +from openadapt_flow.txplan.adapters import RestAdapter # noqa: E402 +from openadapt_flow.txplan.engine import Ctx, TxRefused # noqa: E402 +from openadapt_flow.txplan.spec import load_spec # noqa: E402 +from openadapt_flow.txplan.state import State # noqa: E402 + +sys.path.insert(0, str(Path(__file__).parent)) +from txplan_servers import MailSink, RestStore # noqa: E402 + +SECRET_NOTE = "synthetic-note-7c1f" + + +@pytest.fixture(autouse=True) +def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + monkeypatch.setenv("OPENADAPT_TX_STATE", str(tmp_path / "state")) + monkeypatch.delenv(engine.CRASH_ENV, raising=False) + + +def _db(path: Path, *, trigger: bool = False) -> Path: + con = sqlite3.connect(path) + con.executescript( + """ + CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, balance REAL, note TEXT); + CREATE TABLE orders (id INTEGER PRIMARY KEY, customer INTEGER, total REAL); + CREATE TABLE audit (id INTEGER PRIMARY KEY AUTOINCREMENT, customer INTEGER); + """ + ) + for i in range(1, 21): + con.execute("INSERT INTO customers VALUES (?, ?, ?, ?)", (i, f"cust {i}", 10.0 * i, "")) + con.execute("INSERT INTO orders VALUES (?, ?, ?)", (i, i, 5.0 * i)) + if trigger: + con.execute( + "CREATE TRIGGER t AFTER UPDATE ON customers BEGIN " + "INSERT INTO audit (customer) VALUES (NEW.id); END" + ) + con.commit() + con.close() + return path + + +def _rows(path: Path) -> dict[str, list[tuple]]: + con = sqlite3.connect(path) + try: + return { + t: sorted(con.execute(f"SELECT * FROM {t}").fetchall()) + for t in ("customers", "orders", "audit") + } + finally: + con.close() + + +@pytest.fixture +def rest() -> Iterator[tuple[RestStore, str]]: + store = RestStore(replace=True) + for i in range(1, 11): + store.add(title=f"item {i}", amount=i * 10) + srv, url = store.server() + try: + yield store, url + finally: + srv.shutdown() + + +@pytest.fixture +def mail() -> Iterator[MailSink]: + sink = MailSink() + try: + yield sink + finally: + sink.close() + + +def _spec(tmp_path: Path, *, db: Path | None = None, rest_url: str | None = None, + mail: MailSink | None = None, holdback: float = 60) -> Path: + systems: list[dict[str, Any]] = [] + if db is not None: + systems.append({"name": "crm", "kind": "sql", "dialect": "sqlite", "path": str(db), + "tables": {"customers": "id", "orders": "id"}}) + if rest_url is not None: + systems.append({ + "name": "tasks", "kind": "rest", "base_url": rest_url, + "collections": [{ + "name": "item", "id_field": "id", + "list": {"path": "/api/items", "page_param": "page", "per_page": 4}, + "read": {"path": "/api/items/{id}"}, + "create": {"method": "POST", "path": "/api/items"}, + "update": {"method": "PATCH", "path": "/api/items/{id}", "replace": True}, + "delete": {"method": "DELETE", "path": "/api/items/{id}"}, + "server_fields": ["updated"], + "derived": {"done": ["done_at"]}, + }], + }) + if mail is not None: + systems.append({"name": "outbox", "kind": "mail", + "smtp": {"host": "127.0.0.1", "port": mail.smtp_port}, + "mailbox": {"kind": "mailpit", "base_url": mail.api_url}}) + path = tmp_path / "openadapt.tx.yaml" + path.write_text(yaml.safe_dump({ + "schema_version": "openadapt.tx/v1", + "holdback_s": holdback, + "anomalies": [{"field": "amount", "above": 10000, "label": "large refund"}, + {"op": "delete", "label": "delete"}], + "systems": systems, + })) + return path + + +def _ctx(spec: Path) -> Ctx: + return Ctx(spec=load_spec(spec), state=State()) + + +def _go(ctx: Ctx, task: str, writes: list[dict[str, Any]]) -> dict[str, Any]: + plan = engine.make_plan(ctx, task, writes) + engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + return plan + + +# -- dry run, apply, undo: SQL (staged transaction) ---------------------------- + + +def test_sql_plan_apply_undo_round_trip(tmp_path: Path) -> None: + db = _db(tmp_path / "crm.sqlite") + before = _rows(db) + ctx = _ctx(_spec(tmp_path, db=db)) + writes = [ + {"system": "crm", "collection": "customers", "op": "update", "id": 3, + "fields": {"balance": 99.5, "note": SECRET_NOTE}}, + {"system": "crm", "collection": "customers", "op": "create", + "fields": {"name": "new cust", "balance": 1.0, "note": ""}}, + {"system": "crm", "collection": "orders", "op": "delete", "id": 7}, + ] + plan = _go(ctx, "T-sql", writes) + pred = plan["predicted"]["crm:*"] + assert plan["dry_run"] == {"crm": "staged_transaction"} + assert pred["changed"] == {"customers/3": ["balance", "note"]} + assert pred["added"] == {"customers": 1} and pred["removed"] == ["orders/7"] + assert _rows(db) == before # the staged transaction rolled back + lines = engine.summary_lines(plan) + assert any("1 anomaly" in x for x in lines) and any("delete" in x for x in lines) + + applied = engine.apply_plan(ctx, plan["digest"]) + assert applied["outcome"] == "VERIFIED", applied + assert applied["tx"]["missed_effects"] == 0 and applied["tx"]["false_diffs"] == 0 + assert _rows(db) != before + + undone = engine.undo_plan(ctx, plan["digest"]) + assert undone["outcome"] == "ROLLED_BACK", undone + assert undone["tx"]["undo_verified"] == 3 and undone["tx"]["collateral_changes"] == 0 + assert _rows(db) == before + + +def test_staged_dry_run_sees_a_trigger_and_undo_reports_its_collateral(tmp_path: Path) -> None: + db = _db(tmp_path / "crm.sqlite", trigger=True) + ctx = _ctx(_spec(tmp_path, db=db)) + plan = _go(ctx, "T-trig", [{"system": "crm", "collection": "customers", "op": "update", + "id": 2, "fields": {"balance": 1.0}}]) + assert plan["predicted"]["crm:*"]["added"] == {"audit": 1} + assert any(a["label"] == "side effects in undeclared tables" for a in plan["anomalies"]) + applied = engine.apply_plan(ctx, plan["digest"]) + assert applied["tx"]["missed_effects"] == 0, applied + undone = engine.undo_plan(ctx, plan["digest"]) + # The undo's own UPDATE fires the trigger again: not back to the baseline. + assert undone["outcome"] == "RECONCILIATION_REQUIRED" + assert undone["tx"]["undo_verified"] == 0 and undone["tx"]["collateral_changes"] >= 1 + + +def test_missed_effect_is_counted_when_something_else_moves(tmp_path: Path, rest) -> None: + store, url = rest + ctx = _ctx(_spec(tmp_path, rest_url=url)) + plan = _go(ctx, "T-miss", [{"system": "tasks", "collection": "item", "op": "update", + "id": 1, "fields": {"title": "renamed"}}]) + real = RestAdapter.apply + + def apply_and_touch(self, w, base, key): # a server-side cascade the plan didn't see + out = real(self, w, base, key) + store.records[5]["title"] = "cascaded" + return out + + RestAdapter.apply = apply_and_touch # type: ignore[method-assign] + try: + applied = engine.apply_plan(ctx, plan["digest"]) + finally: + RestAdapter.apply = real # type: ignore[method-assign] + assert applied["tx"]["missed_effects"] == 1 and applied["outcome"] == "RECONCILIATION_REQUIRED" + + +# -- approval binding ---------------------------------------------------------- + + +def test_approval_binds_to_one_digest_and_is_single_use(tmp_path: Path) -> None: + db = _db(tmp_path / "crm.sqlite") + ctx = _ctx(_spec(tmp_path, db=db)) + w = [{"system": "crm", "collection": "customers", "op": "update", "id": 1, "fields": {"balance": 7}}] + a = engine.make_plan(ctx, "T-a", w) + b = engine.make_plan(ctx, "T-b", w) + engine.approve_plan(ctx.state, a["digest"], approver="lab", decided_by="automation") + with pytest.raises(TxRefused) as exc: + engine.apply_plan(ctx, b["digest"]) + assert exc.value.code == "not_approved" + assert engine.apply_plan(ctx, a["digest"])["outcome"] == "VERIFIED" + with pytest.raises(TxRefused): # authority resurrection: no second apply + engine.apply_plan(ctx, a["digest"]) + + +def test_stale_plan_is_refused_before_any_send(tmp_path: Path) -> None: + db = _db(tmp_path / "crm.sqlite") + ctx = _ctx(_spec(tmp_path, db=db)) + plan = _go(ctx, "T-stale", [{"system": "crm", "collection": "customers", "op": "update", + "id": 4, "fields": {"balance": 0}}]) + con = sqlite3.connect(db) + con.execute("UPDATE orders SET total = 1 WHERE id = 9") + con.commit() + con.close() + snapshot = _rows(db) + with pytest.raises(TxRefused) as exc: + engine.apply_plan(ctx, plan["digest"]) + assert exc.value.code == "plan_stale" + assert _rows(db) == snapshot + assert ctx.state.approval_record(plan["digest"])["plan"] == plan["digest"] # not consumed + + +# -- ACRFence: semantic rollback, action replay ------------------------------- + + +def _payment(ref: str, amount: int = 100) -> dict[str, Any]: + return {"system": "tasks", "collection": "item", "op": "create", + "fields": {"title": f"refund {ref}", "amount": amount, "reference": ref}} + + +def test_acrfence_control_arm_without_the_guard_double_charges(tmp_path: Path, rest) -> None: + store, url = rest + spec = load_spec(_spec(tmp_path, rest_url=url)) + raw = RestAdapter(spec.system("tasks")) # type: ignore[arg-type] + n0 = len(store.records) + # A request-id idempotency check (the paper's UUID testbed) sees two requests. + raw.apply(_payment("uuid-a"), None, "req-uuid-a") + raw.apply(_payment("uuid-b"), None, "req-uuid-b") # regenerated after a restore + assert len(store.records) == n0 + 2 + + +def test_acrfence_regenerated_payload_after_restore_is_blocked(tmp_path: Path, rest) -> None: + store, url = rest + workspace = tmp_path / "workspace" + workspace.mkdir() + ctx = _ctx(_spec(tmp_path, rest_url=url)) + first = _go(ctx, "T-refund", [_payment("uuid-a")]) + assert engine.apply_plan(ctx, first["digest"])["outcome"] == "VERIFIED" + n1 = len(store.records) + writes_before = store.writes + + # Checkpoint restore: the agent's workspace goes back to before the apply. + shutil.rmtree(workspace) + workspace.mkdir() + # The agent regenerates the batch: same task, same intent, new reference. + ctx = _ctx(_spec(tmp_path, rest_url=url)) + again = engine.make_plan(ctx, "T-refund", [_payment("uuid-b")]) + assert again["writes"][0]["ledger"] == "replay_mismatch" + assert any("different payload" in a["label"] for a in again["anomalies"]) + engine.approve_plan(ctx.state, again["digest"], approver="lab", decided_by="automation") + with pytest.raises(TxRefused) as exc: + engine.apply_plan(ctx, again["digest"]) + assert exc.value.code == "replay_mismatch" + assert exc.value.report["tx"]["blocked_double_effects"] == 1 + assert len(store.records) == n1 and store.writes == writes_before + + # The identical payload is a replay: the stored result, nothing sent. + same = _go(ctx, "T-refund", [_payment("uuid-a")]) + out = engine.apply_plan(ctx, same["digest"]) + assert out["tx"]["replays"] == 1 and out["tx"]["sent"] == 0 + assert len(store.records) == n1 + + +def test_acrfence_mutated_update_replay_is_blocked(tmp_path: Path, rest) -> None: + store, url = rest + ctx = _ctx(_spec(tmp_path, rest_url=url)) + p = _go(ctx, "T-upd", [{"system": "tasks", "collection": "item", "op": "update", "id": 2, + "fields": {"amount": 500}}]) + engine.apply_plan(ctx, p["digest"]) + q = _go(ctx, "T-upd", [{"system": "tasks", "collection": "item", "op": "update", "id": 2, + "fields": {"amount": 5000}}]) + with pytest.raises(TxRefused) as exc: + engine.apply_plan(ctx, q["digest"]) + assert exc.value.code == "replay_mismatch" + assert store.records[2]["amount"] == 500 + + +def test_crash_after_send_then_regenerated_retry_makes_no_second_effect(tmp_path: Path, rest) -> None: + store, url = rest + spec_path = _spec(tmp_path, rest_url=url) + ctx = _ctx(spec_path) + plan = _go(ctx, "T-crash", [_payment("uuid-c")]) + n0 = len(store.records) + code = ( + "import sys; from pathlib import Path; from openadapt_flow.txplan import engine;" + "from openadapt_flow.txplan.spec import load_spec; from openadapt_flow.txplan.state import State;" + f"engine.apply_plan(engine.Ctx(load_spec(Path({str(spec_path)!r})), State()), {plan['digest']!r})" + ) + env = {**os.environ, engine.CRASH_ENV: "1"} + proc = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, timeout=120) + assert proc.returncode == 70, proc.stderr.decode()[-2000:] + assert len(store.records) == n0 + 1 # the send landed; its outcome was never recorded + key = plan["writes"][0]["key"] + assert ctx.state.entry(key).status == "begun" + + mutated = _go(ctx, "T-crash", [_payment("uuid-d")]) + with pytest.raises(TxRefused): + engine.apply_plan(ctx, mutated["digest"]) + same = _go(ctx, "T-crash", [_payment("uuid-c")]) + out = engine.apply_plan(ctx, same["digest"]) + assert out["tx"]["held_uncertain"] == 1 and out["tx"]["sent"] == 0 # read back, never resent + assert len(store.records) == n0 + 1 + + +# -- REST: computed dry run, replace-style update, derived fields -------------- + + +def test_rest_replace_update_with_derived_field_round_trip(tmp_path: Path, rest) -> None: + store, url = rest + snapshot = {k: {f: v for f, v in r.items() if f != "updated"} for k, r in store.records.items()} + ctx = _ctx(_spec(tmp_path, rest_url=url)) + plan = _go(ctx, "T-rest", [ + {"system": "tasks", "collection": "item", "op": "update", "id": 3, "fields": {"done": True}}, + {"system": "tasks", "collection": "item", "op": "create", "fields": {"title": "x", "amount": 1}}, + ]) + pred = plan["predicted"]["tasks:item"] + assert pred["changed"] == {"item/3": ["done"]} and pred["derived"] == {"item/3": ["done_at"]} + applied = engine.apply_plan(ctx, plan["digest"]) + assert applied["outcome"] == "VERIFIED", applied + assert store.records[3]["title"] == "item 3" # replace-style: the baseline was merged + undone = engine.undo_plan(ctx, plan["digest"]) + assert undone["outcome"] == "ROLLED_BACK", undone + now = {k: {f: v for f, v in r.items() if f != "updated"} for k, r in store.records.items()} + assert now == snapshot + + +def test_undo_refuses_a_record_changed_since_apply(tmp_path: Path, rest) -> None: + store, url = rest + ctx = _ctx(_spec(tmp_path, rest_url=url)) + plan = _go(ctx, "T-chg", [{"system": "tasks", "collection": "item", "op": "update", "id": 4, + "fields": {"amount": 1}}]) + engine.apply_plan(ctx, plan["digest"]) + store.records[4]["amount"] = 2 # a person edited it after the apply + undone = engine.undo_plan(ctx, plan["digest"]) + assert undone["tx"]["codes"] == {"changed_since_apply": 1} + assert store.records[4]["amount"] == 2 + + +def test_large_amount_anomaly_is_shown_in_the_terminal_only(tmp_path: Path, rest) -> None: + _, url = rest + ctx = _ctx(_spec(tmp_path, rest_url=url)) + plan = engine.make_plan(ctx, "T-big", [_payment("r", amount=42_000)]) + text = "\n".join(engine.summary_lines(plan)) + assert "large refund: amount = 42000" in text + report = (Path(plan["run_dir"]) / "report.json").read_text() + assert "42000" not in report and "refund r" not in report + + +# -- email: holdback queue ----------------------------------------------------- + + +def _mail(to: str = "a@example.test") -> dict[str, Any]: + return {"system": "outbox", "op": "send", "fields": {"to": to, "subject": "Invoice", "body": SECRET_NOTE}} + + +def test_email_waits_in_holdback_and_cancel_sends_nothing(tmp_path: Path, mail: MailSink) -> None: + ctx = _ctx(_spec(tmp_path, mail=mail, holdback=3600)) + plan = _go(ctx, "T-mail", [_mail(), _mail("b@example.test")]) + applied = engine.apply_plan(ctx, plan["digest"]) + assert applied["tx"]["held"] == 2 and applied["outcome"] == "COMPLETED_UNVERIFIED" + assert engine.release(ctx, plan["digest"])["tx"]["waiting"] == 2 + undone = engine.undo_plan(ctx, plan["digest"]) + assert undone["tx"]["cancelled"] == 2 and mail.messages == [] + + +def test_email_release_sends_once_even_after_a_crash(tmp_path: Path, mail: MailSink) -> None: + ctx = _ctx(_spec(tmp_path, mail=mail, holdback=0)) + plan = _go(ctx, "T-rel", [_mail()]) + engine.apply_plan(ctx, plan["digest"]) + key = plan["writes"][0]["key"] + # A release that sent and crashed before recording it: the message is there. + from openadapt_flow.txplan.adapters import MailAdapter + + adapter = ctx.adapter("outbox") + assert isinstance(adapter, MailAdapter) + w = json.loads((ctx.state.plan_dir(plan["digest"]) / "private.json").read_text())["writes"][0] + adapter.send(w, key) + out = engine.release(ctx, plan["digest"]) + assert out["tx"] == {"phase": "release", "released": 1, "waiting": 0, "adopted": 1, "double": 0} + assert len(mail.messages) == 1 and out["outcome"] == "VERIFIED" + undone = engine.undo_plan(ctx, plan["digest"]) + assert undone["tx"]["irreversible_released"] == 1 + + +# -- receipts ------------------------------------------------------------------ + + +def test_each_phase_gets_a_signed_receipt_with_the_approval_bound(tmp_path: Path) -> None: + from openadapt_flow.receipt_record import local_registry, verify_run_receipt + + db = _db(tmp_path / "crm.sqlite") + ctx = _ctx(_spec(tmp_path, db=db)) + plan = _go(ctx, "T-rcpt", [{"system": "crm", "collection": "customers", "op": "update", "id": 5, + "fields": {"note": SECRET_NOTE}}]) + applied = engine.apply_plan(ctx, plan["digest"]) + undone = engine.undo_plan(ctx, plan["digest"]) + registry = local_registry(Path(os.environ["OPENADAPT_SEAL_HOME"])) + for run_dir, outcome in ((plan["run_dir"], "UNKNOWN"), (applied["run_dir"], "VERIFIED"), + (undone["run_dir"], "STOPPED")): + run = Path(run_dir) + got = verify_run_receipt(run, registry) + assert got.ok, (run, got) + assert got.statement["predicate"]["outcome"] == outcome + for name in ("report.json", "receipt.json"): + assert SECRET_NOTE not in (run / name).read_text() + report = json.loads((run / "report.json").read_text()) + assert report["plan_sha256"] == plan["digest"] + stmt = verify_run_receipt(Path(applied["run_dir"]), registry).statement + assert stmt["predicate"]["approval"]["mode"] == "each_item" + assert stmt["predicate"]["approval"]["approver_kind"] == "agent" + + +def test_cli_create_show_approve_apply(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + from openadapt_flow.txplan.cli import main + + db = _db(tmp_path / "crm.sqlite") + spec = _spec(tmp_path, db=db) + writes = tmp_path / "w.json" + writes.write_text(json.dumps({"writes": [{"system": "crm", "collection": "customers", "op": "update", + "id": 6, "fields": {"balance": 3}}]})) + assert main(["create", "--tx", str(spec), "--task", "T-cli", str(writes)]) == 0 + out = capsys.readouterr().out + assert "1 crm.customers updated" in out + digest = out.split("openadapt plan approve ")[1].split()[0] + assert main(["approve", digest]) == 2 # not a terminal: a person must approve + assert main(["approve", digest, "--automation"]) == 0 + assert main(["apply", "--tx", str(spec), digest]) == 0 + assert main(["apply", "--tx", str(spec), digest]) == 3 diff --git a/packages/flow/tests/txplan_servers.py b/packages/flow/tests/txplan_servers.py new file mode 100644 index 0000000000..0ffae1e73d --- /dev/null +++ b/packages/flow/tests/txplan_servers.py @@ -0,0 +1,183 @@ +"""Small real servers for the txplan tests: a JSON REST API and a mail sink. + +They speak real HTTP and SMTP over loopback sockets. The lab harness +(``benchmark/ext_tx``) runs the same flows against Vikunja, Mailpit and a +MariaDB-backed app. +""" + +from __future__ import annotations + +import json +import socketserver +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, Optional + + +class RestStore: + """Records with an id, a server-set ``updated`` and ``done`` -> ``done_at``.""" + + def __init__(self, *, replace: bool = False) -> None: + self.records: dict[int, dict[str, Any]] = {} + self.next_id = 1 + self.replace = replace + self.lock = threading.Lock() + self.writes = 0 + + def add(self, **fields: Any) -> dict[str, Any]: + with self.lock: + rid = self.next_id + self.next_id += 1 + rec = {"id": rid, "done": False, "done_at": None, **fields, "updated": time.time()} + self.records[rid] = rec + return dict(rec) + + def server(self) -> tuple[ThreadingHTTPServer, str]: + store = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *a: Any) -> None: + pass + + def _send(self, code: int, body: Any = None) -> None: + data = b"" if body is None else json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _body(self) -> dict[str, Any]: + n = int(self.headers.get("Content-Length") or 0) + return json.loads(self.rfile.read(n)) if n else {} + + def _id(self) -> Optional[int]: + parts = self.path.split("?")[0].strip("/").split("/") + if len(parts) == 3 and parts[:2] == ["api", "items"]: + return int(parts[2]) + return None + + def do_GET(self) -> None: # noqa: N802 + path, _, query = self.path.partition("?") + if path == "/api/items": + q = dict(p.split("=") for p in query.split("&") if "=" in p) + page, per = int(q.get("page", 1)), int(q.get("per_page", 50)) + items = [store.records[k] for k in sorted(store.records)] + return self._send(200, items[(page - 1) * per : page * per]) + rid = self._id() + if rid is None or rid not in store.records: + return self._send(404, {}) + self._send(200, store.records[rid]) + + def do_POST(self) -> None: # noqa: N802 + if self.path != "/api/items": + return self._send(404, {}) + store.writes += 1 + self._send(201, store.add(**self._body())) + + def do_PATCH(self) -> None: # noqa: N802 + rid = self._id() + if rid is None or rid not in store.records: + return self._send(404, {}) + body = self._body() + store.writes += 1 + with store.lock: + old = store.records[rid] + if store.replace: + new = {"id": rid, "done": False, "done_at": None, **body} + else: + new = {**old, **body} + new["id"] = rid + if new.get("done") != old.get("done"): + new["done_at"] = time.time() if new.get("done") else None + new["updated"] = time.time() + store.records[rid] = new + self._send(200, new) + + def do_DELETE(self) -> None: # noqa: N802 + rid = self._id() + if rid is None or rid not in store.records: + return self._send(404, {}) + store.writes += 1 + with store.lock: + del store.records[rid] + self._send(204) + + srv = ThreadingHTTPServer(("127.0.0.1", 0), H) + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv, f"http://127.0.0.1:{srv.server_address[1]}" + + +class MailSink: + """An SMTP server that keeps messages, and a Mailpit-shaped list API.""" + + def __init__(self) -> None: + self.messages: list[dict[str, Any]] = [] + sink = self + + class Smtp(socketserver.StreamRequestHandler): + def handle(self) -> None: + self.wfile.write(b"220 sink\r\n") + data: Optional[list[bytes]] = None + while True: + line = self.rfile.readline() + if not line: + return + if data is not None: + if line in (b".\r\n", b".\n"): + sink._store(b"".join(data)) + data = None + self.wfile.write(b"250 ok\r\n") + else: + data.append(line[1:] if line.startswith(b"..") else line) + continue + cmd = line[:4].upper() + if cmd == b"EHLO": + self.wfile.write(b"250 sink\r\n") + elif cmd == b"DATA": + data = [] + self.wfile.write(b"354 go\r\n") + elif cmd == b"QUIT": + self.wfile.write(b"221 bye\r\n") + return + else: + self.wfile.write(b"250 ok\r\n") + + class Api(BaseHTTPRequestHandler): + def log_message(self, *a: Any) -> None: + pass + + def do_GET(self) -> None: # noqa: N802 + body = json.dumps({"messages": list(sink.messages)}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + socketserver.ThreadingTCPServer.allow_reuse_address = True + self.smtp = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Smtp) + self.api = ThreadingHTTPServer(("127.0.0.1", 0), Api) + for s in (self.smtp, self.api): + threading.Thread(target=s.serve_forever, daemon=True).start() + self.smtp_port = self.smtp.server_address[1] + self.api_url = f"http://127.0.0.1:{self.api.server_address[1]}" + + def _store(self, raw: bytes) -> None: + from email import message_from_bytes + + msg = message_from_bytes(raw) + self.messages.append( + { + "ID": str(len(self.messages) + 1), + "MessageID": str(msg["Message-ID"] or "").strip("<>"), + "Subject": str(msg["Subject"] or ""), + "To": [{"Address": a.strip()} for a in str(msg["To"] or "").split(",") if a.strip()], + } + ) + + def close(self) -> None: + for s in (self.smtp, self.api): + s.shutdown() + s.server_close() From 18bb64a26d53b2ed40b01a017ae386755ea04e90 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:44:19 -0500 Subject: [PATCH 02/21] feat(proxy): hold database credentials; preview, apply once and undo each SQL statement over MCP --- CAPABILITIES.md | 1 + openadapt/cli.py | 27 + packages/flow/benchmark/ext_tx/compose.yml | 22 + packages/flow/benchmark/ext_tx/run.py | 526 ++++++++++++++++++ packages/flow/docs/TRANSACTIONS.md | 152 +++++ .../11-guard-an-agent-you-already-run/plan.md | 1 + .../proxy.md | 1 + packages/flow/openadapt_flow/__main__.py | 4 + .../flow/openadapt_flow/txplan/adapters.py | 153 ++++- packages/flow/openadapt_flow/txplan/engine.py | 199 ++++++- packages/flow/openadapt_flow/txplan/proxy.py | 366 ++++++++++++ .../flow/openadapt_flow/txplan/proxy_cli.py | 74 +++ packages/flow/openadapt_flow/txplan/spec.py | 15 +- packages/flow/tests/test_txplan.py | 127 +++++ 14 files changed, 1644 insertions(+), 24 deletions(-) create mode 100644 packages/flow/benchmark/ext_tx/compose.yml create mode 100644 packages/flow/benchmark/ext_tx/run.py create mode 100644 packages/flow/docs/TRANSACTIONS.md create mode 100644 packages/flow/docs/commands/11-guard-an-agent-you-already-run/plan.md create mode 100644 packages/flow/docs/commands/11-guard-an-agent-you-already-run/proxy.md create mode 100644 packages/flow/openadapt_flow/txplan/proxy.py create mode 100644 packages/flow/openadapt_flow/txplan/proxy_cli.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index f3f57cecf6..98ced845b8 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -488,6 +488,7 @@ A test fails when a command has no file or this list is out of date. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +- `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/openadapt/cli.py b/openadapt/cli.py index 50bcdc287d..7cfc567909 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1901,6 +1901,33 @@ def plan(command_ctx: click.Context) -> None: sys.exit(int(plan_main(list(command_ctx.args)) or 0)) +@main.command( + "proxy", + context_settings={ + "ignore_unknown_options": True, + "allow_extra_args": True, + "help_option_names": [], + }, +) +@click.pass_context +def proxy(command_ctx: click.Context) -> None: + """Hold the database credentials; give the agent tools that preview, apply once and undo.""" + _require_supported_python() + proxy_main = _optional_engine_entrypoint(command_ctx, ("openadapt_flow.txplan.proxy_cli",)) + if proxy_main is None: + click.echo( + "Error: this openadapt-flow installation has no proxy command.", err=True + ) + sys.exit(2) + args = list(command_ctx.args) + # Click drops a bare "--"; restore it from argv so the agent's arguments stay its own. + if "--" in sys.argv and "--" not in args: + tail = sys.argv[sys.argv.index("--") + 1 :] + if tail and args[-len(tail):] == tail: + args = args[: -len(tail)] + ["--"] + tail + sys.exit(int(proxy_main(args) or 0)) + + @main.command( "wrap", context_settings={ diff --git a/packages/flow/benchmark/ext_tx/compose.yml b/packages/flow/benchmark/ext_tx/compose.yml new file mode 100644 index 0000000000..0d75e61820 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/compose.yml @@ -0,0 +1,22 @@ +# External transaction safety lab (openadapt plan): a REST app and an email sink. +# Ports bind to loopback inside WSL; the harness runs there through remote-run.sh. +# Synthetic data only. The database-backed app is the standing zen-dolibarr fixture. +name: oa-ext-tx +services: + vikunja: + image: vikunja/vikunja:2.7.1 + environment: + VIKUNJA_SERVICE_PUBLICURL: http://127.0.0.1:9670/ + VIKUNJA_SERVICE_ENABLEREGISTRATION: "true" + VIKUNJA_SERVICE_SECRET: synthetic-lab-jwt-secret-not-a-real-one + VIKUNJA_DATABASE_TYPE: sqlite + VIKUNJA_DATABASE_PATH: /db/vikunja.db + ports: ["127.0.0.1:9670:3456"] + tmpfs: ["/db:uid=1000", "/app/vikunja/files:uid=1000"] + mem_limit: 512m + mailpit: + image: axllent/mailpit:v1.27.10 + environment: + MP_MAX_MESSAGES: "20000" + ports: ["127.0.0.1:9671:1025", "127.0.0.1:9672:8025"] + mem_limit: 256m diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py new file mode 100644 index 0000000000..7469154ec5 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/run.py @@ -0,0 +1,526 @@ +"""Lab proof for ``openadapt plan`` on real apps: Vikunja (REST), Mailpit +(email sink) and Dolibarr's MariaDB (a database-backed app). + +Run inside the zenbook's WSL, from packages/flow:: + + ~/oa/scratch/winlap/remote-run.sh uv run --with pymysql \\ + python benchmark/ext_tx/run.py --phase measured --out benchmark/ext_tx/results/x.json + +The app-specific declarations (server-set and derived fields, ignored +tables) are in ``SPEC`` below and are fixed before a measured run. The +results file holds counts and digests, never record values. Synthetic data +only. Kill criteria (any one stops the work): + +* a verified undo fails on more than 5% of supported writes; +* the dry-run diff misses an effect the later read-back finds; +* a double effect gets through the idempotency test. +""" + +from __future__ import annotations + +import argparse +import json +import os +import random +import re +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any, Callable + +import httpx +import yaml + +from openadapt_flow.txplan import engine +from openadapt_flow.txplan.adapters import MailAdapter, RestAdapter, SqlAdapter +from openadapt_flow.txplan.engine import Ctx, TxRefused +from openadapt_flow.txplan.spec import load_spec +from openadapt_flow.txplan.state import State + +VIKUNJA = os.environ.get("LAB_VIKUNJA", "http://127.0.0.1:9670") +MAILPIT = os.environ.get("LAB_MAILPIT", "http://127.0.0.1:9672") +SMTP_PORT = int(os.environ.get("LAB_SMTP_PORT", "9671")) +DOLI_COMPOSE = Path.home() / "fixtures" / "dolibarr" / "compose.yml" + +#: Frozen before the measured run. Everything app-specific is here. +SPEC: dict[str, Any] = { + "schema_version": "openadapt.tx/v1", + "holdback_s": 1, + "anomalies": [ + {"field": "amount", "above": 10000, "label": "large amount"}, + {"op": "delete", "label": "delete"}, + {"max_writes": 500, "label": "large batch"}, + ], + "systems": [ + { + "name": "vikunja", + "kind": "rest", + "base_url": VIKUNJA, + "auth": {"header": "Authorization", "prefix": "Bearer ", "value_env": "LAB_VIKUNJA_TOKEN"}, + "collections": [ + { + "name": "task", + "id_field": "id", + "list": {"path": "/api/v1/tasks", "page_param": "page", "per_page": 50}, + "read": {"path": "/api/v1/tasks/{id}"}, + "create": {"method": "PUT", "path": "/api/v1/projects/{project_id}/tasks"}, + "update": {"method": "POST", "path": "/api/v1/tasks/{id}", "replace": True}, + "delete": {"method": "DELETE", "path": "/api/v1/tasks/{id}"}, + "server_fields": ["updated"], + "derived": {"done": ["done_at"]}, + } + ], + }, + { + "name": "outbox", + "kind": "mail", + "smtp": {"host": "127.0.0.1", "port": SMTP_PORT}, + "mailbox": {"kind": "mailpit", "base_url": MAILPIT}, + }, + { + "name": "dolibarr", + "kind": "sql", + "dialect": "mysql", + "driver": "pymysql", + "connect_args": { + "host": "127.0.0.1", "port": 9636, "user": "dolidbuser", + "database": "dolidb", "charset": "utf8mb4", + }, + "password_env": "LAB_DOLI_DB_PASSWORD", + "tables": {"llx_societe": "rowid"}, + }, + ], +} + +#: Per-app overrides learned in the pilot, applied in both phases once fixed. +PILOT_DECLARATIONS: dict[str, Any] = {} + + +def log(msg: str) -> None: + print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) + + +# -- setup --------------------------------------------------------------------- + + +def doli_password() -> str: + text = DOLI_COMPOSE.read_text() + m = re.search(r"DOLI_DB_PASSWORD:\s*\"?([^\"\n]+)\"?", text) + if not m: + raise SystemExit("cannot find the fixture's synthetic DB password") + return m.group(1).strip() + + +def vikunja_setup() -> tuple[str, int]: + user = f"lab{int(time.time())}" + pw = "synthetic-Lab-pass-1" + c = httpx.Client(base_url=VIKUNJA, timeout=20) + r = c.post("/api/v1/register", json={"username": user, "email": f"{user}@example.test", "password": pw}) + r.raise_for_status() + token = c.post("/api/v1/login", json={"username": user, "password": pw}).json()["token"] + c.headers["Authorization"] = f"Bearer {token}" + project = c.put("/api/v1/projects", json={"title": "lab project"}).json()["id"] + for i in range(40): + c.put(f"/api/v1/projects/{project}/tasks", json={ + "title": f"seed task {i}", "description": f"synthetic {i}", "priority": i % 5, + }).raise_for_status() + return token, int(project) + + +def doli_seed(adapter: SqlAdapter, n: int) -> list[int]: + con = adapter.connect() + ids = [] + try: + cur = con.cursor() + tag = int(time.time()) + for i in range(n): + cur.execute( + "INSERT INTO llx_societe (nom, entity, datec, status, client, note_public, phone, town) " + "VALUES (%s, 1, NOW(), 1, 1, %s, %s, %s)", + (f"Lab seed {tag}-{i}", "synthetic", f"555-01{i:02d}", "Labtown"), + ) + ids.append(int(cur.lastrowid)) + con.commit() + finally: + con.close() + return ids + + +def doli_cleanup(adapter: SqlAdapter, prefix: str = "Lab ") -> int: + con = adapter.connect() + try: + cur = con.cursor() + cur.execute("DELETE FROM llx_societe WHERE nom LIKE %s", (prefix + "%",)) + n = cur.rowcount + con.commit() + return n + finally: + con.close() + + +# -- batches ------------------------------------------------------------------- + + +def rest_batch(rng: random.Random, ids: list[int], project: int, b: int) -> list[dict[str, Any]]: + out = [] + for tid in rng.sample(ids, 6): + field = rng.choice(["title", "description", "priority", "done", "percent_done"]) + value: Any = { + "title": f"edited {b}-{tid}", + "description": f"synthetic edit {b}", + "priority": rng.randint(0, 5), + "done": rng.choice([True, False]), + "percent_done": rng.choice([0.1, 0.5, 0.9]), + }[field] + out.append({"system": "vikunja", "collection": "task", "op": "update", "id": tid, "fields": {field: value}}) + for i in range(4): + out.append({"system": "vikunja", "collection": "task", "op": "create", + "fields": {"title": f"new {b}-{i}", "project_id": project, "description": "synthetic"}}) + return out + + +def sql_batch(rng: random.Random, ids: list[int], b: int, tag: int) -> list[dict[str, Any]]: + picks = rng.sample(ids, 7) + out = [] + for rid in picks[:5]: + field = rng.choice(["note_public", "phone", "town", "email"]) + value = {"note_public": f"synthetic note {b}", "phone": f"555-9{b:03d}", + "town": f"Town {b}", "email": f"lab{b}@example.test"}[field] + out.append({"system": "dolibarr", "collection": "llx_societe", "op": "update", "id": rid, + "fields": {field: value}}) + for rid in picks[5:]: + out.append({"system": "dolibarr", "collection": "llx_societe", "op": "delete", "id": rid}) + for i in range(3): + out.append({"system": "dolibarr", "collection": "llx_societe", "op": "create", + "fields": {"nom": f"Lab new {tag}-{b}-{i}", "entity": 1, "datec": "2026-11-21 12:00:00", + "status": 1, "client": 1}}) + return out + + +def mail_batch(b: int) -> list[dict[str, Any]]: + return [{"system": "outbox", "op": "send", + "fields": {"to": f"lab{b}-{i}@example.test", "subject": f"Synthetic notice {b}-{i}", + "body": "synthetic body"}} for i in range(10)] + + +# -- one round ----------------------------------------------------------------- + + +def round_trip(ctx: Ctx, task: str, writes: list[dict[str, Any]], *, release_first: int = 0) -> dict[str, Any]: + plan = engine.make_plan(ctx, task, writes) + engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + applied = engine.apply_plan(ctx, plan["digest"]) + released = None + if release_first: + time.sleep(1.2) + # Release only the first N held writes: cancel the rest first. + held = [h for h in ctx.state.held() if h["plan"] == plan["digest"]] + for h in held[release_first:]: + ctx.state.unhold(h["key"]) + e = ctx.state.entry(h["key"]) + ctx.state.record(h["key"], "cancelled", plan=plan["digest"], payload=e.payload if e else "") + released = engine.release(ctx, plan["digest"]) + undone = engine.undo_plan(ctx, plan["digest"]) + mailbox = None + if release_first: + mail = ctx.adapter("outbox") + per = {"cancelled_never_sent": 0, "cancelled_sent": 0, "released_exactly_once": 0, "released_other": 0} + for w in plan["writes"]: + n = mail.count(w["key"]) + status = ctx.state.entry(w["key"]).status + if status == "cancelled": + per["cancelled_never_sent" if n == 0 else "cancelled_sent"] += 1 + else: + per["released_exactly_once" if n == 1 else "released_other"] += 1 + mailbox = per + return { + "mailbox": mailbox, + "digest": plan["digest"][:16], + "dry_run": plan["dry_run"], + "anomalies": len(plan["anomalies"]), + "apply": applied["tx"], "apply_outcome": applied["outcome"], + "missed": applied["missed"], "false": applied["false"], + "release": released["tx"] if released else None, + "undo": undone["tx"], "undo_outcome": undone["outcome"], + "collateral": undone["collateral"][:10], + } + + +def acrfence(ctx: Ctx, kind: str, trials: int, count: Callable[[], int], make: Callable[[str, int], dict[str, Any]], + *, release: bool = False) -> dict[str, Any]: + """Control arm (no guard) and guarded arm, per trial.""" + raw = ctx.adapter(make("x", 0)["system"]) + ctrl_dups = 0 + guarded_extra = 0 + blocked = 0 + replays_not_sent = 0 + for t in range(trials): + # Control: the paper's UUID-style request check sees two different requests. + n0 = count() + a, b = make(f"ctrl-a-{t}", t), make(f"ctrl-b-{t}", t) + if isinstance(raw, MailAdapter): + raw.send(a, f"ik-ctrla{t:035d}") + raw.send(b, f"ik-ctrlb{t:035d}") + time.sleep(0.5) + else: + raw.apply(a, None, f"req-a-{t}") + raw.apply(b, None, f"req-b-{t}") + ctrl_dups += count() - n0 - 1 + # Guarded. + task = f"acr-{kind}-{t}-{int(time.time())}" + n0 = count() + p = engine.make_plan(ctx, task, [make(f"uuid-a-{t}", t)]) + engine.approve_plan(ctx.state, p["digest"], approver="lab", decided_by="automation") + engine.apply_plan(ctx, p["digest"]) + if release: + time.sleep(1.2) + engine.release(ctx, p["digest"]) + # Restore: drop the agent's in-memory context and regenerate the payload. + ctx2 = Ctx(spec=ctx.spec, state=State(ctx.state.root)) + q = engine.make_plan(ctx2, task, [make(f"uuid-b-{t}", t)]) + engine.approve_plan(ctx2.state, q["digest"], approver="lab", decided_by="automation") + try: + engine.apply_plan(ctx2, q["digest"]) + except TxRefused as exc: + blocked += int(exc.code == "replay_mismatch") + r = engine.make_plan(ctx2, task, [make(f"uuid-a-{t}", t)]) + engine.approve_plan(ctx2.state, r["digest"], approver="lab", decided_by="automation") + out = engine.apply_plan(ctx2, r["digest"]) + if release: + time.sleep(1.2) + engine.release(ctx2, r["digest"]) + replays_not_sent += int(out["tx"].get("replays", 0) == 1 and out["tx"]["sent"] == 0) + time.sleep(0.3 if release else 0) + guarded_extra += max(0, count() - n0 - 1) + return {"trials": trials, "control_duplicates": ctrl_dups, "blocked": blocked, + "identical_replays_not_sent": replays_not_sent, "double_effects_through": guarded_extra} + + +def crash_arm(spec_path: Path, state_root: Path, trials: int, count: Callable[[], int], + make: Callable[[str, int], dict[str, Any]]) -> dict[str, Any]: + extra = 0 + crashed = 0 + for t in range(trials): + ctx = Ctx(spec=load_spec(spec_path), state=State(state_root)) + task = f"crash-{t}-{int(time.time())}" + n0 = count() + p = engine.make_plan(ctx, task, [make(f"uuid-c-{t}", t)]) + engine.approve_plan(ctx.state, p["digest"], approver="lab", decided_by="automation") + code = ( + "from pathlib import Path; from openadapt_flow.txplan import engine;" + "from openadapt_flow.txplan.spec import load_spec; from openadapt_flow.txplan.state import State;" + f"engine.apply_plan(engine.Ctx(load_spec(Path({str(spec_path)!r})), State(Path({str(state_root)!r}))), {p['digest']!r})" + ) + proc = subprocess.run([sys.executable, "-c", code], env={**os.environ, engine.CRASH_ENV: "1"}, + capture_output=True, timeout=300) + crashed += int(proc.returncode == 70) + for ref in (f"uuid-d-{t}", f"uuid-c-{t}"): # regenerated, then identical + q = engine.make_plan(ctx, task, [make(ref, t)]) + engine.approve_plan(ctx.state, q["digest"], approver="lab", decided_by="automation") + try: + engine.apply_plan(ctx, q["digest"]) + except TxRefused: + pass + extra += max(0, count() - n0 - 1) + return {"trials": trials, "crashed_after_send": crashed, "double_effects_through": extra} + + +def seeded_faults(ctx: Ctx, writes_fn: Callable[[int], list[dict[str, Any]]], poke: Callable[[], None], + adapter_cls: Any, trials: int) -> dict[str, Any]: + """A change the plan didn't predict, during apply and before undo: both must be caught.""" + caught_apply = caught_undo = 0 + real = adapter_cls.apply + for t in range(trials): + def apply_and_poke(self, w, base, key, _real=real): # noqa: ANN001 + out = _real(self, w, base, key) + poke() + return out + + plan = engine.make_plan(ctx, f"fault-a-{t}-{int(time.time())}", writes_fn(t)) + engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + adapter_cls.apply = apply_and_poke + try: + applied = engine.apply_plan(ctx, plan["digest"]) + finally: + adapter_cls.apply = real + caught_apply += int(applied["tx"]["missed_effects"] > 0) + engine.undo_plan(ctx, plan["digest"]) + plan = engine.make_plan(ctx, f"fault-u-{t}-{int(time.time())}", writes_fn(1000 + t)) + engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + engine.apply_plan(ctx, plan["digest"]) + poke() + undone = engine.undo_plan(ctx, plan["digest"]) + caught_undo += int(undone["outcome"] != "ROLLED_BACK" and undone["tx"]["collateral_changes"] > 0) + return {"trials": trials, "missed_effect_caught": caught_apply, "collateral_caught": caught_undo} + + +# -- main ---------------------------------------------------------------------- + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--phase", choices=["pilot", "measured"], required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--batches", type=int, default=10) + ap.add_argument("--acr-trials", type=int, default=20) + ap.add_argument("--seed", type=int, default=20261121) + args = ap.parse_args() + rng = random.Random(args.seed) + work = Path(tempfile.mkdtemp(prefix="ext-tx-")) + os.environ["OPENADAPT_TX_STATE"] = str(work / "state") + os.environ.setdefault("OPENADAPT_SEAL_HOME", str(work / "seal")) + os.environ["LAB_DOLI_DB_PASSWORD"] = doli_password() + token, project = vikunja_setup() + os.environ["LAB_VIKUNJA_TOKEN"] = token + spec_path = work / "openadapt.tx.yaml" + spec_path.write_text(yaml.safe_dump(SPEC)) + ctx = Ctx(spec=load_spec(spec_path), state=State()) + vik: RestAdapter = ctx.adapter("vikunja") + sql: SqlAdapter = ctx.adapter("dolibarr") + mail: MailAdapter = ctx.adapter("outbox") + ids = sorted(int(r.split("/")[1]) for r in vik.frame("task")) + log(f"vikunja: {len(ids)} tasks; project {project}") + tag = int(time.time()) + doli_ids = doli_seed(sql, 60) + log(f"dolibarr: seeded {len(doli_ids)} thirdparties") + results: dict[str, Any] = { + "schema": "openadapt.ext-tx-lab/v1", + "phase": args.phase, + "started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "apps": {"rest": "Vikunja 2.7.1", "email": "Mailpit v1.27.10", "database": "Dolibarr 21.0.4 on MariaDB 11.4.13"}, + "spec_sha256": __import__("hashlib").sha256(spec_path.read_bytes()).hexdigest(), + "rounds": {"rest": [], "sql": [], "mail": []}, + } + try: + for b in range(args.batches): + r = round_trip(ctx, f"lab-rest-{tag}-{b}", rest_batch(rng, ids, project, b)) + results["rounds"]["rest"].append(r) + log(f"rest {b}: apply {r['apply_outcome']} missed {r['missed']} false {r['false']} undo {r['undo_outcome']} {r['undo']['codes']} {r['collateral']}") + for b in range(args.batches): + r = round_trip(ctx, f"lab-sql-{tag}-{b}", sql_batch(rng, doli_ids, b, tag)) + results["rounds"]["sql"].append(r) + log(f"sql {b}: apply {r['apply_outcome']} missed {r['missed']} false {r['false']} undo {r['undo_outcome']} {r['undo']['codes']} {r['collateral']}") + for b in range(args.batches): + r = round_trip(ctx, f"lab-mail-{tag}-{b}", mail_batch(b), release_first=5) + results["rounds"]["mail"].append(r) + log(f"mail {b}: apply {r['apply_outcome']} release {r['release']} undo {r['undo']['codes']}") + + def vik_count() -> int: + return len(vik.frame("task")) + + def vik_make(ref: str, t: int) -> dict[str, Any]: + return {"system": "vikunja", "collection": "task", "op": "create", + "fields": {"title": f"refund {ref}", "project_id": project, "description": f"reference {ref}"}} + + def sql_count() -> int: + return sum(1 for r in sql.frame() if r.startswith("llx_societe/")) + + def sql_make(ref: str, t: int) -> dict[str, Any]: + return {"system": "dolibarr", "collection": "llx_societe", "op": "create", + "fields": {"nom": f"Lab refund {tag}-{ref}", "entity": 1, "datec": "2026-11-21 12:00:00", + "status": 1, "client": 1}} + + def mail_count() -> int: + return len(mail.frame()) + + def mail_make(ref: str, t: int) -> dict[str, Any]: + return {"system": "outbox", "op": "send", + "fields": {"to": "billing@example.test", "subject": f"Refund {ref}", "body": f"reference {ref}"}} + + results["acrfence"] = { + "rest": acrfence(ctx, "rest", args.acr_trials, vik_count, vik_make), + "sql": acrfence(ctx, "sql", args.acr_trials, sql_count, sql_make), + "mail": acrfence(ctx, "mail", args.acr_trials, mail_count, mail_make, release=True), + } + log(f"acrfence {results['acrfence']}") + results["crash"] = { + "rest": crash_arm(spec_path, ctx.state.root, max(5, args.acr_trials // 4), vik_count, vik_make), + "sql": crash_arm(spec_path, ctx.state.root, max(5, args.acr_trials // 4), sql_count, sql_make), + } + log(f"crash {results['crash']}") + + other = [i for i in ids if i % 7 == 0][:1] + + def vik_poke() -> None: + got = vik.read("task", str(other[0])) or {} + body = {k: v for k, v in got.items() if k != "updated"} + body["description"] = f"poked {time.time()}" + vik.http.post(f"/api/v1/tasks/{other[0]}", json=body).raise_for_status() + + def sql_poke() -> None: + con = sql.connect() + try: + cur = con.cursor() + cur.execute("UPDATE llx_societe SET town = %s WHERE rowid = %s", (f"poked {time.time()}", doli_ids[-1])) + con.commit() + finally: + con.close() + + results["seeded_faults"] = { + "rest": seeded_faults(ctx, lambda t: [{"system": "vikunja", "collection": "task", "op": "update", + "id": ids[t % 5], "fields": {"priority": (t % 4) + 1}}], + vik_poke, RestAdapter, 5), + "sql": seeded_faults(ctx, lambda t: [{"system": "dolibarr", "collection": "llx_societe", "op": "update", + "id": doli_ids[t % 5], "fields": {"phone": f"555-7{t:03d}"}}], + sql_poke, SqlAdapter, 5), + } + log(f"faults {results['seeded_faults']}") + finally: + removed = doli_cleanup(sql) + log(f"dolibarr cleanup: removed {removed} lab rows") + results["finished_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + results["summary"] = summarize(results) + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text(json.dumps(results, indent=2, sort_keys=True) + "\n") + log(json.dumps(results["summary"], indent=2, sort_keys=True)) + return 0 + + +def summarize(res: dict[str, Any]) -> dict[str, Any]: + out: dict[str, Any] = {} + for kind, rounds in res["rounds"].items(): + if not rounds: + continue + sup = sum(r["undo"]["undo_supported"] for r in rounds) + ver = sum(r["undo"]["undo_verified"] for r in rounds) + out[kind] = { + "rounds": len(rounds), + "writes": sum(r["apply"]["writes"] for r in rounds), + "apply_verified_rounds": sum(1 for r in rounds if r["apply_outcome"] in ("VERIFIED", "COMPLETED_UNVERIFIED")), + "missed_effects": sum(r["apply"].get("missed_effects", 0) for r in rounds), + "false_diffs": sum(r["apply"].get("false_diffs", 0) for r in rounds), + "undo_supported": sup, + "undo_verified": ver, + "undo_success_rate": round(ver / sup, 4) if sup else None, + "cancelled_in_holdback": sum(r["undo"].get("cancelled", 0) for r in rounds), + "irreversible_released": sum(r["undo"].get("irreversible_released", 0) for r in rounds), + "release_double_sends": sum((r["release"] or {}).get("double", 0) for r in rounds), + **{k: sum((r.get("mailbox") or {}).get(k, 0) for r in rounds) + for k in ("cancelled_never_sent", "cancelled_sent", "released_exactly_once", "released_other")}, + } + acr = res.get("acrfence", {}) + crash = res.get("crash", {}) + out["double_effects_through"] = sum(v["double_effects_through"] for v in acr.values()) + sum( + v["double_effects_through"] for v in crash.values()) + out["blocked_double_effects"] = sum(v["blocked"] for v in acr.values()) + out["control_duplicates"] = sum(v["control_duplicates"] for v in acr.values()) + kills = [] + m = out.get("mail") or {} + if m.get("cancelled_sent") or m.get("released_other"): + kills.append("mail: a cancelled email was sent or a released one was not sent exactly once") + for kind in ("rest", "sql"): + k = out.get(kind) or {} + if k.get("undo_success_rate") is not None and k["undo_success_rate"] < 0.95: + kills.append(f"{kind}: undo success {k['undo_success_rate']}") + if k.get("missed_effects"): + kills.append(f"{kind}: {k['missed_effects']} missed effects") + if out["double_effects_through"]: + kills.append(f"{out['double_effects_through']} double effects through") + out["kill_criteria_tripped"] = kills + return out + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/flow/docs/TRANSACTIONS.md b/packages/flow/docs/TRANSACTIONS.md new file mode 100644 index 0000000000..201cf837d9 --- /dev/null +++ b/packages/flow/docs/TRANSACTIONS.md @@ -0,0 +1,152 @@ +# External transactions: plan, apply, undo + +`openadapt plan` gives a batch of agent writes to external systems (a REST +API, a SQL database, email) four properties: + +1. **Dry-run diff.** Before anything is sent, you see what would change, for + example "398 crm.contacts updated, 14 outbox.outbox queued, 1 anomaly: + large refund: amount = 42000". Approval binds to that exact plan digest and + can be used once. +2. **Idempotent retry.** Each write carries a key derived from the task, the + system, the collection, the operation and the record slot. The key never + comes from the payload. After a crash or a rewind, a retry that regenerates + a different payload is refused (`replay_mismatch`). An identical retry gets + the stored result, and nothing is sent. +3. **Verified undo.** Each applied write has a compensating action. After the + undo, every touched record and the whole frame around it (the collection, + every table of the database) are read back and compared with the baseline. + Irreversible writes (email, a delete the API can't reverse) wait in a + cancelable holdback queue before they are released. +4. **Receipts.** Plan, apply, undo and release each write a `report.json` + (digests and counts, never record values) and a signed `record/run/v1` + receipt. The receipt's `approval` block commits to the approved plan + digest. + +Healthy runs make no model calls. + +``` +openadapt plan create --tx openadapt.tx.yaml --task T-42 writes.json +openadapt plan approve 3f2a9c1e # a person, at a terminal; types the digest +openadapt plan apply --tx openadapt.tx.yaml 3f2a9c1e +openadapt plan undo --tx openadapt.tx.yaml 3f2a9c1e +openadapt plan release --tx openadapt.tx.yaml 3f2a9c1e # held email, after holdback +openadapt plan cancel 3f2a9c1e # drop held writes instead +openadapt plan status +``` + +## The tx file + +`openadapt.tx.yaml` (`openadapt.tx/v1`) declares each system and how to read, +list, write and undo it. Everything specific to an app lives in this file, +never in the engine. See the docstring of +[`openadapt_flow/txplan/spec.py`](../openadapt_flow/txplan/spec.py) for every +key. Three kinds of system: + +| Kind | Dry run | Read-back frame | Undo | +|---|---|---|---| +| `sql` (SQLite, MySQL/MariaDB, PostgreSQL) | **Staged transaction.** The planned statements run inside a transaction. Every table is read before and after, inside that transaction, and then the transaction is rolled back. Triggers and cascades appear in the diff. | Every table of the database (`frame_ignore_tables` and `frame_ignore_columns` excluded) | A create is deleted by key. An update gets back its whole before-image, including columns the database set itself. A delete is reinserted with its exact row. | +| `rest` (JSON over HTTP) | **Computed shadow.** The baseline merged with the planned fields. `server_fields` are ignored, and `derived` fields are expected to change with their cause. | The whole collection, through its list route, every page | A create is deleted. An update is restored, and for `replace: true` APIs the full baseline is sent. A delete waits in holdback unless `delete_reversible` is set. | +| `mail` (SMTP and a Mailpit API) | **Holdback.** A send is queued, never sent at apply. | The mailbox | Cancel before release. A released email can't be undone. | + +A write is `{"system", "collection", "op", "id", "fields"}`, with `op` one of +`create`, `update`, `delete` or `send`. An update or delete names the +record's `id`. A create or send has no id: its slot is its ordinal within the +task (`create#1`, `create#2`). + +## Why the key isn't the payload + +A checkpoint restore makes an agent regenerate a request that is slightly +different from the one it already sent: a new reference id, a reworded memo. +A server that dedupes on a request id or on the payload sees a new request, +and the write lands twice. The ACRFence paper calls this a semantic rollback +attack, specifically *action replay* (see [References](#references)). +`openadapt plan` keys each write on what OpenAdapt knows independently of the +model: the task id, the system, the collection, the operation, and the record +id or the create's ordinal. It stores the payload digest and the plan digest +under that key. + +- A second write under a key whose payload digest differs is refused before + anything is sent. The plan already shows it as an anomaly ("replays an + applied write with a different payload"). +- The plan digest is bound to the key, not part of it. If the plan digest + were part of the key, a re-plan would mint a fresh key and defeat the guard. +- An open attempt, where the send may have landed but the outcome was never + recorded, is resolved by reading the record back, never by sending again. + An update that reads back as planned is adopted. A create that can't be + attributed is held as `UNCERTAIN` for a person. +- The ledger, approvals and holdback queue live in `~/.openadapt/tx` (or + `$OPENADAPT_TX_STATE`), outside the agent's workspace. A restore of the + workspace can't roll them back. +- Approvals are single-use. Apply consumes the approval before its first send, + so a consumed approval can't authorize a second apply. This covers the + paper's second class, *authority resurrection*. + +The task id must be OpenAdapt's own (a run or ticket id), not text the model +writes. A model that can choose a new task id for each retry can mint new +keys. + +## Before apply + +`apply` refuses, and sends nothing, when: + +- the tx file changed since the plan (`spec_changed`); +- any key was already used with a different payload (`replay_mismatch`); +- any frame moved since the plan, which makes the plan stale (`plan_stale`). + In that case the approval isn't consumed; +- the plan has no unused approval (`not_approved`, `approval_consumed`). + +After the writes, apply reads every frame again and compares the diff with +the prediction. A **missed effect** is something the read-back found that the +dry run didn't predict. A **false diff** is something the dry run predicted +that the read-back didn't find. Either one makes the outcome +`RECONCILIATION_REQUIRED`. + +## Undo + +`undo` runs latest write first, and only on writes this plan applied: + +- It refuses a record that changed since apply (`changed_since_apply`). A + person's later edit is never overwritten. +- Held writes are cancelled. +- After compensating, it reads each record back. A create must be gone. An + update or delete must equal its baseline. +- It then compares the whole frame with the baseline. Any other change is + collateral, and then no undo in the plan counts as verified. + +Some effects can't be undone exactly: a trigger that writes an audit row on +every update, or an auto-increment counter. When the trigger's rows are in +the frame, the undo is reported `RECONCILIATION_REQUIRED` with the collateral +count, never `ROLLED_BACK`. Counters aren't rows and aren't compared. + +## Hooks and wrap + +`openadapt plan apply` is the executor: OpenAdapt makes the write. For a +coding agent that also has direct access, declare the same system in +`openadapt.systems.yaml` with `approval: block` ([HOOKS.md](HOOKS.md)), so a +direct write is refused and batch writes go through a plan. `openadapt wrap` +([WRAP.md](WRAP.md)) is a browser MCP harness, not a broker for these +systems. Like the hooks, this layer is advisory against an agent that holds +its own credentials to the system. + +## Lab results + +`benchmark/ext_tx/run.py` runs every flow against real apps on the lab +machine: Vikunja 2.7.1 (REST), Mailpit v1.27.10 (email), and Dolibarr 21.0.4 +on MariaDB 11.4.13 (a database-backed app, written through SQL). The results +are in `benchmark/ext_tx/results/`. See [the summary below](#measured). + +## References + +- Zheng, Yang, Zhang, Quinn. *ACRFence: Preventing Semantic Rollback Attacks + in Agent Checkpoint-Restore.* arXiv:2603.20625, March 2026. + +- Dong et al. *DeltaBox: Millisecond-Scale Sandbox Checkpoint and Rollback + for Stateful AI Agents.* arXiv:2605.22781. + DeltaState is its OS abstraction, and it rolls back only state inside the + sandbox. +- Li et al. *PACE: Provenance-Aware Capability Enforcement for Tool-Using LLM + Agents.* arXiv:2610.01349. +- Rubrik, *Rubrik Unveils Agent Rewind For When AI Agents Go Awry*, 12 August + 2025. + +- Neon, *Branching*. diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/plan.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/plan.md new file mode 100644 index 0000000000..5bc85ce74f --- /dev/null +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/plan.md @@ -0,0 +1 @@ +Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/proxy.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/proxy.md new file mode 100644 index 0000000000..854cdc8dd1 --- /dev/null +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/proxy.md @@ -0,0 +1 @@ +Holds the database credentials and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof. diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 5b6350a3a7..db352ba950 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13226,6 +13226,10 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _add_plan_parser(sub) + from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser + + _add_proxy_parser(sub) + from openadapt_flow.cli_fleet import register_fleet_parser register_fleet_parser(sub) diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index 66a538fadc..eabdab3cd4 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -48,6 +48,20 @@ class AdapterError(RuntimeError): """A read or a write failed. For a write, delivery is unknown.""" +class Diverged(AdapterError): + """The statement did something other than the plan showed. Nothing landed.""" + + +def _shape(diff: Mapping[str, Any]) -> tuple[Any, ...]: + """A diff, comparable across runs: ids added by a sequence can differ, so + added rows count per table.""" + added: dict[str, int] = {} + for rid in diff["added"]: + t = rid.split("/", 1)[0] + added[t] = added.get(t, 0) + 1 + return (sorted(added.items()), sorted(diff["removed"]), sorted((k, tuple(v)) for k, v in diff["changed"].items())) + + # -- values -------------------------------------------------------------------- @@ -370,6 +384,8 @@ def read_mapping(self) -> dict[str, Any]: } def _begin(self, cur: Any) -> None: + if self.system.dialect == "postgresql": + return # the DB-API driver opens a transaction on the first statement cur.execute("BEGIN" if self.system.dialect != "mysql" else "START TRANSACTION") def _ident(self, name: str) -> str: @@ -425,7 +441,11 @@ def _rows(self, cur: Any, table: str) -> tuple[list[str], list[tuple[Any, ...]]] cols = [str(d[0]) for d in cur.description] return cols, list(cur.fetchall()) - def frame_cur(self, cur: Any) -> dict[str, dict[str, str]]: + def frame_cur( + self, cur: Any, rows_out: Optional[dict[str, Any]] = None + ) -> dict[str, dict[str, str]]: + """Every table's rows as column digests. With ``rows_out``, also keep + each row's tagged values there (in memory, for undo images).""" out: dict[str, dict[str, str]] = {} total = 0 for table in self._tables(cur): @@ -445,6 +465,10 @@ def frame_cur(self, cur: Any) -> dict[str, dict[str, str]]: seen[base] = seen.get(base, 0) + 1 rid = f"~{base}#{seen[base]}" out[f"{table}/{rid}"] = digs + if rows_out is not None: + rows_out[f"{table}/{rid}"] = { + "pk": pk, "row": {c: tag(v) for c, v in rec.items()} + } return out def frame(self, collection: Optional[str] = None) -> dict[str, dict[str, str]]: @@ -492,9 +516,12 @@ def normalize(self, coll: Any, record: Mapping[str, Any]) -> Record: def _exec(self, cur: Any, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: table = str(write["collection"]) key = self.system.tables.get(table) - if key is None: + if key is None and write["op"] != "sql": raise AdapterError(f"table {table} is not declared") op = write["op"] + if op == "sql": + cur.execute(str((write.get("fields") or {})["sql"])) + return {"rows": max(0, int(cur.rowcount or 0))} fields = {k: untag(v) for k, v in (write.get("fields") or {}).items()} t = self._ident(table) if op == "create": @@ -539,8 +566,22 @@ def stage( cur = con.cursor() self._begin(cur) try: - before = self.frame_cur(cur) - results = [self._exec(cur, w, b) for w, b in zip(writes, baselines)] + rows: dict[str, Any] = {} + before = self.frame_cur(cur, rows) + results = [] + prev = before + for w, b in zip(writes, baselines): + result = self._exec(cur, w, b) + if w["op"] == "sql": + now_ = self.frame_cur(cur) + result["staged_diff"] = diff_frames(prev, now_) + result["before_rows"] = { + rid: rows[rid]["row"] + for rid in [*result["staged_diff"]["removed"], *result["staged_diff"]["changed"]] + if rid in rows + } + prev = now_ + results.append(result) after = self.frame_cur(cur) finally: con.rollback() @@ -552,6 +593,8 @@ def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[ raise NotImplementedError("SQL plans are staged as one transaction") def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) -> dict[str, Any]: + if write["op"] == "sql": + return self._apply_sql(write) con = self.connect() try: cur = con.cursor() @@ -566,6 +609,94 @@ def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) finally: con.close() + def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: + """Run one statement; commit only if its diff, read inside the same + transaction, is exactly the diff the plan showed. Keep the undo images.""" + want = write.get("staged_diff") + if not isinstance(want, Mapping): + raise AdapterError("the plan has no staged diff for this statement") + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + rows: dict[str, Any] = {} + before = self.frame_cur(cur, rows) + result = self._exec(cur, write, None) + after_rows: dict[str, Any] = {} + after = self.frame_cur(cur, after_rows) + diff = diff_frames(before, after) + if _shape(diff) != _shape(want): + con.rollback() + raise Diverged("the statement's diff is not the planned diff; rolled back") + images = { + "before": {r: rows[r] for r in [*diff["removed"], *diff["changed"]]}, + "after": {r: after[r] for r in [*diff["added"], *diff["changed"]]}, + "added_pk": {r: after_rows[r] for r in diff["added"]}, + } + except Diverged: + raise + except Exception: + con.rollback() + raise + con.commit() + return {**result, "_images": images} + finally: + con.close() + + def compensate_sql(self, images: Mapping[str, Any]) -> None: + """Undo one statement from its images, in one transaction: delete what + it added, restore what it changed, reinsert what it removed.""" + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + for rid, item in images.get("added_pk", {}).items(): + self._delete_row(cur, rid, item) + for rid, item in images.get("before", {}).items(): + table = rid.split("/", 1)[0] + pk, row = item["pk"], item["row"] + if not pk: + raise AdapterError(f"{table} has no primary key: no generated undo") + where = " AND ".join(f"{self._ident(c)} = {self.ph}" for c in pk) + cur.execute(f"SELECT 1 FROM {self._ident(table)} WHERE {where}", + tuple(untag(row[c]) for c in pk)) + if cur.fetchall(): + cols = [c for c in row if c not in pk] + sets = ", ".join(f"{self._ident(c)} = {self.ph}" for c in cols) + if cols: + cur.execute( + f"UPDATE {self._ident(table)} SET {sets} WHERE {where}", + (*(untag(row[c]) for c in cols), *(untag(row[c]) for c in pk)), + ) + else: + cols = list(row) + cur.execute( + f"INSERT INTO {self._ident(table)} ({', '.join(self._ident(c) for c in cols)}) " + f"VALUES ({', '.join([self.ph] * len(cols))})", + tuple(untag(row[c]) for c in cols), + ) + except Exception: + con.rollback() + raise + con.commit() + finally: + con.close() + + def _delete_row(self, cur: Any, rid: str, item: Mapping[str, Any]) -> None: + table = rid.split("/", 1)[0] + pk, row = item["pk"], item["row"] + if not pk: + raise AdapterError(f"{table} has no primary key: no generated undo") + where = " AND ".join(f"{self._ident(c)} = {self.ph}" for c in pk) + cur.execute(f"DELETE FROM {self._ident(table)} WHERE {where}", tuple(untag(row[c]) for c in pk)) + + def current_digests(self, rids: Sequence[str]) -> dict[str, Optional[dict[str, str]]]: + """The current column digests of some frame rows (None when gone).""" + frame = self.frame() + return {r: frame.get(r) for r in rids} + def compensate( self, write: Mapping[str, Any], baseline: Optional[Record], result: Mapping[str, Any], key: str ) -> None: @@ -575,12 +706,14 @@ def compensate( inverse = {"op": "delete", "collection": write["collection"], "id": rid} elif op == "update": assert baseline is not None - inverse = { - "op": "update", - "collection": write["collection"], - "id": rid, - "fields": {k: baseline.get(k) for k in (write.get("fields") or {})}, - } + # The whole before-image, not just the planned columns: a column the + # database set itself (ON UPDATE CURRENT_TIMESTAMP, a trigger on the + # same row) is restored too, by naming its old value explicitly. + current = self.read(write["collection"], rid) or {} + fields = { + k: v for k, v in baseline.items() if k in current and not same(current.get(k), v) + } or {k: baseline.get(k) for k in (write.get("fields") or {})} + inverse = {"op": "update", "collection": write["collection"], "id": rid, "fields": fields} elif op == "delete": assert baseline is not None inverse = {"op": "create", "collection": write["collection"], "fields": dict(baseline)} diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 3b266e9c2e..6a25397d6e 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -18,6 +18,7 @@ from __future__ import annotations import os +import re import secrets from dataclasses import dataclass, field from pathlib import Path @@ -25,6 +26,7 @@ from openadapt_flow.txplan.adapters import ( AdapterError, + Diverged, MailAdapter, SqlAdapter, adapter_for, @@ -45,7 +47,11 @@ PLAN_SCHEMA = "openadapt.tx-plan/v1" REPORT_SCHEMA = "openadapt.tx-report/v1" -OPS = ("create", "update", "delete", "send") +OPS = ("create", "update", "delete", "send", "sql") +#: Ledger states after which a key is free again. +FREE = ("undone", "cancelled", "refused") +_DDL = re.compile(r"^\s*(create|alter|drop|truncate|rename|comment|grant|revoke)\b", re.I) +_READ = re.compile(r"^\s*(select|with|show|explain|pragma|values)\b", re.I) #: Test hook: exit right after the Nth send, before its outcome is recorded. CRASH_ENV = "OPENADAPT_TX_CRASH_AFTER_SEND" @@ -254,6 +260,79 @@ def _line( # -- plan ---------------------------------------------------------------------- +def _counts(diff: Optional[Mapping[str, Any]]) -> Optional[dict[str, Any]]: + """A staged diff as counts per table (what plan.json may hold).""" + if not diff: + return None + out: dict[str, dict[str, int]] = {} + for what in ("added", "removed"): + for rid in diff[what]: + t = out.setdefault(rid.split("/", 1)[0], {"added": 0, "changed": 0, "removed": 0}) + t[what] += 1 + for rid in diff["changed"]: + t = out.setdefault(rid.split("/", 1)[0], {"added": 0, "changed": 0, "removed": 0}) + t["changed"] += 1 + return out + + +def _row_anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], rows: Mapping[int, Mapping[str, Any]]) -> list[dict[str, Any]]: + """Blast-radius and row-value rules, from the staged transaction's rows.""" + found = [] + touched = sum( + len(d["added"]) + len(d["removed"]) + len(d["changed"]) + for w in writes + if (d := w.get("staged_diff")) + ) + for rule in spec.anomalies: + if rule.max_rows is not None and touched > rule.max_rows: + found.append({"label": rule.label, "write": None, "detail": "rows", "value": touched}) + if rule.table and rule.column: + hits = sum( + 1 + for n, before in rows.items() + for rid, row in before.items() + if rid.split("/", 1)[0] == rule.table and same(row.get(rule.column), rule.equals) + ) + if hits: + found.append({"label": rule.label, "write": None, "detail": f"{rule.table}.{rule.column}", "value": hits}) + for n, w in enumerate(writes): + if w.get("ddl"): + found.append({"label": "schema change: no generated undo", "write": n, "detail": "ddl"}) + return found + + +def _row_digests(adapter: Any, rid: str, row: Mapping[str, Any]) -> dict[str, str]: + from openadapt_flow.txplan.adapters import digest as _d + + table = rid.split("/", 1)[0] + return {c: _d(v) for c, v in row.items() if not adapter._ignored(table, c)} + + +def _undo_sql(state: State, adapter: Any, w: Mapping[str, Any], entry: Any, images: Any, digest: str) -> str: + if w.get("ddl") or not images: + return "no_undo" + rids = [*images.get("after", {}), *images.get("before", {})] + current = adapter.current_digests(rids) + for rid, want in images.get("after", {}).items(): + if current.get(rid) != want: + return "changed_since_apply" + for rid in images.get("before", {}): + if rid not in images.get("after", {}) and current.get(rid) is not None: + return "changed_since_apply" # a removed row came back + state.record(w["key"], "undo_begun", plan=digest, payload=entry.payload) + try: + adapter.compensate_sql(images) + except AdapterError as exc: + state.record(w["key"], "uncertain", plan=digest, payload=entry.payload, reason=f"undo: {exc}"[:120]) + return "undo_failed" + now_ = adapter.current_digests(rids + list(images.get("added_pk", {}))) + ok = all(now_.get(r) is None for r in images.get("added_pk", {})) and all( + now_.get(r) == _row_digests(adapter, r, item["row"]) for r, item in images.get("before", {}).items() + ) + state.record(w["key"], "undone", plan=digest, payload=entry.payload, read_back=ok) + return "undone" if ok else "undo_refuted" + + def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: if not isinstance(w, Mapping): raise TxRefused("bad_write", f"write {n} is not an object") @@ -264,6 +343,22 @@ def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: op = w.get("op") if op not in OPS: raise TxRefused("bad_write", f"write {n}: op must be one of {OPS}") + if op == "sql": + if not isinstance(system, SqlSystem): + raise TxRefused("bad_write", f"write {n}: a SQL statement needs a sql system") + sql = (w.get("fields") or {}).get("sql") if isinstance(w.get("fields"), Mapping) else None + if not isinstance(sql, str) or not sql.strip(): + raise TxRefused("bad_write", f"write {n}: sql needs fields.sql") + sql = sql.strip().rstrip(";").strip() + if ";" in sql: + raise TxRefused("bad_write", f"write {n}: one statement per write") + if _READ.match(sql): + raise TxRefused("bad_write", f"write {n}: a read is not a write (use a query)") + ddl = bool(_DDL.match(sql)) + if ddl and system.dialect == "mysql": + raise TxRefused("bad_write", f"write {n}: MySQL commits DDL at once, so it can't be staged") + return {"system": system.name, "collection": "statement", "op": "sql", "id": None, + "fields": {"sql": sql}, "label": str(w.get("label") or "")[:80], "ddl": ddl} if isinstance(system, MailSystem) != (op == "send"): raise TxRefused("bad_write", f"write {n}: {op} doesn't fit a {system.kind} system") if isinstance(system, RestSystem): @@ -291,7 +386,11 @@ def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: def _anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], baselines: Sequence[Any]) -> list[dict[str, Any]]: found: list[dict[str, Any]] = [] for rule in spec.anomalies: - if rule.max_writes is not None and len(writes) > rule.max_writes: + if rule.max_writes is None and not (rule.field or rule.op or rule.clears): + continue # a row rule (max_rows, table/column): see _row_anomalies + if rule.max_writes is not None: + if len(writes) <= rule.max_writes: + continue found.append({"label": rule.label, "write": None, "detail": f"{len(writes)} writes"}) continue for n, (w, base) in enumerate(zip(writes, baselines)): @@ -345,6 +444,25 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str if not writes: raise TxRefused("empty_plan", "a plan needs at least one write") slots = _slots(writes) + # A statement's record is the set of rows it changes or removes, read from + # a first staged run: a regenerated UPDATE that touches the same rows gets + # the same key whatever its values. A statement that only inserts has no + # such identity; its slot is the table, so a second insert into it in the + # same task is a possible replay that a person must approve. + sql_idx: dict[str, list[int]] = {} + for n, w in enumerate(writes): + if w["op"] == "sql": + sql_idx.setdefault(w["system"], []).append(n) + for name, idx in sql_idx.items(): + _, pre = ctx.adapter(name).stage([writes[i] for i in idx], [None] * len(idx)) + for i, res in zip(idx, pre): + d = res["staged_diff"] + touched = sorted([*d["changed"], *d["removed"]]) + if touched: + slots[i] = "rows:" + sha256(touched)[:32] + else: + tables = sorted({r.split("/", 1)[0] for r in d["added"]}) + slots[i] = "insert:" + ",".join(tables) if tables else "noop" for w, slot in zip(writes, slots): if w["op"] in ("update", "delete"): dup = [x for x in writes if x is not w and x["system"] == w["system"] @@ -362,8 +480,12 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str for n, w in enumerate(writes): entry = state.entry(w["key"]) w["ledger"] = "free" - if entry is not None and entry.status not in ("undone", "cancelled"): + if entry is not None and entry.status not in FREE: w["ledger"] = "replay" if entry.payload == w["payload_sha256"] else "replay_mismatch" + if w["ledger"] == "replay_mismatch" and w["op"] == "sql": + # A raw statement's identity is the rows it touches, which new work + # can share: a person decides, and policy never approves it. + w["ledger"] = "possible_replay" replays.append({"write": n, "status": w["ledger"], "prior_plan": entry.plan[:12]}) baselines: list[Optional[dict]] = [] for w in writes: @@ -379,10 +501,11 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str dry_run: dict[str, str] = {} queued = 0 staged: dict[str, list[int]] = {} + staged_rows: dict[int, dict[str, Any]] = {} for n, (w, base, scope) in enumerate(zip(writes, baselines, scopes)): adapter = ctx.adapter(w["system"]) dry_run[w["system"]] = adapter.dry_run - if w["ledger"] != "free": + if w["ledger"] not in ("free", "possible_replay"): continue if isinstance(adapter, SqlAdapter): staged.setdefault(w["system"], []).append(n) @@ -393,15 +516,26 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str for name, idx in staged.items(): diff, results = ctx.adapter(name).stage([writes[i] for i in idx], [baselines[i] for i in idx]) _merge(predicted[f"{name}:*"], _staged_to_prediction(diff)) + for i, res in zip(idx, results): + if writes[i]["op"] == "sql": + writes[i]["staged_diff"] = res["staged_diff"] + writes[i]["staged_rows"] = res["rows"] + staged_rows[i] = res.get("before_rows", {}) summary: dict[str, int] = {} for w in writes: - verb = {"create": "created", "update": "updated", "delete": "deleted", "send": "queued"}[w["op"]] + verb = {"create": "created", "update": "updated", "delete": "deleted", "send": "queued", + "sql": "statements"}[w["op"]] if w["irreversible"] and w["op"] == "delete": verb = "deleted after holdback" k = f"{w['system']}.{w['collection']} {verb}" summary[k] = summary.get(k, 0) + 1 anomalies = _anomalies(spec, writes, baselines) + anomalies += _row_anomalies(spec, writes, staged_rows) for r in replays: + if r["status"] == "possible_replay": + anomalies.append( + {"label": "possible replay: this task already wrote these rows (or this table) with another statement", "write": r["write"], "detail": "possible_replay"} + ) if r["status"] == "replay_mismatch": anomalies.append( {"label": "replays an applied write with a different payload", "write": r["write"], "detail": "replay_mismatch"} @@ -413,7 +547,7 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str other = {rid.split("/", 1)[0] for rid in pred["changed"]} | set(pred["added"]) | { rid.split("/", 1)[0] for rid in pred["removed"] } - if other - declared: + if declared and other - declared: anomalies.append( {"label": "side effects in undeclared tables", "write": None, "detail": str(len(other - declared))} ) @@ -425,7 +559,10 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str "nonce": secrets.token_hex(8), "holdback_s": spec.holdback_s, "writes": [ - {k: w[k] for k in ("system", "collection", "op", "id", "slot", "key", "payload_sha256", "irreversible", "ledger")} + { + **{k: w[k] for k in ("system", "collection", "op", "id", "slot", "key", "payload_sha256", "irreversible", "ledger")}, + **({"ddl": w["ddl"], "staged_diff": _counts(w.get("staged_diff"))} if w["op"] == "sql" else {}), + } for w in writes ], "baseline_sha256": [None if b is None else sha256(b) for b in baselines], @@ -477,6 +614,8 @@ def _readback(ctx: Ctx, w: Mapping[str, Any], base: Any, result: Mapping[str, An adapter = ctx.adapter(w["system"]) if isinstance(adapter, MailAdapter): return None, None + if w["op"] == "sql": + return True, None # committed only when its own diff matched the plan rid = str(result.get("id") or w.get("id")) got = adapter.read(w["collection"], rid) if w["op"] == "delete": @@ -509,7 +648,16 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: # Every key before any send: a mismatched replay refuses the whole plan. for n, w in enumerate(writes): entry = state.entry(w["key"]) - if entry is not None and entry.status not in ("undone", "cancelled") and entry.payload != w["payload_sha256"]: + if ( + entry is not None + and entry.status not in FREE + and entry.payload != w["payload_sha256"] + and w.get("ledger") != "possible_replay" + ): + tx["blocked_double_effects"] = tx.get("blocked_double_effects", 0) + 1 + approval_peek = state.approval_record(digest) or {} + for w in writes: + if w.get("ledger") == "possible_replay" and approval_peek.get("decided_by") != "human": tx["blocked_double_effects"] = tx.get("blocked_double_effects", 0) + 1 if tx.get("blocked_double_effects"): raise refuse( @@ -537,7 +685,9 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: if stop: results.append(_line(ok=False, verified=None, irreversible=w["irreversible"], payload=payload, code="not_sent")) continue - if entry is not None and entry.status not in ("undone", "cancelled"): + if w.get("ledger") == "possible_replay" and entry is not None and entry.status == "applied": + entry = None # a person approved it as new work: a new attempt under the key + if entry is not None and entry.status not in FREE: if entry.status in ("applied", "held", "released"): tx["replays"] = tx.get("replays", 0) + 1 results.append(_line(ok=True, verified=None, irreversible=w["irreversible"], payload=payload, code="replay_not_sent")) @@ -567,6 +717,12 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: continue try: result = ctx.adapter(w["system"]).apply(w, base, key) + except Diverged: + state.record(key, "refused", plan=digest, payload=payload, reason="diverged") + stop = "diverged" + tx["diverged"] = tx.get("diverged", 0) + 1 + results.append(_line(ok=False, verified=False, irreversible=False, payload=payload, code="diverged_rolled_back")) + continue except AdapterError as exc: state.record(key, "uncertain", plan=digest, payload=payload, reason=str(exc)[:120]) stop = "send_failed" @@ -575,9 +731,12 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: sent += 1 if crash_after and sent >= crash_after: os._exit(70) + rows_image = result.pop("_images", None) state.record(key, "applied", plan=digest, payload=payload, result=result) verified, got = _readback(ctx, w, base, result) images[key] = {"result": result, "after": _norm(spec.system(w["system"]), w, got)} + if rows_image is not None: + images[key]["rows"] = rows_image results.append(_line(ok=bool(verified), verified=verified, irreversible=False, payload=payload, code="confirmed" if verified else "refuted")) after = ctx.frames(list(priv["frames"])) @@ -633,6 +792,9 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: state.record(key, "cancelled", plan=digest, payload=entry.payload) per_write[key] = "cancelled" continue + if entry.status == "cancelled": + per_write[key] = "cancelled" + continue if entry.status == "released": per_write[key] = "irreversible_released" continue @@ -644,6 +806,9 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: continue result = entry.result or {"id": w.get("id")} adapter = ctx.adapter(w["system"]) + if w["op"] == "sql": + per_write[key] = _undo_sql(state, adapter, w, entry, (images.get(key) or {}).get("rows"), digest) + continue rid = str(result.get("id") or w.get("id")) current = adapter.read(w["collection"], rid) want = (images.get(key) or {}).get("after") @@ -675,15 +840,20 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: e = state.entry(w["key"]) rid = f"{w['collection']}/{(e.result.get('id') if e else None) or w.get('id')}" own[rid] = w["key"] + counted = [k for k, v in per_write.items() if v in ("undone", "undo_refuted", "frame_differs", "changed_since_apply", "undo_failed", "unresolved")] + # Undo images name the rows a statement touched: those are the write's own. + for w in writes: + img = (images.get(w["key"]) or {}).get("rows") or {} + for rid in [*img.get("before", {}), *img.get("added_pk", {})]: + own.setdefault(rid, w["key"]) collateral = [r for r in leftover if r not in own] for r in leftover: if r in own and per_write.get(own[r]) == "undone": per_write[own[r]] = "frame_differs" - counted = [k for k, v in per_write.items() if v in ("undone", "undo_refuted", "frame_differs", "changed_since_apply", "undo_failed", "unresolved")] verified = [k for k in counted if per_write[k] == "undone" and not collateral] for w in writes: code = per_write.get(w["key"]) - if code in (None, "not_this_plan", "cancelled", "already_undone"): + if code in (None, "not_this_plan", "cancelled", "already_undone", "no_undo"): continue results.append( _line( @@ -700,6 +870,7 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: "undo_verified": len(verified), "cancelled": sum(1 for v in per_write.values() if v == "cancelled"), "irreversible_released": sum(1 for v in per_write.values() if v == "irreversible_released"), + "no_generated_undo": sum(1 for v in per_write.values() if v == "no_undo"), "collateral_changes": len(collateral), "codes": {c: sum(1 for v in per_write.values() if v == c) for c in sorted(set(per_write.values()))}, } @@ -792,6 +963,12 @@ def summary_lines(plan: Mapping[str, Any]) -> list[str]: lines.append( f" {scope}: predicted {added} added, {len(pred['changed'])} changed, {len(pred['removed'])} removed" ) + tables = _counts({"added": [f"{t}/+{i}" for t, n in pred["added"].items() for i in range(n)], + "removed": pred["removed"], "changed": pred["changed"]}) or {} + if len(tables) > 1 or scope.endswith(":*"): + for table, c in sorted(tables.items()): + parts = [f"{v} rows {k}" for k, v in c.items() if v] + lines.append(f" {table}: {', '.join(parts)}") details = plan.get("anomaly_details") or plan["anomalies"] lines.append(f" {len(details)} anomal{'y' if len(details) == 1 else 'ies'}") for a in details: diff --git a/packages/flow/openadapt_flow/txplan/proxy.py b/packages/flow/openadapt_flow/txplan/proxy.py new file mode 100644 index 0000000000..868d0fe35c --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/proxy.py @@ -0,0 +1,366 @@ +"""``openadapt proxy``: OpenAdapt holds the database credentials; the agent gets +scoped MCP tools. + + openadapt proxy --postgres "$DATABASE_URL" -- claude + openadapt proxy --sqlite app.db -- claude + openadapt proxy --sqlite app.db # serve here; approve with y / u + +The proxy serves a Model Context Protocol endpoint (streamable HTTP, JSON +responses) on ``127.0.0.1`` with a random per-run bearer token. It starts the +command with ``OPENADAPT_MCP_URL`` and ``OPENADAPT_MCP_TOKEN`` and with the +database URL and the ``PG*`` variables removed from its environment. For +``claude`` it also passes ``--mcp-config``. Each write goes through five +stages: + +1. **Pre-read**: open a transaction and read every table. +2. **Dry-run diff**: run the statement inside it, read every table again, + compute the row-level diff ("412 rows changed in users; 3 rows where + users.role = admin"), and roll back. +3. **Gate**: a plan within the blast-radius limit and with no anomaly is + approved by policy. Anything else waits for a person: ``y`` in the proxy's + terminal, or ``openadapt plan approve`` in another. Approval binds to the plan + digest and is used once. +4. **Execute once**: under the idempotency ledger. The statement commits only + when its diff, read inside the same transaction, is exactly the planned + diff. Otherwise it is rolled back. +5. **Read back and undo**: the frame is read again and compared. The undo + images (before rows, added keys) give a generated compensating undo that is + verified by read-back. Each stage writes a signed receipt. + +The agent never receives write credentials in its environment. An agent that +runs as the same OS user with a shell can still find credentials the user +keeps elsewhere (a ``.env`` file, ``~/.pgpass``). For a hard boundary, give +the proxy credentials the agent's user can't read. +""" + +from __future__ import annotations + +import hmac +import json +import os +import secrets +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.txplan import engine +from openadapt_flow.txplan.adapters import AdapterError, SqlAdapter, tag +from openadapt_flow.txplan.engine import Ctx, TxRefused +from openadapt_flow.txplan.spec import Anomaly, SqlSystem, TxSpec +from openadapt_flow.txplan.state import State, StateError, sha256 + +PROTOCOL = "2025-06-18" +PATH = "/mcp" +MAX_QUERY_ROWS = 200 +#: Environment variables that carry database credentials, removed from the child. +SCRUB = ("DATABASE_URL", "PGPASSWORD", "PGPASSFILE", "PGSERVICE", "PGSERVICEFILE", "PGHOST", + "PGUSER", "PGDATABASE", "PGPORT", "MYSQL_PWD") + + +def child_environment(environ: Mapping[str, str], secrets_: Sequence[str]) -> dict[str, str]: + """The command's environment: credentials and their copies removed.""" + out = {} + for k, v in environ.items(): + if k in SCRUB or any(s and s in v for s in secrets_): + continue + out[k] = v + return out + + +def sql_spec(*, postgres: Optional[str] = None, sqlite: Optional[str] = None, + max_rows: int = 0, flags: Sequence[str] = ()) -> TxSpec: + """A one-system tx spec for a database URL or a SQLite file.""" + if bool(postgres) == bool(sqlite): + raise ValueError("give exactly one of --postgres or --sqlite") + if postgres: + system = SqlSystem(name="db", kind="sql", dialect="postgresql", driver="psycopg", + connect_args={"conninfo": postgres}) + else: + system = SqlSystem(name="db", kind="sql", dialect="sqlite", path=str(Path(str(sqlite)).resolve())) + anomalies = [Anomaly(label="more rows than the auto-approve limit", max_rows=max_rows)] + for flag in flags: + target, _, value = flag.partition("=") + table, _, column = target.partition(".") + if not (table and column and value): + raise ValueError(f"--flag {flag!r}: use table.column=value") + anomalies.append(Anomaly(label=f"rows where {table}.{column} = {value}", table=table, + column=column, equals=value)) + return TxSpec(schema_version="openadapt.tx/v1", holdback_s=0, anomalies=anomalies, systems=[system]) + + +class Proxy: + """The tools, over one database, for one task (this proxy session).""" + + def __init__(self, ctx: Ctx, *, task: str, system: str = "db", interactive: bool = False) -> None: + self.ctx = ctx + self.task = task + self.system = system + self.interactive = interactive + self.lock = threading.Lock() + self.pending: list[str] = [] + self.applied: list[str] = [] + + @property + def adapter(self) -> SqlAdapter: + return self.ctx.adapter(self.system) + + # tools ------------------------------------------------------------------- + + def query(self, sql: str) -> dict[str, Any]: + """A read, in a transaction that is always rolled back.""" + con = self.adapter.connect() + try: + cur = con.cursor() + self.adapter._begin(cur) + if self.adapter.system.dialect == "postgresql": + cur.execute("SET TRANSACTION READ ONLY") + try: + cur.execute(sql) + cols = [str(d[0]) for d in (cur.description or [])] + rows = cur.fetchmany(MAX_QUERY_ROWS + 1) if cols else [] + finally: + con.rollback() + finally: + con.close() + return { + "columns": cols, + "rows": [[tag(v) for v in r] for r in rows[:MAX_QUERY_ROWS]], + "truncated": len(rows) > MAX_QUERY_ROWS, + } + + def preview(self, sql: str) -> dict[str, Any]: + with self.lock: + plan = engine.make_plan(self.ctx, self.task, [{"system": self.system, "op": "sql", "fields": {"sql": sql}}]) + digest = plan["digest"] + w = plan["writes"][0] + counts = w.get("staged_diff") or {} + auto = not plan["anomalies"] and w["ledger"] == "free" and not w.get("ddl") + if auto: + engine.approve_plan(self.ctx.state, digest, approver="policy", decided_by="automation") + else: + self.pending.append(digest) + text = "\n".join(engine.summary_lines(plan)) + if self.interactive and not auto: + print("\n" + text + "\n press y to approve, n to decline", file=sys.stderr, flush=True) + return { + "plan": digest[:16], + "tables": counts, + "ledger": w["ledger"], + "anomalies": [a["label"] for a in plan["anomaly_details"]], + "approval": "approved by policy" if auto else ( + "waiting for a person (y in the proxy terminal, or `openadapt plan approve " + f"{digest[:16]}`)" + ), + "summary": text, + } + + def apply(self, plan: str) -> dict[str, Any]: + with self.lock: + digest = self.ctx.state.find_plan(plan) + out = engine.apply_plan(self.ctx, digest) + if out["outcome"] in ("VERIFIED", "COMPLETED_UNVERIFIED"): + self.applied.append(digest) + return {"outcome": out["outcome"], "tx": out["tx"], "receipt": out["run_dir"]} + + def undo(self, plan: str) -> dict[str, Any]: + with self.lock: + digest = self.ctx.state.find_plan(plan) + out = engine.undo_plan(self.ctx, digest) + return {"outcome": out["outcome"], "tx": out["tx"], "receipt": out["run_dir"]} + + def call(self, name: str, args: Mapping[str, Any]) -> tuple[str, bool]: + try: + if name == "sql_query": + got: Any = self.query(str(args["sql"])) + elif name == "sql_preview": + got = self.preview(str(args["sql"])) + elif name == "sql_apply": + got = self.apply(str(args["plan"])) + elif name == "sql_undo": + got = self.undo(str(args["plan"])) + else: + return f"unknown tool {name}", True + except TxRefused as exc: + return json.dumps({"refused": exc.code, "detail": exc.detail}), True + except (AdapterError, StateError, KeyError, ValueError) as exc: + return json.dumps({"error": type(exc).__name__, "detail": str(exc)[:300]}), True + except Exception as exc: # noqa: BLE001 - a database error is the tool's answer + return json.dumps({"error": type(exc).__name__, "detail": str(exc)[:300]}), True + return json.dumps(got, default=str), False + + # the person's keys --------------------------------------------------------- + + def key(self, ch: str) -> str: + """``y`` approves the oldest waiting plan, ``n`` declines it, ``u`` undoes + the last applied one.""" + with self.lock: + if ch == "y" and self.pending: + digest = self.pending.pop(0) + engine.approve_plan(self.ctx.state, digest, approver=os.environ.get("USER", "person"), + decided_by="human") + return f"approved {digest[:16]}" + if ch == "n" and self.pending: + return f"declined {self.pending.pop(0)[:16]}" + if ch == "u" and self.applied: + digest = self.applied.pop() + out = engine.undo_plan(self.ctx, digest) + return f"undo {digest[:16]}: {out['outcome']}" + return "nothing to do" + + +TOOLS = [ + {"name": "sql_query", "description": "Run a read-only SQL query (rolled back; at most 200 rows).", + "inputSchema": {"type": "object", "properties": {"sql": {"type": "string"}}, "required": ["sql"]}}, + {"name": "sql_preview", "description": ( + "Dry-run one SQL write statement: OpenAdapt runs it in a transaction, returns the exact " + "row-level diff and a plan id, and rolls back. Small plans are approved by policy; others " + "wait for a person."), + "inputSchema": {"type": "object", "properties": {"sql": {"type": "string"}}, "required": ["sql"]}}, + {"name": "sql_apply", "description": "Apply an approved plan once; it commits only if the diff is the planned diff.", + "inputSchema": {"type": "object", "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, + {"name": "sql_undo", "description": "Undo an applied plan and verify it by reading every table back.", + "inputSchema": {"type": "object", "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, +] + + +class McpServer: + """A minimal streamable-HTTP MCP server: JSON responses, one bearer token.""" + + def __init__(self, proxy: Proxy, *, port: int = 0) -> None: + self.proxy = proxy + self.token = secrets.token_urlsafe(32) + outer = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *a: Any) -> None: # no access log: never log the token + pass + + def _send(self, code: int, body: Any = None) -> None: + data = b"" if body is None else json.dumps(body).encode() + self.send_response(code) + if body is not None: + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _authorized(self) -> bool: + given = self.headers.get("Authorization", "") + return self.path.split("?")[0] == PATH and hmac.compare_digest( + given.encode(), f"Bearer {outer.token}".encode() + ) + + def do_GET(self) -> None: # noqa: N802 + self._send(405 if self._authorized() else 401) + + def do_DELETE(self) -> None: # noqa: N802 + self._send(405 if self._authorized() else 401) + + def do_POST(self) -> None: # noqa: N802 + if self.path.split("?")[0] != PATH: + return self._send(404) + if not self._authorized(): + return self._send(401) + try: + msg = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0))) + except ValueError: + return self._send(400, {"jsonrpc": "2.0", "id": None, + "error": {"code": -32700, "message": "parse error"}}) + if isinstance(msg, list): + replies = [r for r in (outer.handle(m) for m in msg) if r is not None] + return self._send(200, replies) if replies else self._send(202) + reply = outer.handle(msg) + return self._send(202) if reply is None else self._send(200, reply) + + self.http = ThreadingHTTPServer(("127.0.0.1", port), H) + self.url = f"http://127.0.0.1:{self.http.server_address[1]}{PATH}" + + def handle(self, msg: Mapping[str, Any]) -> Optional[dict[str, Any]]: + mid = msg.get("id") + method = msg.get("method") + if mid is None: + return None # a notification + if method == "initialize": + asked = (msg.get("params") or {}).get("protocolVersion") or PROTOCOL + result: Any = {"protocolVersion": asked, "capabilities": {"tools": {}}, + "serverInfo": {"name": "openadapt-proxy", "version": "1"}} + elif method == "ping": + result = {} + elif method == "tools/list": + result = {"tools": TOOLS} + elif method == "tools/call": + params = msg.get("params") or {} + text, is_error = self.proxy.call(str(params.get("name")), params.get("arguments") or {}) + result = {"content": [{"type": "text", "text": text}], "isError": is_error} + else: + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "method not found"}} + return {"jsonrpc": "2.0", "id": mid, "result": result} + + def start(self) -> None: + threading.Thread(target=self.http.serve_forever, daemon=True).start() + + def stop(self) -> None: + self.http.shutdown() + self.http.server_close() + + +def mcp_config(server: McpServer, folder: Path) -> Path: + path = folder / "openadapt-mcp.json" + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + json.dump({"mcpServers": {"openadapt": { + "type": "http", "url": server.url, + "headers": {"Authorization": f"Bearer {server.token}"}, + }}}, f) + return path + + +def run(argv_command: Sequence[str], *, spec: TxSpec, state: State, task: str, + secrets_: Sequence[str], port: int = 0) -> int: + ctx = Ctx(spec=spec, state=state) + proxy = Proxy(ctx, task=task, interactive=not argv_command) + server = McpServer(proxy, port=port) + server.start() + tmp = Path(tempfile.mkdtemp(prefix="openadapt-proxy-")) + try: + config = mcp_config(server, tmp) + print(f"openadapt proxy: MCP endpoint {server.url} (task {task})", file=sys.stderr, flush=True) + if not argv_command: + print(f"MCP config for your agent: {config}\n" + "keys: y approve the waiting plan, n decline it, u undo the last applied plan, q quit", + file=sys.stderr, flush=True) + for line in sys.stdin: + ch = line.strip()[:1].lower() + if ch == "q": + return 0 + print(proxy.key(ch), file=sys.stderr, flush=True) + return 0 + env = child_environment(os.environ, secrets_) + env.update({"OPENADAPT_MCP_URL": server.url, "OPENADAPT_MCP_TOKEN": server.token, + "OPENADAPT_MCP_CONFIG": str(config), "OPENADAPT_TASK": task}) + cmd = list(argv_command) + if Path(cmd[0]).name == "claude" and "--mcp-config" not in cmd: + cmd[1:1] = ["--mcp-config", str(config)] + exe = shutil.which(cmd[0], path=env.get("PATH")) + if exe is None: + print(f"openadapt proxy: {cmd[0]} is not on PATH", file=sys.stderr) + return 127 + child = subprocess.Popen([exe, *cmd[1:]], env=env) + try: + return child.wait() + except KeyboardInterrupt: + child.send_signal(signal.SIGINT) + return child.wait() + finally: + server.stop() + shutil.rmtree(tmp, ignore_errors=True) + + +def default_task() -> str: + return "proxy-" + sha256([os.getpid(), secrets.token_hex(8)])[:16] diff --git a/packages/flow/openadapt_flow/txplan/proxy_cli.py b/packages/flow/openadapt_flow/txplan/proxy_cli.py new file mode 100644 index 0000000000..f6b38c1c4f --- /dev/null +++ b/packages/flow/openadapt_flow/txplan/proxy_cli.py @@ -0,0 +1,74 @@ +"""``openadapt proxy``: hold the database credentials and give the agent scoped tools. + + openadapt proxy --postgres "$DATABASE_URL" -- claude + openadapt proxy --sqlite app.db --auto-approve-max-rows 10 -- claude + openadapt proxy --sqlite app.db # serve here; y approve, u undo + +See ``openadapt_flow.txplan.proxy`` and ``docs/TRANSACTIONS.md``. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path +from typing import Optional, Sequence + + +def _parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="openadapt proxy", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) + _fill(p) + return p + + +def _fill(p: argparse.ArgumentParser) -> None: + db = p.add_mutually_exclusive_group(required=True) + db.add_argument("--postgres", metavar="URL", help="a PostgreSQL URL (needs the psycopg package)") + db.add_argument("--sqlite", metavar="PATH", help="a SQLite file") + p.add_argument("--task", help="the task these writes belong to (default: one per proxy run)") + p.add_argument("--auto-approve-max-rows", type=int, default=0, metavar="N", + help="approve by policy a plan that touches at most N rows and has no anomaly (default 0)") + p.add_argument("--flag", action="append", default=[], metavar="TABLE.COLUMN=VALUE", + help="show rows the statement touches where TABLE.COLUMN = VALUE (repeatable)") + p.add_argument("--state", help="the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)") + p.add_argument("--port", type=int, default=0, help="the MCP port on 127.0.0.1 (default: random)") + + +def add_parser(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser("proxy", help=( + "Hold the database credentials; give the agent MCP tools that preview, apply " + "once and undo each write"), description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) + _fill(p) + p.add_argument("command", nargs=argparse.REMAINDER, help="-- COMMAND ... (the agent)") + p.set_defaults(func=lambda a: _run(a, [x for x in a.command if x != "--"][: None])) + + +def _run(args: argparse.Namespace, command: Sequence[str]) -> int: + from openadapt_flow.txplan.proxy import default_task, run, sql_spec + from openadapt_flow.txplan.state import State + + try: + spec = sql_spec(postgres=args.postgres, sqlite=args.sqlite, + max_rows=args.auto_approve_max_rows, flags=args.flag) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + state = State(Path(args.state) if args.state else None) + return run(command, spec=spec, state=state, task=args.task or default_task(), + secrets_=[args.postgres] if args.postgres else [], port=args.port) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + command: list[str] = [] + if "--" in argv: + i = argv.index("--") + argv, command = argv[:i], argv[i + 1 :] + args = _parser().parse_args(argv) + return _run(args, command) + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/packages/flow/openadapt_flow/txplan/spec.py b/packages/flow/openadapt_flow/txplan/spec.py index 0b9f38f95c..69cdd6cc3a 100644 --- a/packages/flow/openadapt_flow/txplan/spec.py +++ b/packages/flow/openadapt_flow/txplan/spec.py @@ -158,7 +158,7 @@ class SqlSystem(_Closed): connect_args: dict[str, object] = Field(default_factory=dict) password_env: Optional[str] = None #: The tables a plan may write, each with its key column. - tables: dict[str, str] = Field(min_length=1) + tables: dict[str, str] = Field(default_factory=dict) #: Tables whose rows the frame doesn't compare (a session table, a cache). #: Declare them before a measured run. frame_ignore_tables: list[str] = Field(default_factory=list) @@ -211,16 +211,25 @@ class Anomaly(_Closed): label: str = Field(min_length=1, max_length=60) field: Optional[str] = None above: Optional[float] = None - op: Optional[Literal["create", "update", "delete", "send"]] = None + op: Optional[Literal["create", "update", "delete", "send", "sql"]] = None #: A field set from a non-empty value to an empty one. clears: bool = False max_writes: Optional[int] = Field(default=None, ge=1) + #: SQL: more rows than this touched in total (the blast radius). + max_rows: Optional[int] = Field(default=None, ge=0) + #: SQL: rows of ``table`` whose ``column`` equals ``equals`` before the + #: statement ("3 admins"), from the staged transaction. + table: Optional[str] = None + column: Optional[str] = None + equals: Optional[object] = None @model_validator(mode="after") def _check(self) -> "Anomaly": if self.above is not None and self.field is None: raise ValueError(f"anomaly {self.label}: above needs field") - if not any([self.field, self.op, self.max_writes, self.clears]): + if (self.table is None) != (self.column is None): + raise ValueError(f"anomaly {self.label}: table and column go together") + if not any([self.field, self.op, self.max_writes, self.clears, self.max_rows is not None, self.table]): raise ValueError(f"anomaly {self.label}: says nothing to check") return self diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 507794263e..479ab55a3d 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -462,3 +462,130 @@ def test_cli_create_show_approve_apply(tmp_path: Path, capsys: pytest.CaptureFix assert main(["approve", digest, "--automation"]) == 0 assert main(["apply", "--tx", str(spec), digest]) == 0 assert main(["apply", "--tx", str(spec), digest]) == 3 + + +# -- raw SQL statements and the credential-holding proxy ------------------------ + + +def _users(path: Path, n: int = 500) -> Path: + con = sqlite3.connect(path) + con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT, active INTEGER)") + con.execute("CREATE TABLE logins (id INTEGER PRIMARY KEY, user_id INTEGER)") + for i in range(1, n + 1): + con.execute("INSERT INTO users VALUES (?, ?, ?, 1)", (i, f"user {i}", "admin" if i in (3, 30, 300) else "member")) + con.commit() + con.close() + return path + + +def _proxy(db: Path, **kw: Any): # type: ignore[no-untyped-def] + from openadapt_flow.txplan.proxy import Proxy, sql_spec + + spec = sql_spec(sqlite=str(db), flags=["users.role=admin"], **kw) + return Proxy(Ctx(spec=spec, state=State()), task="T-proxy") + + +def _all(db: Path) -> list[tuple]: + con = sqlite3.connect(db) + try: + return sorted(con.execute("SELECT * FROM users").fetchall()) + finally: + con.close() + + +def test_proxy_bulk_update_shows_exact_diff_then_applies_once_and_undoes(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite") + before = _all(db) + proxy = _proxy(db) + got = proxy.preview("UPDATE users SET active = 0 WHERE id <= 412") + assert got["tables"] == {"users": {"added": 0, "changed": 412, "removed": 0}} + assert "rows where users.role = admin" in got["anomalies"] + assert "users: 412 rows changed" in got["summary"] and "= admin: users.role = 3" in got["summary"] + assert got["approval"].startswith("waiting for a person") and _all(db) == before + with pytest.raises(TxRefused): + proxy.apply(got["plan"]) + assert proxy.key("y").startswith("approved") + out = proxy.apply(got["plan"]) + assert out["outcome"] == "VERIFIED" and out["tx"]["missed_effects"] == 0 + con = sqlite3.connect(db) + assert con.execute("SELECT count(*) FROM users WHERE active = 0").fetchone()[0] == 412 + con.close() + undone = proxy.undo(got["plan"]) + assert undone["outcome"] == "ROLLED_BACK", undone + assert _all(db) == before + + +def test_proxy_insert_and_delete_round_trip_and_policy_auto_approve(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=20) + before = _all(db) + proxy = _proxy(db, max_rows=5) + a = proxy.preview("INSERT INTO users (name, role, active) VALUES ('new', 'member', 1)") + assert a["approval"] == "approved by policy" + assert proxy.apply(a["plan"])["outcome"] == "VERIFIED" + b = proxy.preview("DELETE FROM users WHERE id IN (4, 5)") + assert b["approval"] == "approved by policy" + assert proxy.apply(b["plan"])["outcome"] == "VERIFIED" + assert proxy.undo(b["plan"])["outcome"] == "ROLLED_BACK" + assert proxy.undo(a["plan"])["outcome"] == "ROLLED_BACK" + assert _all(db) == before + + +def test_proxy_commits_only_the_planned_diff(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=20) + proxy = _proxy(db, max_rows=100) + got = proxy.preview("UPDATE users SET name = 'x' WHERE active = 1") + con = sqlite3.connect(db) # another writer between the dry run and apply + con.execute("UPDATE users SET active = 0 WHERE id = 7") + con.commit() + con.close() + snapshot = _all(db) + with pytest.raises(TxRefused) as exc: + proxy.apply(got["plan"]) + assert exc.value.code == "plan_stale" and _all(db) == snapshot + + +def test_proxy_regenerated_statement_after_restore_is_held_not_applied(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=50) + proxy = _proxy(db, max_rows=100) + a = proxy.preview("UPDATE users SET name = 'refund 100' WHERE id = 9") + proxy.apply(a["plan"]) + # Restored agent regenerates the same intent with a different payload. + b = proxy.preview("UPDATE users SET name = 'refund 100 (ref 2)' WHERE id = 9") + assert b["ledger"] == "possible_replay" and b["approval"].startswith("waiting") + with pytest.raises(TxRefused) as exc: + proxy.apply(b["plan"]) + assert exc.value.code in ("not_approved", "replay_mismatch") + con = sqlite3.connect(db) + assert con.execute("SELECT name FROM users WHERE id = 9").fetchone()[0] == "refund 100" + con.close() + # The identical statement now changes nothing: its dry run is empty. + c = proxy.preview("UPDATE users SET name = 'refund 100' WHERE id = 9") + assert c["tables"] == {} + + +def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child(tmp_path: Path) -> None: + import httpx + + from openadapt_flow.txplan.proxy import McpServer, child_environment + + db = _users(tmp_path / "app.sqlite", n=5) + server = McpServer(_proxy(db, max_rows=10)) + server.start() + try: + assert httpx.post(server.url, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}).status_code == 401 + h = {"Authorization": f"Bearer {server.token}"} + init = httpx.post(server.url, headers=h, json={"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18"}}).json() + assert init["result"]["capabilities"] == {"tools": {}} + names = [t["name"] for t in httpx.post(server.url, headers=h, json={ + "jsonrpc": "2.0", "id": 2, "method": "tools/list"}).json()["result"]["tools"]] + assert names == ["sql_query", "sql_preview", "sql_apply", "sql_undo"] + call = httpx.post(server.url, headers=h, json={"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { + "name": "sql_preview", "arguments": {"sql": "UPDATE users SET active = 0 WHERE id = 2"}}}).json() + body = json.loads(call["result"]["content"][0]["text"]) + assert body["approval"] == "approved by policy" + finally: + server.stop() + env = child_environment({"DATABASE_URL": "postgres://u:pw@h/db", "X": "postgres://u:pw@h/db", + "PGPASSWORD": "pw", "PATH": "/bin"}, ["postgres://u:pw@h/db"]) + assert env == {"PATH": "/bin"} From 8d3bc363e9fb14141ba378590afa68849a8e1923 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:49:20 -0500 Subject: [PATCH 03/21] test(plan): lab harnesses for Vikunja, Mailpit, Dolibarr and PostgreSQL; setup-time script --- .../benchmark/ext_tx/first_diff_client.py | 18 ++ packages/flow/benchmark/ext_tx/proxy_lab.py | 240 ++++++++++++++++++ packages/flow/benchmark/ext_tx/run.py | 10 +- packages/flow/benchmark/ext_tx/setup_time.sh | 26 ++ .../flow/openadapt_flow/txplan/adapters.py | 79 ++++-- packages/flow/openadapt_flow/txplan/engine.py | 2 +- 6 files changed, 346 insertions(+), 29 deletions(-) create mode 100644 packages/flow/benchmark/ext_tx/first_diff_client.py create mode 100644 packages/flow/benchmark/ext_tx/proxy_lab.py create mode 100755 packages/flow/benchmark/ext_tx/setup_time.sh diff --git a/packages/flow/benchmark/ext_tx/first_diff_client.py b/packages/flow/benchmark/ext_tx/first_diff_client.py new file mode 100644 index 0000000000..4898c1094d --- /dev/null +++ b/packages/flow/benchmark/ext_tx/first_diff_client.py @@ -0,0 +1,18 @@ +"""A stand-in agent for the setup-time measurement: it gets only the MCP URL +and token from ``openadapt proxy``, asks for a dry run of a bulk UPDATE and +prints the diff. It has no database credentials.""" + +import json +import os + +import httpx + +url, token = os.environ["OPENADAPT_MCP_URL"], os.environ["OPENADAPT_MCP_TOKEN"] +assert "DATABASE_URL" not in os.environ and "PGPASSWORD" not in os.environ +h = {"Authorization": f"Bearer {token}", "Accept": "application/json, text/event-stream"} +httpx.post(url, headers=h, json={"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "lab", "version": "1"}}}).raise_for_status() +got = httpx.post(url, headers=h, json={"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { + "name": "sql_preview", "arguments": {"sql": "UPDATE users SET active = false WHERE id <= 412"}}}).json() +print(json.loads(got["result"]["content"][0]["text"])["summary"]) diff --git a/packages/flow/benchmark/ext_tx/proxy_lab.py b/packages/flow/benchmark/ext_tx/proxy_lab.py new file mode 100644 index 0000000000..327a481626 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/proxy_lab.py @@ -0,0 +1,240 @@ +"""Lab proof for ``openadapt proxy`` on PostgreSQL 16 (zenbook WSL). + + remote-run.sh uv run --no-sync --with 'psycopg[binary]' --with mcp \\ + python benchmark/ext_tx/proxy_lab.py --out benchmark/ext_tx/results/proxy.json + +A synthetic schema (users, orders with ON DELETE CASCADE, a table with no +primary key) in its own database. Each statement goes through the proxy's +tools: preview (dry run in a rolled-back transaction), approval by key +``y``, apply once, undo. After each undo the whole database is compared with +its state before the statement. An independent read-back +(``openadapt_flow.verifier.capture_database``/``diff_database``) checks the +dry run's per-table counts after each apply. One session runs over the real +MCP client SDK against the HTTP endpoint. Counts only in the output. +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import os +import random +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +DB = os.environ.get("LAB_PG_DB", "oa_ext_tx") +CONNINFO = f"dbname={DB} host=/var/run/postgresql" + + +def log(msg: str) -> None: + print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) + + +def psql(sql: str, db: str = DB) -> str: + return subprocess.run(["psql", "-qAt", "-d", db, "-c", sql], check=True, capture_output=True, text=True).stdout + + +def reset() -> None: + subprocess.run(["dropdb", "--if-exists", DB], check=True) + subprocess.run(["createdb", DB], check=True) + psql(""" + CREATE TABLE users (id serial PRIMARY KEY, name text NOT NULL, role text NOT NULL, + active boolean NOT NULL DEFAULT true, balance numeric(12,2) NOT NULL DEFAULT 0, + updated_at timestamptz NOT NULL DEFAULT now()); + CREATE TABLE orders (id serial PRIMARY KEY, user_id int NOT NULL REFERENCES users(id) ON DELETE CASCADE, + total numeric(12,2) NOT NULL, placed date NOT NULL DEFAULT '2026-11-01'); + CREATE TABLE events (user_id int, kind text); + INSERT INTO users (name, role, balance) + SELECT 'user ' || g, CASE WHEN g % 97 = 0 THEN 'admin' ELSE 'member' END, g * 1.5 + FROM generate_series(1, 600) g; + INSERT INTO orders (user_id, total) SELECT 1 + (g % 600), (g % 50) + 0.99 FROM generate_series(1, 1500) g; + INSERT INTO events SELECT g, 'seed' FROM generate_series(1, 20) g; + """) + + +def dump() -> str: + return psql("SELECT 'u', md5(string_agg(t::text, ',' ORDER BY id)) FROM users t " + "UNION ALL SELECT 'o', md5(string_agg(t::text, ',' ORDER BY id)) FROM orders t " + "UNION ALL SELECT 'e', md5(string_agg(t::text, ',' ORDER BY user_id, kind)) FROM events t") + + +def statements(rng: random.Random, n: int) -> list[tuple[str, str]]: + out = [] + for i in range(n): + k = i % 8 + a = rng.randint(1, 550) + if k == 0: + out.append(("bulk_update", f"UPDATE users SET active = false WHERE id BETWEEN {a} AND {a + rng.randint(5, 60)}")) + elif k == 1: + out.append(("expr_update", f"UPDATE users SET balance = balance * 1.1 WHERE role = 'member' AND id % {rng.randint(7, 40)} = 0")) + elif k == 2: + out.append(("insert_values", f"INSERT INTO users (name, role) VALUES ('lab {i}a', 'member'), ('lab {i}b', 'member')")) + elif k == 3: + out.append(("insert_select", f"INSERT INTO orders (user_id, total) SELECT id, 1.00 FROM users WHERE id BETWEEN {a} AND {a + 4}")) + elif k == 4: + out.append(("delete_where", f"DELETE FROM orders WHERE total < {rng.randint(2, 6)} AND user_id BETWEEN {a} AND {a + 40}")) + elif k == 5: + out.append(("delete_cascade", f"DELETE FROM users WHERE id = {a}")) + elif k == 6: + out.append(("update_join", f"UPDATE orders SET total = 0 WHERE user_id IN (SELECT id FROM users WHERE id BETWEEN {a} AND {a + 3})")) + else: + out.append(("migration_like", f"UPDATE users SET name = upper(name) WHERE id % {rng.randint(50, 90)} = 0")) + return out + + +def independent_counts(before: Any, after: Any) -> dict[str, dict[str, int]]: + from openadapt_flow.verifier import diff_database + + out = {} + for table, d in diff_database(before, after).items(): + n = (lambda v: v if isinstance(v, int) else len(v)) + out[table] = {"added": n(d.added), "changed": n(d.changed), "removed": n(d.removed)} + return out + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--n", type=int, default=120) + ap.add_argument("--seed", type=int, default=20261121) + args = ap.parse_args() + from openadapt_flow.txplan.engine import Ctx + from openadapt_flow.txplan.proxy import McpServer, Proxy, sql_spec + from openadapt_flow.txplan.state import State + from openadapt_flow.verifier import capture_database + + work = Path(tempfile.mkdtemp(prefix="proxy-lab-")) + os.environ["OPENADAPT_TX_STATE"] = str(work / "state") + os.environ.setdefault("OPENADAPT_SEAL_HOME", str(work / "seal")) + reset() + spec = sql_spec(postgres=CONNINFO, flags=["users.role=admin"], max_rows=0) + proxy = Proxy(Ctx(spec=spec, state=State()), task=f"lab-proxy-{int(time.time())}") + read = {"sql_driver": "psycopg", "sql_connect_args": {"conninfo": CONNINFO}} + key = os.urandom(32) + rng = random.Random(args.seed) + rows: list[dict[str, Any]] = [] + for kind, sql in statements(rng, args.n): + start = dump() + t0 = time.monotonic() + prev = proxy.preview(sql) + t_preview = time.monotonic() - t0 + assert dump() == start, "the dry run changed the database" + proxy.key("y") + snap0 = capture_database(read, "postgresql", key=key) + applied = proxy.apply(prev["plan"]) + snap1 = capture_database(read, "postgresql", key=key, before=snap0) + indep = independent_counts(snap0, snap1) + predicted = {t: c for t, c in (prev["tables"] or {}).items()} + agree = {t: c for t, c in indep.items() if any(c.values())} == { + t: c for t, c in predicted.items() if any(c.values())} + undone = proxy.undo(prev["plan"]) + back = dump() == start + rows.append({ + "kind": kind, "rows_touched": sum(sum(c.values()) for c in predicted.values()), + "tables": sorted(predicted), "anomalies": len(prev["anomalies"]), + "apply": applied["outcome"], "missed": applied["tx"].get("missed_effects"), + "false": applied["tx"].get("false_diffs"), "independent_agrees": agree, + "undo": undone["outcome"], "undo_verified": undone["tx"]["undo_verified"], + "undo_supported": undone["tx"]["undo_supported"], "db_back_to_start": back, + "preview_s": round(t_preview, 3), + }) + if not (agree and back and undone["outcome"] == "ROLLED_BACK"): + log(f"{kind}: apply {applied['outcome']} agree {agree} undo {undone['outcome']} back {back} {undone['tx'].get('codes')} pred {predicted} indep {indep}") + log(f"{len(rows)} statements done") + + # ACRFence on the proxy: a regenerated statement for the same rows after a restore. + acr = {"trials": 0, "held_not_applied": 0, "double_effects_through": 0, "control_duplicates": 0} + for t in range(20): + a = 100 + t * 7 + before = psql(f"SELECT balance FROM users WHERE id = {a}").strip() + p1 = proxy.preview(f"UPDATE users SET balance = balance + 100 WHERE id = {a}") + proxy.key("y") + proxy.apply(p1["plan"]) + p2 = proxy.preview(f"UPDATE users SET balance = balance + 100.00 WHERE id = {a} AND active IS NOT NULL") + try: + out = proxy.apply(p2["plan"]) + applied_twice = out["outcome"] == "VERIFIED" + except Exception: # noqa: BLE001 - refused + applied_twice = False + proxy.pending.clear() + after = psql(f"SELECT balance - {before} FROM users WHERE id = {a}").strip() + acr["trials"] += 1 + acr["held_not_applied"] += int(p2["ledger"] == "possible_replay" and not applied_twice) + acr["double_effects_through"] += int(float(after) > 100.0) + # Control: the same two statements straight to the database. + psql(f"UPDATE users SET balance = balance + 100 WHERE id = {a + 1}") + psql(f"UPDATE users SET balance = balance + 100.00 WHERE id = {a + 1} AND active IS NOT NULL") + acr["control_duplicates"] += 1 + log(f"acrfence {acr}") + + # Trigger probe (not in the supported set): the dry run must show the trigger's rows. + psql("CREATE TABLE audit (id serial PRIMARY KEY, user_id int);" + "CREATE FUNCTION f_audit() RETURNS trigger AS $$ BEGIN INSERT INTO audit (user_id) VALUES (NEW.id); RETURN NEW; END $$ LANGUAGE plpgsql;" + "CREATE TRIGGER t_audit AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f_audit();") + tp = proxy.preview("UPDATE users SET name = name || '!' WHERE id BETWEEN 10 AND 14") + proxy.key("y") + ta = proxy.apply(tp["plan"]) + tu = proxy.undo(tp["plan"]) + trigger = {"predicted_tables": tp["tables"], "apply": ta["outcome"], "missed": ta["tx"].get("missed_effects"), + "undo": tu["outcome"], "collateral": tu["tx"]["collateral_changes"]} + log(f"trigger {trigger}") + psql("DROP TRIGGER t_audit ON users; DROP TABLE audit; DROP FUNCTION f_audit();") + + # One session over the real MCP client SDK. + mcp_ok = asyncio.run(mcp_session(McpServer, proxy)) + log(f"mcp {mcp_ok}") + + sup = sum(r["undo_supported"] for r in rows) + ver = sum(r["undo_verified"] for r in rows) + summary = { + "statements": len(rows), + "rows_touched": sum(r["rows_touched"] for r in rows), + "by_kind": {k: sum(1 for r in rows if r["kind"] == k) for k in sorted({r["kind"] for r in rows})}, + "apply_verified": sum(1 for r in rows if r["apply"] == "VERIFIED"), + "missed_effects": sum(r["missed"] or 0 for r in rows), + "false_diffs": sum(r["false"] or 0 for r in rows), + "independent_disagreements": sum(1 for r in rows if not r["independent_agrees"]), + "undo_supported": sup, "undo_verified": ver, + "undo_success_rate": round(ver / sup, 4) if sup else None, + "db_back_to_start": sum(1 for r in rows if r["db_back_to_start"]), + "preview_s_median": sorted(r["preview_s"] for r in rows)[len(rows) // 2], + "acrfence": acr, "trigger_probe": trigger, "mcp_sdk_session": mcp_ok, + } + result = {"schema": "openadapt.ext-tx-proxy-lab/v1", "app": "PostgreSQL 16 (synthetic schema)", + "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "summary": summary, "rows": rows} + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + log(json.dumps(summary, indent=2, sort_keys=True)) + subprocess.run(["dropdb", "--if-exists", DB], check=False) + return 0 + + +async def mcp_session(server_cls: Any, proxy: Any) -> dict[str, Any]: + from mcp import ClientSession + from mcp.client.streamable_http import streamablehttp_client + + server = server_cls(proxy) + server.start() + try: + headers = {"Authorization": f"Bearer {server.token}"} + async with streamablehttp_client(server.url, headers=headers) as (r, w, _): + async with ClientSession(r, w) as s: + await s.initialize() + tools = [t.name for t in (await s.list_tools()).tools] + got = await s.call_tool("sql_preview", {"sql": "UPDATE users SET active = true WHERE id = 1"}) + body = json.loads(got.content[0].text) + proxy.key("y") + applied = json.loads((await s.call_tool("sql_apply", {"plan": body["plan"]})).content[0].text) + undone = json.loads((await s.call_tool("sql_undo", {"plan": body["plan"]})).content[0].text) + return {"tools": tools, "apply": applied["outcome"], "undo": undone["outcome"]} + finally: + server.stop() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py index 7469154ec5..f672e8eb2e 100644 --- a/packages/flow/benchmark/ext_tx/run.py +++ b/packages/flow/benchmark/ext_tx/run.py @@ -331,6 +331,7 @@ def seeded_faults(ctx: Ctx, writes_fn: Callable[[int], list[dict[str, Any]]], po adapter_cls: Any, trials: int) -> dict[str, Any]: """A change the plan didn't predict, during apply and before undo: both must be caught.""" caught_apply = caught_undo = 0 + detail: list[dict[str, Any]] = [] real = adapter_cls.apply for t in range(trials): def apply_and_poke(self, w, base, key, _real=real): # noqa: ANN001 @@ -352,8 +353,13 @@ def apply_and_poke(self, w, base, key, _real=real): # noqa: ANN001 engine.apply_plan(ctx, plan["digest"]) poke() undone = engine.undo_plan(ctx, plan["digest"]) - caught_undo += int(undone["outcome"] != "ROLLED_BACK" and undone["tx"]["collateral_changes"] > 0) - return {"trials": trials, "missed_effect_caught": caught_apply, "collateral_caught": caught_undo} + hit = undone["outcome"] != "ROLLED_BACK" and undone["tx"]["collateral_changes"] > 0 + caught_undo += int(hit) + if not hit: + detail.append({"trial": t, "undo": undone["outcome"], "codes": undone["tx"]["codes"], + "collateral": undone["tx"]["collateral_changes"], "planned": plan["predicted"]}) + return {"trials": trials, "missed_effect_caught": caught_apply, "collateral_caught": caught_undo, + "not_caught": detail} # -- main ---------------------------------------------------------------------- diff --git a/packages/flow/benchmark/ext_tx/setup_time.sh b/packages/flow/benchmark/ext_tx/setup_time.sh new file mode 100755 index 0000000000..d2a1552816 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/setup_time.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Time from a fresh virtual environment to the first dry-run diff through +# `openadapt-flow proxy`, on the zenbook's WSL (PostgreSQL 16 local). +# The wheels are built from this worktree first (a stand-in for PyPI, not timed); +# the install is timed with no package cache. +set -euo pipefail +cd "$(dirname "$0")/../.." # packages/flow +UV=${UV:-$HOME/.local/bin/uv} +out=$(mktemp -d) +$UV build -q --wheel --out-dir "$out" . >/dev/null +$UV build -q --wheel --out-dir "$out" ../types >/dev/null +db=oa_first_diff +dropdb --if-exists $db; createdb $db +psql -qAt -d $db -c "CREATE TABLE users (id serial PRIMARY KEY, name text, role text, active boolean DEFAULT true); + INSERT INTO users (name, role) SELECT 'u' || g, CASE WHEN g % 150 = 0 THEN 'admin' ELSE 'member' END FROM generate_series(1, 1000) g;" +fresh=$(mktemp -d) +t0=$(date +%s.%N) +$UV venv -q --python 3.12 "$fresh/venv" +$UV pip install -q --no-cache --python "$fresh/venv/bin/python" "$out"/openadapt_types-*.whl "$out"/openadapt_flow-*.whl 'psycopg[binary]' +t1=$(date +%s.%N) +OPENADAPT_TX_STATE="$fresh/state" OPENADAPT_SEAL_HOME="$fresh/seal" \ + "$fresh/venv/bin/openadapt-flow" proxy --postgres "dbname=$db host=/var/run/postgresql" --flag users.role=admin \ + -- "$fresh/venv/bin/python" benchmark/ext_tx/first_diff_client.py +t2=$(date +%s.%N) +python3 -c "print(f'install_s={$t1-$t0:.1f} first_diff_s={$t2-$t1:.1f} total_s={$t2-$t0:.1f}')" +dropdb --if-exists $db; rm -rf "$fresh" "$out" diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index eabdab3cd4..c63f45564e 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -646,37 +646,41 @@ def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: def compensate_sql(self, images: Mapping[str, Any]) -> None: """Undo one statement from its images, in one transaction: delete what - it added, restore what it changed, reinsert what it removed.""" + it added, restore what it changed, reinsert what it removed. + + Foreign keys can make the order matter (a cascade removed children + with their parent), so each row runs under a savepoint and failed rows + are retried in later passes until none makes progress.""" + steps: list[tuple[str, str, Mapping[str, Any]]] = [ + ("delete", rid, item) for rid, item in images.get("added_pk", {}).items() + ] + [("restore", rid, item) for rid, item in images.get("before", {}).items()] con = self.connect() try: cur = con.cursor() self._begin(cur) try: - for rid, item in images.get("added_pk", {}).items(): - self._delete_row(cur, rid, item) - for rid, item in images.get("before", {}).items(): - table = rid.split("/", 1)[0] - pk, row = item["pk"], item["row"] - if not pk: - raise AdapterError(f"{table} has no primary key: no generated undo") - where = " AND ".join(f"{self._ident(c)} = {self.ph}" for c in pk) - cur.execute(f"SELECT 1 FROM {self._ident(table)} WHERE {where}", - tuple(untag(row[c]) for c in pk)) - if cur.fetchall(): - cols = [c for c in row if c not in pk] - sets = ", ".join(f"{self._ident(c)} = {self.ph}" for c in cols) - if cols: - cur.execute( - f"UPDATE {self._ident(table)} SET {sets} WHERE {where}", - (*(untag(row[c]) for c in cols), *(untag(row[c]) for c in pk)), - ) - else: - cols = list(row) - cur.execute( - f"INSERT INTO {self._ident(table)} ({', '.join(self._ident(c) for c in cols)}) " - f"VALUES ({', '.join([self.ph] * len(cols))})", - tuple(untag(row[c]) for c in cols), - ) + left = steps + n = 0 + while left: + failed = [] + for step in left: + n += 1 + sp = f"oa_undo_{n}" + cur.execute(f"SAVEPOINT {sp}") + try: + if step[0] == "delete": + self._delete_row(cur, step[1], step[2]) + else: + self._restore_row(cur, step[1], step[2]) + cur.execute(f"RELEASE SAVEPOINT {sp}") + except AdapterError: + raise + except Exception: # noqa: BLE001 - a constraint: retry after the others + cur.execute(f"ROLLBACK TO SAVEPOINT {sp}") + failed.append(step) + if len(failed) == len(left): + raise AdapterError(f"{len(failed)} row(s) could not be restored") + left = failed except Exception: con.rollback() raise @@ -684,6 +688,29 @@ def compensate_sql(self, images: Mapping[str, Any]) -> None: finally: con.close() + def _restore_row(self, cur: Any, rid: str, item: Mapping[str, Any]) -> None: + table = rid.split("/", 1)[0] + pk, row = item["pk"], item["row"] + if not pk: + raise AdapterError(f"{table} has no primary key: no generated undo") + where = " AND ".join(f"{self._ident(c)} = {self.ph}" for c in pk) + cur.execute(f"SELECT 1 FROM {self._ident(table)} WHERE {where}", tuple(untag(row[c]) for c in pk)) + if cur.fetchall(): + cols = [c for c in row if c not in pk] + if cols: + sets = ", ".join(f"{self._ident(c)} = {self.ph}" for c in cols) + cur.execute( + f"UPDATE {self._ident(table)} SET {sets} WHERE {where}", + (*(untag(row[c]) for c in cols), *(untag(row[c]) for c in pk)), + ) + else: + cols = list(row) + cur.execute( + f"INSERT INTO {self._ident(table)} ({', '.join(self._ident(c) for c in cols)}) " + f"VALUES ({', '.join([self.ph] * len(cols))})", + tuple(untag(row[c]) for c in cols), + ) + def _delete_row(self, cur: Any, rid: str, item: Mapping[str, Any]) -> None: table = rid.split("/", 1)[0] pk, row = item["pk"], item["row"] diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 6a25397d6e..f3e59086f1 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -527,7 +527,7 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str "sql": "statements"}[w["op"]] if w["irreversible"] and w["op"] == "delete": verb = "deleted after holdback" - k = f"{w['system']}.{w['collection']} {verb}" + k = f"SQL statement(s) on {w['system']}" if w["op"] == "sql" else f"{w['system']}.{w['collection']} {verb}" summary[k] = summary.get(k, 0) + 1 anomalies = _anomalies(spec, writes, baselines) anomalies += _row_anomalies(spec, writes, staged_rows) From 4665a9e08ac3d8cf46ce12090a15c74487fed223 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:50:35 -0500 Subject: [PATCH 04/21] chore(plan): ruff, mypy; tx file key 'list' maps to list_ --- .../benchmark/ext_tx/first_diff_client.py | 37 +- packages/flow/benchmark/ext_tx/proxy_lab.py | 192 +++-- packages/flow/benchmark/ext_tx/run.py | 437 ++++++++--- .../flow/openadapt_flow/txplan/adapters.py | 214 ++++-- packages/flow/openadapt_flow/txplan/cli.py | 92 ++- packages/flow/openadapt_flow/txplan/engine.py | 690 +++++++++++++++--- packages/flow/openadapt_flow/txplan/proxy.py | 262 +++++-- .../flow/openadapt_flow/txplan/proxy_cli.py | 84 ++- packages/flow/openadapt_flow/txplan/spec.py | 16 +- packages/flow/openadapt_flow/txplan/state.py | 38 +- packages/flow/tests/test_txplan.py | 506 ++++++++++--- packages/flow/tests/txplan_servers.py | 14 +- 12 files changed, 2070 insertions(+), 512 deletions(-) diff --git a/packages/flow/benchmark/ext_tx/first_diff_client.py b/packages/flow/benchmark/ext_tx/first_diff_client.py index 4898c1094d..c2c4aed86f 100644 --- a/packages/flow/benchmark/ext_tx/first_diff_client.py +++ b/packages/flow/benchmark/ext_tx/first_diff_client.py @@ -9,10 +9,35 @@ url, token = os.environ["OPENADAPT_MCP_URL"], os.environ["OPENADAPT_MCP_TOKEN"] assert "DATABASE_URL" not in os.environ and "PGPASSWORD" not in os.environ -h = {"Authorization": f"Bearer {token}", "Accept": "application/json, text/event-stream"} -httpx.post(url, headers=h, json={"jsonrpc": "2.0", "id": 1, "method": "initialize", - "params": {"protocolVersion": "2025-06-18", "capabilities": {}, - "clientInfo": {"name": "lab", "version": "1"}}}).raise_for_status() -got = httpx.post(url, headers=h, json={"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { - "name": "sql_preview", "arguments": {"sql": "UPDATE users SET active = false WHERE id <= 412"}}}).json() +h = { + "Authorization": f"Bearer {token}", + "Accept": "application/json, text/event-stream", +} +httpx.post( + url, + headers=h, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "lab", "version": "1"}, + }, + }, +).raise_for_status() +got = httpx.post( + url, + headers=h, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "sql_preview", + "arguments": {"sql": "UPDATE users SET active = false WHERE id <= 412"}, + }, + }, +).json() print(json.loads(got["result"]["content"][0]["text"])["summary"]) diff --git a/packages/flow/benchmark/ext_tx/proxy_lab.py b/packages/flow/benchmark/ext_tx/proxy_lab.py index 327a481626..1d33b2102a 100644 --- a/packages/flow/benchmark/ext_tx/proxy_lab.py +++ b/packages/flow/benchmark/ext_tx/proxy_lab.py @@ -36,7 +36,12 @@ def log(msg: str) -> None: def psql(sql: str, db: str = DB) -> str: - return subprocess.run(["psql", "-qAt", "-d", db, "-c", sql], check=True, capture_output=True, text=True).stdout + return subprocess.run( + ["psql", "-qAt", "-d", db, "-c", sql], + check=True, + capture_output=True, + text=True, + ).stdout def reset() -> None: @@ -58,9 +63,11 @@ def reset() -> None: def dump() -> str: - return psql("SELECT 'u', md5(string_agg(t::text, ',' ORDER BY id)) FROM users t " - "UNION ALL SELECT 'o', md5(string_agg(t::text, ',' ORDER BY id)) FROM orders t " - "UNION ALL SELECT 'e', md5(string_agg(t::text, ',' ORDER BY user_id, kind)) FROM events t") + return psql( + "SELECT 'u', md5(string_agg(t::text, ',' ORDER BY id)) FROM users t " + "UNION ALL SELECT 'o', md5(string_agg(t::text, ',' ORDER BY id)) FROM orders t " + "UNION ALL SELECT 'e', md5(string_agg(t::text, ',' ORDER BY user_id, kind)) FROM events t" + ) def statements(rng: random.Random, n: int) -> list[tuple[str, str]]: @@ -69,21 +76,56 @@ def statements(rng: random.Random, n: int) -> list[tuple[str, str]]: k = i % 8 a = rng.randint(1, 550) if k == 0: - out.append(("bulk_update", f"UPDATE users SET active = false WHERE id BETWEEN {a} AND {a + rng.randint(5, 60)}")) + out.append( + ( + "bulk_update", + f"UPDATE users SET active = false WHERE id BETWEEN {a} AND {a + rng.randint(5, 60)}", + ) + ) elif k == 1: - out.append(("expr_update", f"UPDATE users SET balance = balance * 1.1 WHERE role = 'member' AND id % {rng.randint(7, 40)} = 0")) + out.append( + ( + "expr_update", + f"UPDATE users SET balance = balance * 1.1 WHERE role = 'member' AND id % {rng.randint(7, 40)} = 0", + ) + ) elif k == 2: - out.append(("insert_values", f"INSERT INTO users (name, role) VALUES ('lab {i}a', 'member'), ('lab {i}b', 'member')")) + out.append( + ( + "insert_values", + f"INSERT INTO users (name, role) VALUES ('lab {i}a', 'member'), ('lab {i}b', 'member')", + ) + ) elif k == 3: - out.append(("insert_select", f"INSERT INTO orders (user_id, total) SELECT id, 1.00 FROM users WHERE id BETWEEN {a} AND {a + 4}")) + out.append( + ( + "insert_select", + f"INSERT INTO orders (user_id, total) SELECT id, 1.00 FROM users WHERE id BETWEEN {a} AND {a + 4}", + ) + ) elif k == 4: - out.append(("delete_where", f"DELETE FROM orders WHERE total < {rng.randint(2, 6)} AND user_id BETWEEN {a} AND {a + 40}")) + out.append( + ( + "delete_where", + f"DELETE FROM orders WHERE total < {rng.randint(2, 6)} AND user_id BETWEEN {a} AND {a + 40}", + ) + ) elif k == 5: out.append(("delete_cascade", f"DELETE FROM users WHERE id = {a}")) elif k == 6: - out.append(("update_join", f"UPDATE orders SET total = 0 WHERE user_id IN (SELECT id FROM users WHERE id BETWEEN {a} AND {a + 3})")) + out.append( + ( + "update_join", + f"UPDATE orders SET total = 0 WHERE user_id IN (SELECT id FROM users WHERE id BETWEEN {a} AND {a + 3})", + ) + ) else: - out.append(("migration_like", f"UPDATE users SET name = upper(name) WHERE id % {rng.randint(50, 90)} = 0")) + out.append( + ( + "migration_like", + f"UPDATE users SET name = upper(name) WHERE id % {rng.randint(50, 90)} = 0", + ) + ) return out @@ -92,8 +134,15 @@ def independent_counts(before: Any, after: Any) -> dict[str, dict[str, int]]: out = {} for table, d in diff_database(before, after).items(): - n = (lambda v: v if isinstance(v, int) else len(v)) - out[table] = {"added": n(d.added), "changed": n(d.changed), "removed": n(d.removed)} + + def n(v: Any) -> int: + return v if isinstance(v, int) else len(v) + + out[table] = { + "added": n(d.added), + "changed": n(d.changed), + "removed": n(d.removed), + } return out @@ -131,31 +180,49 @@ def main() -> int: indep = independent_counts(snap0, snap1) predicted = {t: c for t, c in (prev["tables"] or {}).items()} agree = {t: c for t, c in indep.items() if any(c.values())} == { - t: c for t, c in predicted.items() if any(c.values())} + t: c for t, c in predicted.items() if any(c.values()) + } undone = proxy.undo(prev["plan"]) back = dump() == start - rows.append({ - "kind": kind, "rows_touched": sum(sum(c.values()) for c in predicted.values()), - "tables": sorted(predicted), "anomalies": len(prev["anomalies"]), - "apply": applied["outcome"], "missed": applied["tx"].get("missed_effects"), - "false": applied["tx"].get("false_diffs"), "independent_agrees": agree, - "undo": undone["outcome"], "undo_verified": undone["tx"]["undo_verified"], - "undo_supported": undone["tx"]["undo_supported"], "db_back_to_start": back, - "preview_s": round(t_preview, 3), - }) + rows.append( + { + "kind": kind, + "rows_touched": sum(sum(c.values()) for c in predicted.values()), + "tables": sorted(predicted), + "anomalies": len(prev["anomalies"]), + "apply": applied["outcome"], + "missed": applied["tx"].get("missed_effects"), + "false": applied["tx"].get("false_diffs"), + "independent_agrees": agree, + "undo": undone["outcome"], + "undo_verified": undone["tx"]["undo_verified"], + "undo_supported": undone["tx"]["undo_supported"], + "db_back_to_start": back, + "preview_s": round(t_preview, 3), + } + ) if not (agree and back and undone["outcome"] == "ROLLED_BACK"): - log(f"{kind}: apply {applied['outcome']} agree {agree} undo {undone['outcome']} back {back} {undone['tx'].get('codes')} pred {predicted} indep {indep}") + log( + f"{kind}: apply {applied['outcome']} agree {agree} undo {undone['outcome']} back {back} {undone['tx'].get('codes')} pred {predicted} indep {indep}" + ) log(f"{len(rows)} statements done") # ACRFence on the proxy: a regenerated statement for the same rows after a restore. - acr = {"trials": 0, "held_not_applied": 0, "double_effects_through": 0, "control_duplicates": 0} + acr = { + "trials": 0, + "held_not_applied": 0, + "double_effects_through": 0, + "control_duplicates": 0, + } for t in range(20): a = 100 + t * 7 before = psql(f"SELECT balance FROM users WHERE id = {a}").strip() p1 = proxy.preview(f"UPDATE users SET balance = balance + 100 WHERE id = {a}") proxy.key("y") proxy.apply(p1["plan"]) - p2 = proxy.preview(f"UPDATE users SET balance = balance + 100.00 WHERE id = {a} AND active IS NOT NULL") + p2 = proxy.preview( + f"UPDATE users SET balance = balance + 100.00 WHERE id = {a} AND active IS NOT NULL" + ) try: out = proxy.apply(p2["plan"]) applied_twice = out["outcome"] == "VERIFIED" @@ -164,24 +231,35 @@ def main() -> int: proxy.pending.clear() after = psql(f"SELECT balance - {before} FROM users WHERE id = {a}").strip() acr["trials"] += 1 - acr["held_not_applied"] += int(p2["ledger"] == "possible_replay" and not applied_twice) + acr["held_not_applied"] += int( + p2["ledger"] == "possible_replay" and not applied_twice + ) acr["double_effects_through"] += int(float(after) > 100.0) # Control: the same two statements straight to the database. psql(f"UPDATE users SET balance = balance + 100 WHERE id = {a + 1}") - psql(f"UPDATE users SET balance = balance + 100.00 WHERE id = {a + 1} AND active IS NOT NULL") + psql( + f"UPDATE users SET balance = balance + 100.00 WHERE id = {a + 1} AND active IS NOT NULL" + ) acr["control_duplicates"] += 1 log(f"acrfence {acr}") # Trigger probe (not in the supported set): the dry run must show the trigger's rows. - psql("CREATE TABLE audit (id serial PRIMARY KEY, user_id int);" - "CREATE FUNCTION f_audit() RETURNS trigger AS $$ BEGIN INSERT INTO audit (user_id) VALUES (NEW.id); RETURN NEW; END $$ LANGUAGE plpgsql;" - "CREATE TRIGGER t_audit AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f_audit();") + psql( + "CREATE TABLE audit (id serial PRIMARY KEY, user_id int);" + "CREATE FUNCTION f_audit() RETURNS trigger AS $$ BEGIN INSERT INTO audit (user_id) VALUES (NEW.id); RETURN NEW; END $$ LANGUAGE plpgsql;" + "CREATE TRIGGER t_audit AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f_audit();" + ) tp = proxy.preview("UPDATE users SET name = name || '!' WHERE id BETWEEN 10 AND 14") proxy.key("y") ta = proxy.apply(tp["plan"]) tu = proxy.undo(tp["plan"]) - trigger = {"predicted_tables": tp["tables"], "apply": ta["outcome"], "missed": ta["tx"].get("missed_effects"), - "undo": tu["outcome"], "collateral": tu["tx"]["collateral_changes"]} + trigger = { + "predicted_tables": tp["tables"], + "apply": ta["outcome"], + "missed": ta["tx"].get("missed_effects"), + "undo": tu["outcome"], + "collateral": tu["tx"]["collateral_changes"], + } log(f"trigger {trigger}") psql("DROP TRIGGER t_audit ON users; DROP TABLE audit; DROP FUNCTION f_audit();") @@ -194,19 +272,32 @@ def main() -> int: summary = { "statements": len(rows), "rows_touched": sum(r["rows_touched"] for r in rows), - "by_kind": {k: sum(1 for r in rows if r["kind"] == k) for k in sorted({r["kind"] for r in rows})}, + "by_kind": { + k: sum(1 for r in rows if r["kind"] == k) + for k in sorted({r["kind"] for r in rows}) + }, "apply_verified": sum(1 for r in rows if r["apply"] == "VERIFIED"), "missed_effects": sum(r["missed"] or 0 for r in rows), "false_diffs": sum(r["false"] or 0 for r in rows), - "independent_disagreements": sum(1 for r in rows if not r["independent_agrees"]), - "undo_supported": sup, "undo_verified": ver, + "independent_disagreements": sum( + 1 for r in rows if not r["independent_agrees"] + ), + "undo_supported": sup, + "undo_verified": ver, "undo_success_rate": round(ver / sup, 4) if sup else None, "db_back_to_start": sum(1 for r in rows if r["db_back_to_start"]), "preview_s_median": sorted(r["preview_s"] for r in rows)[len(rows) // 2], - "acrfence": acr, "trigger_probe": trigger, "mcp_sdk_session": mcp_ok, + "acrfence": acr, + "trigger_probe": trigger, + "mcp_sdk_session": mcp_ok, + } + result = { + "schema": "openadapt.ext-tx-proxy-lab/v1", + "app": "PostgreSQL 16 (synthetic schema)", + "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "summary": summary, + "rows": rows, } - result = {"schema": "openadapt.ext-tx-proxy-lab/v1", "app": "PostgreSQL 16 (synthetic schema)", - "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "summary": summary, "rows": rows} Path(args.out).parent.mkdir(parents=True, exist_ok=True) Path(args.out).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") log(json.dumps(summary, indent=2, sort_keys=True)) @@ -226,12 +317,27 @@ async def mcp_session(server_cls: Any, proxy: Any) -> dict[str, Any]: async with ClientSession(r, w) as s: await s.initialize() tools = [t.name for t in (await s.list_tools()).tools] - got = await s.call_tool("sql_preview", {"sql": "UPDATE users SET active = true WHERE id = 1"}) + got = await s.call_tool( + "sql_preview", + {"sql": "UPDATE users SET active = true WHERE id = 1"}, + ) body = json.loads(got.content[0].text) proxy.key("y") - applied = json.loads((await s.call_tool("sql_apply", {"plan": body["plan"]})).content[0].text) - undone = json.loads((await s.call_tool("sql_undo", {"plan": body["plan"]})).content[0].text) - return {"tools": tools, "apply": applied["outcome"], "undo": undone["outcome"]} + applied = json.loads( + (await s.call_tool("sql_apply", {"plan": body["plan"]})) + .content[0] + .text + ) + undone = json.loads( + (await s.call_tool("sql_undo", {"plan": body["plan"]})) + .content[0] + .text + ) + return { + "tools": tools, + "apply": applied["outcome"], + "undo": undone["outcome"], + } finally: server.stop() diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py index f672e8eb2e..7fa9c0c157 100644 --- a/packages/flow/benchmark/ext_tx/run.py +++ b/packages/flow/benchmark/ext_tx/run.py @@ -58,15 +58,30 @@ "name": "vikunja", "kind": "rest", "base_url": VIKUNJA, - "auth": {"header": "Authorization", "prefix": "Bearer ", "value_env": "LAB_VIKUNJA_TOKEN"}, + "auth": { + "header": "Authorization", + "prefix": "Bearer ", + "value_env": "LAB_VIKUNJA_TOKEN", + }, "collections": [ { "name": "task", "id_field": "id", - "list": {"path": "/api/v1/tasks", "page_param": "page", "per_page": 50}, + "list": { + "path": "/api/v1/tasks", + "page_param": "page", + "per_page": 50, + }, "read": {"path": "/api/v1/tasks/{id}"}, - "create": {"method": "PUT", "path": "/api/v1/projects/{project_id}/tasks"}, - "update": {"method": "POST", "path": "/api/v1/tasks/{id}", "replace": True}, + "create": { + "method": "PUT", + "path": "/api/v1/projects/{project_id}/tasks", + }, + "update": { + "method": "POST", + "path": "/api/v1/tasks/{id}", + "replace": True, + }, "delete": {"method": "DELETE", "path": "/api/v1/tasks/{id}"}, "server_fields": ["updated"], "derived": {"done": ["done_at"]}, @@ -85,8 +100,11 @@ "dialect": "mysql", "driver": "pymysql", "connect_args": { - "host": "127.0.0.1", "port": 9636, "user": "dolidbuser", - "database": "dolidb", "charset": "utf8mb4", + "host": "127.0.0.1", + "port": 9636, + "user": "dolidbuser", + "database": "dolidb", + "charset": "utf8mb4", }, "password_env": "LAB_DOLI_DB_PASSWORD", "tables": {"llx_societe": "rowid"}, @@ -117,15 +135,25 @@ def vikunja_setup() -> tuple[str, int]: user = f"lab{int(time.time())}" pw = "synthetic-Lab-pass-1" c = httpx.Client(base_url=VIKUNJA, timeout=20) - r = c.post("/api/v1/register", json={"username": user, "email": f"{user}@example.test", "password": pw}) + r = c.post( + "/api/v1/register", + json={"username": user, "email": f"{user}@example.test", "password": pw}, + ) r.raise_for_status() - token = c.post("/api/v1/login", json={"username": user, "password": pw}).json()["token"] + token = c.post("/api/v1/login", json={"username": user, "password": pw}).json()[ + "token" + ] c.headers["Authorization"] = f"Bearer {token}" project = c.put("/api/v1/projects", json={"title": "lab project"}).json()["id"] for i in range(40): - c.put(f"/api/v1/projects/{project}/tasks", json={ - "title": f"seed task {i}", "description": f"synthetic {i}", "priority": i % 5, - }).raise_for_status() + c.put( + f"/api/v1/projects/{project}/tasks", + json={ + "title": f"seed task {i}", + "description": f"synthetic {i}", + "priority": i % 5, + }, + ).raise_for_status() return token, int(project) @@ -163,7 +191,9 @@ def doli_cleanup(adapter: SqlAdapter, prefix: str = "Lab ") -> int: # -- batches ------------------------------------------------------------------- -def rest_batch(rng: random.Random, ids: list[int], project: int, b: int) -> list[dict[str, Any]]: +def rest_batch( + rng: random.Random, ids: list[int], project: int, b: int +) -> list[dict[str, Any]]: out = [] for tid in rng.sample(ids, 6): field = rng.choice(["title", "description", "priority", "done", "percent_done"]) @@ -174,43 +204,105 @@ def rest_batch(rng: random.Random, ids: list[int], project: int, b: int) -> list "done": rng.choice([True, False]), "percent_done": rng.choice([0.1, 0.5, 0.9]), }[field] - out.append({"system": "vikunja", "collection": "task", "op": "update", "id": tid, "fields": {field: value}}) + out.append( + { + "system": "vikunja", + "collection": "task", + "op": "update", + "id": tid, + "fields": {field: value}, + } + ) for i in range(4): - out.append({"system": "vikunja", "collection": "task", "op": "create", - "fields": {"title": f"new {b}-{i}", "project_id": project, "description": "synthetic"}}) + out.append( + { + "system": "vikunja", + "collection": "task", + "op": "create", + "fields": { + "title": f"new {b}-{i}", + "project_id": project, + "description": "synthetic", + }, + } + ) return out -def sql_batch(rng: random.Random, ids: list[int], b: int, tag: int) -> list[dict[str, Any]]: +def sql_batch( + rng: random.Random, ids: list[int], b: int, tag: int +) -> list[dict[str, Any]]: picks = rng.sample(ids, 7) out = [] for rid in picks[:5]: field = rng.choice(["note_public", "phone", "town", "email"]) - value = {"note_public": f"synthetic note {b}", "phone": f"555-9{b:03d}", - "town": f"Town {b}", "email": f"lab{b}@example.test"}[field] - out.append({"system": "dolibarr", "collection": "llx_societe", "op": "update", "id": rid, - "fields": {field: value}}) + value = { + "note_public": f"synthetic note {b}", + "phone": f"555-9{b:03d}", + "town": f"Town {b}", + "email": f"lab{b}@example.test", + }[field] + out.append( + { + "system": "dolibarr", + "collection": "llx_societe", + "op": "update", + "id": rid, + "fields": {field: value}, + } + ) for rid in picks[5:]: - out.append({"system": "dolibarr", "collection": "llx_societe", "op": "delete", "id": rid}) + out.append( + { + "system": "dolibarr", + "collection": "llx_societe", + "op": "delete", + "id": rid, + } + ) for i in range(3): - out.append({"system": "dolibarr", "collection": "llx_societe", "op": "create", - "fields": {"nom": f"Lab new {tag}-{b}-{i}", "entity": 1, "datec": "2026-11-21 12:00:00", - "status": 1, "client": 1}}) + out.append( + { + "system": "dolibarr", + "collection": "llx_societe", + "op": "create", + "fields": { + "nom": f"Lab new {tag}-{b}-{i}", + "entity": 1, + "datec": "2026-11-21 12:00:00", + "status": 1, + "client": 1, + }, + } + ) return out def mail_batch(b: int) -> list[dict[str, Any]]: - return [{"system": "outbox", "op": "send", - "fields": {"to": f"lab{b}-{i}@example.test", "subject": f"Synthetic notice {b}-{i}", - "body": "synthetic body"}} for i in range(10)] + return [ + { + "system": "outbox", + "op": "send", + "fields": { + "to": f"lab{b}-{i}@example.test", + "subject": f"Synthetic notice {b}-{i}", + "body": "synthetic body", + }, + } + for i in range(10) + ] # -- one round ----------------------------------------------------------------- -def round_trip(ctx: Ctx, task: str, writes: list[dict[str, Any]], *, release_first: int = 0) -> dict[str, Any]: +def round_trip( + ctx: Ctx, task: str, writes: list[dict[str, Any]], *, release_first: int = 0 +) -> dict[str, Any]: plan = engine.make_plan(ctx, task, writes) - engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, plan["digest"], approver="lab", decided_by="automation" + ) applied = engine.apply_plan(ctx, plan["digest"]) released = None if release_first: @@ -220,13 +312,23 @@ def round_trip(ctx: Ctx, task: str, writes: list[dict[str, Any]], *, release_fir for h in held[release_first:]: ctx.state.unhold(h["key"]) e = ctx.state.entry(h["key"]) - ctx.state.record(h["key"], "cancelled", plan=plan["digest"], payload=e.payload if e else "") + ctx.state.record( + h["key"], + "cancelled", + plan=plan["digest"], + payload=e.payload if e else "", + ) released = engine.release(ctx, plan["digest"]) undone = engine.undo_plan(ctx, plan["digest"]) mailbox = None if release_first: mail = ctx.adapter("outbox") - per = {"cancelled_never_sent": 0, "cancelled_sent": 0, "released_exactly_once": 0, "released_other": 0} + per = { + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "released_exactly_once": 0, + "released_other": 0, + } for w in plan["writes"]: n = mail.count(w["key"]) status = ctx.state.entry(w["key"]).status @@ -240,16 +342,26 @@ def round_trip(ctx: Ctx, task: str, writes: list[dict[str, Any]], *, release_fir "digest": plan["digest"][:16], "dry_run": plan["dry_run"], "anomalies": len(plan["anomalies"]), - "apply": applied["tx"], "apply_outcome": applied["outcome"], - "missed": applied["missed"], "false": applied["false"], + "apply": applied["tx"], + "apply_outcome": applied["outcome"], + "missed": applied["missed"], + "false": applied["false"], "release": released["tx"] if released else None, - "undo": undone["tx"], "undo_outcome": undone["outcome"], + "undo": undone["tx"], + "undo_outcome": undone["outcome"], "collateral": undone["collateral"][:10], } -def acrfence(ctx: Ctx, kind: str, trials: int, count: Callable[[], int], make: Callable[[str, int], dict[str, Any]], - *, release: bool = False) -> dict[str, Any]: +def acrfence( + ctx: Ctx, + kind: str, + trials: int, + count: Callable[[], int], + make: Callable[[str, int], dict[str, Any]], + *, + release: bool = False, +) -> dict[str, Any]: """Control arm (no guard) and guarded arm, per trial.""" raw = ctx.adapter(make("x", 0)["system"]) ctrl_dups = 0 @@ -272,7 +384,9 @@ def acrfence(ctx: Ctx, kind: str, trials: int, count: Callable[[], int], make: C task = f"acr-{kind}-{t}-{int(time.time())}" n0 = count() p = engine.make_plan(ctx, task, [make(f"uuid-a-{t}", t)]) - engine.approve_plan(ctx.state, p["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, p["digest"], approver="lab", decided_by="automation" + ) engine.apply_plan(ctx, p["digest"]) if release: time.sleep(1.2) @@ -280,26 +394,42 @@ def acrfence(ctx: Ctx, kind: str, trials: int, count: Callable[[], int], make: C # Restore: drop the agent's in-memory context and regenerate the payload. ctx2 = Ctx(spec=ctx.spec, state=State(ctx.state.root)) q = engine.make_plan(ctx2, task, [make(f"uuid-b-{t}", t)]) - engine.approve_plan(ctx2.state, q["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx2.state, q["digest"], approver="lab", decided_by="automation" + ) try: engine.apply_plan(ctx2, q["digest"]) except TxRefused as exc: blocked += int(exc.code == "replay_mismatch") r = engine.make_plan(ctx2, task, [make(f"uuid-a-{t}", t)]) - engine.approve_plan(ctx2.state, r["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx2.state, r["digest"], approver="lab", decided_by="automation" + ) out = engine.apply_plan(ctx2, r["digest"]) if release: time.sleep(1.2) engine.release(ctx2, r["digest"]) - replays_not_sent += int(out["tx"].get("replays", 0) == 1 and out["tx"]["sent"] == 0) + replays_not_sent += int( + out["tx"].get("replays", 0) == 1 and out["tx"]["sent"] == 0 + ) time.sleep(0.3 if release else 0) guarded_extra += max(0, count() - n0 - 1) - return {"trials": trials, "control_duplicates": ctrl_dups, "blocked": blocked, - "identical_replays_not_sent": replays_not_sent, "double_effects_through": guarded_extra} + return { + "trials": trials, + "control_duplicates": ctrl_dups, + "blocked": blocked, + "identical_replays_not_sent": replays_not_sent, + "double_effects_through": guarded_extra, + } -def crash_arm(spec_path: Path, state_root: Path, trials: int, count: Callable[[], int], - make: Callable[[str, int], dict[str, Any]]) -> dict[str, Any]: +def crash_arm( + spec_path: Path, + state_root: Path, + trials: int, + count: Callable[[], int], + make: Callable[[str, int], dict[str, Any]], +) -> dict[str, Any]: extra = 0 crashed = 0 for t in range(trials): @@ -307,40 +437,60 @@ def crash_arm(spec_path: Path, state_root: Path, trials: int, count: Callable[[] task = f"crash-{t}-{int(time.time())}" n0 = count() p = engine.make_plan(ctx, task, [make(f"uuid-c-{t}", t)]) - engine.approve_plan(ctx.state, p["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, p["digest"], approver="lab", decided_by="automation" + ) code = ( "from pathlib import Path; from openadapt_flow.txplan import engine;" "from openadapt_flow.txplan.spec import load_spec; from openadapt_flow.txplan.state import State;" f"engine.apply_plan(engine.Ctx(load_spec(Path({str(spec_path)!r})), State(Path({str(state_root)!r}))), {p['digest']!r})" ) - proc = subprocess.run([sys.executable, "-c", code], env={**os.environ, engine.CRASH_ENV: "1"}, - capture_output=True, timeout=300) + proc = subprocess.run( + [sys.executable, "-c", code], + env={**os.environ, engine.CRASH_ENV: "1"}, + capture_output=True, + timeout=300, + ) crashed += int(proc.returncode == 70) for ref in (f"uuid-d-{t}", f"uuid-c-{t}"): # regenerated, then identical q = engine.make_plan(ctx, task, [make(ref, t)]) - engine.approve_plan(ctx.state, q["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, q["digest"], approver="lab", decided_by="automation" + ) try: engine.apply_plan(ctx, q["digest"]) except TxRefused: pass extra += max(0, count() - n0 - 1) - return {"trials": trials, "crashed_after_send": crashed, "double_effects_through": extra} + return { + "trials": trials, + "crashed_after_send": crashed, + "double_effects_through": extra, + } -def seeded_faults(ctx: Ctx, writes_fn: Callable[[int], list[dict[str, Any]]], poke: Callable[[], None], - adapter_cls: Any, trials: int) -> dict[str, Any]: +def seeded_faults( + ctx: Ctx, + writes_fn: Callable[[int], list[dict[str, Any]]], + poke: Callable[[], None], + adapter_cls: Any, + trials: int, +) -> dict[str, Any]: """A change the plan didn't predict, during apply and before undo: both must be caught.""" caught_apply = caught_undo = 0 detail: list[dict[str, Any]] = [] real = adapter_cls.apply for t in range(trials): + def apply_and_poke(self, w, base, key, _real=real): # noqa: ANN001 out = _real(self, w, base, key) poke() return out plan = engine.make_plan(ctx, f"fault-a-{t}-{int(time.time())}", writes_fn(t)) - engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, plan["digest"], approver="lab", decided_by="automation" + ) adapter_cls.apply = apply_and_poke try: applied = engine.apply_plan(ctx, plan["digest"]) @@ -348,18 +498,36 @@ def apply_and_poke(self, w, base, key, _real=real): # noqa: ANN001 adapter_cls.apply = real caught_apply += int(applied["tx"]["missed_effects"] > 0) engine.undo_plan(ctx, plan["digest"]) - plan = engine.make_plan(ctx, f"fault-u-{t}-{int(time.time())}", writes_fn(1000 + t)) - engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + plan = engine.make_plan( + ctx, f"fault-u-{t}-{int(time.time())}", writes_fn(1000 + t) + ) + engine.approve_plan( + ctx.state, plan["digest"], approver="lab", decided_by="automation" + ) engine.apply_plan(ctx, plan["digest"]) poke() undone = engine.undo_plan(ctx, plan["digest"]) - hit = undone["outcome"] != "ROLLED_BACK" and undone["tx"]["collateral_changes"] > 0 + hit = ( + undone["outcome"] != "ROLLED_BACK" + and undone["tx"]["collateral_changes"] > 0 + ) caught_undo += int(hit) if not hit: - detail.append({"trial": t, "undo": undone["outcome"], "codes": undone["tx"]["codes"], - "collateral": undone["tx"]["collateral_changes"], "planned": plan["predicted"]}) - return {"trials": trials, "missed_effect_caught": caught_apply, "collateral_caught": caught_undo, - "not_caught": detail} + detail.append( + { + "trial": t, + "undo": undone["outcome"], + "codes": undone["tx"]["codes"], + "collateral": undone["tx"]["collateral_changes"], + "planned": plan["predicted"], + } + ) + return { + "trials": trials, + "missed_effect_caught": caught_apply, + "collateral_caught": caught_undo, + "not_caught": detail, + } # -- main ---------------------------------------------------------------------- @@ -395,7 +563,11 @@ def main() -> int: "schema": "openadapt.ext-tx-lab/v1", "phase": args.phase, "started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), - "apps": {"rest": "Vikunja 2.7.1", "email": "Mailpit v1.27.10", "database": "Dolibarr 21.0.4 on MariaDB 11.4.13"}, + "apps": { + "rest": "Vikunja 2.7.1", + "email": "Mailpit v1.27.10", + "database": "Dolibarr 21.0.4 on MariaDB 11.4.13", + }, "spec_sha256": __import__("hashlib").sha256(spec_path.read_bytes()).hexdigest(), "rounds": {"rest": [], "sql": [], "mail": []}, } @@ -403,47 +575,91 @@ def main() -> int: for b in range(args.batches): r = round_trip(ctx, f"lab-rest-{tag}-{b}", rest_batch(rng, ids, project, b)) results["rounds"]["rest"].append(r) - log(f"rest {b}: apply {r['apply_outcome']} missed {r['missed']} false {r['false']} undo {r['undo_outcome']} {r['undo']['codes']} {r['collateral']}") + log( + f"rest {b}: apply {r['apply_outcome']} missed {r['missed']} false {r['false']} undo {r['undo_outcome']} {r['undo']['codes']} {r['collateral']}" + ) for b in range(args.batches): r = round_trip(ctx, f"lab-sql-{tag}-{b}", sql_batch(rng, doli_ids, b, tag)) results["rounds"]["sql"].append(r) - log(f"sql {b}: apply {r['apply_outcome']} missed {r['missed']} false {r['false']} undo {r['undo_outcome']} {r['undo']['codes']} {r['collateral']}") + log( + f"sql {b}: apply {r['apply_outcome']} missed {r['missed']} false {r['false']} undo {r['undo_outcome']} {r['undo']['codes']} {r['collateral']}" + ) for b in range(args.batches): r = round_trip(ctx, f"lab-mail-{tag}-{b}", mail_batch(b), release_first=5) results["rounds"]["mail"].append(r) - log(f"mail {b}: apply {r['apply_outcome']} release {r['release']} undo {r['undo']['codes']}") + log( + f"mail {b}: apply {r['apply_outcome']} release {r['release']} undo {r['undo']['codes']}" + ) def vik_count() -> int: return len(vik.frame("task")) def vik_make(ref: str, t: int) -> dict[str, Any]: - return {"system": "vikunja", "collection": "task", "op": "create", - "fields": {"title": f"refund {ref}", "project_id": project, "description": f"reference {ref}"}} + return { + "system": "vikunja", + "collection": "task", + "op": "create", + "fields": { + "title": f"refund {ref}", + "project_id": project, + "description": f"reference {ref}", + }, + } def sql_count() -> int: return sum(1 for r in sql.frame() if r.startswith("llx_societe/")) def sql_make(ref: str, t: int) -> dict[str, Any]: - return {"system": "dolibarr", "collection": "llx_societe", "op": "create", - "fields": {"nom": f"Lab refund {tag}-{ref}", "entity": 1, "datec": "2026-11-21 12:00:00", - "status": 1, "client": 1}} + return { + "system": "dolibarr", + "collection": "llx_societe", + "op": "create", + "fields": { + "nom": f"Lab refund {tag}-{ref}", + "entity": 1, + "datec": "2026-11-21 12:00:00", + "status": 1, + "client": 1, + }, + } def mail_count() -> int: return len(mail.frame()) def mail_make(ref: str, t: int) -> dict[str, Any]: - return {"system": "outbox", "op": "send", - "fields": {"to": "billing@example.test", "subject": f"Refund {ref}", "body": f"reference {ref}"}} + return { + "system": "outbox", + "op": "send", + "fields": { + "to": "billing@example.test", + "subject": f"Refund {ref}", + "body": f"reference {ref}", + }, + } results["acrfence"] = { "rest": acrfence(ctx, "rest", args.acr_trials, vik_count, vik_make), "sql": acrfence(ctx, "sql", args.acr_trials, sql_count, sql_make), - "mail": acrfence(ctx, "mail", args.acr_trials, mail_count, mail_make, release=True), + "mail": acrfence( + ctx, "mail", args.acr_trials, mail_count, mail_make, release=True + ), } log(f"acrfence {results['acrfence']}") results["crash"] = { - "rest": crash_arm(spec_path, ctx.state.root, max(5, args.acr_trials // 4), vik_count, vik_make), - "sql": crash_arm(spec_path, ctx.state.root, max(5, args.acr_trials // 4), sql_count, sql_make), + "rest": crash_arm( + spec_path, + ctx.state.root, + max(5, args.acr_trials // 4), + vik_count, + vik_make, + ), + "sql": crash_arm( + spec_path, + ctx.state.root, + max(5, args.acr_trials // 4), + sql_count, + sql_make, + ), } log(f"crash {results['crash']}") @@ -459,18 +675,45 @@ def sql_poke() -> None: con = sql.connect() try: cur = con.cursor() - cur.execute("UPDATE llx_societe SET town = %s WHERE rowid = %s", (f"poked {time.time()}", doli_ids[-1])) + cur.execute( + "UPDATE llx_societe SET town = %s WHERE rowid = %s", + (f"poked {time.time()}", doli_ids[-1]), + ) con.commit() finally: con.close() results["seeded_faults"] = { - "rest": seeded_faults(ctx, lambda t: [{"system": "vikunja", "collection": "task", "op": "update", - "id": ids[t % 5], "fields": {"priority": (t % 4) + 1}}], - vik_poke, RestAdapter, 5), - "sql": seeded_faults(ctx, lambda t: [{"system": "dolibarr", "collection": "llx_societe", "op": "update", - "id": doli_ids[t % 5], "fields": {"phone": f"555-7{t:03d}"}}], - sql_poke, SqlAdapter, 5), + "rest": seeded_faults( + ctx, + lambda t: [ + { + "system": "vikunja", + "collection": "task", + "op": "update", + "id": ids[t % 5], + "fields": {"priority": (t % 4) + 1}, + } + ], + vik_poke, + RestAdapter, + 5, + ), + "sql": seeded_faults( + ctx, + lambda t: [ + { + "system": "dolibarr", + "collection": "llx_societe", + "op": "update", + "id": doli_ids[t % 5], + "fields": {"phone": f"555-7{t:03d}"}, + } + ], + sql_poke, + SqlAdapter, + 5, + ), } log(f"faults {results['seeded_faults']}") finally: @@ -494,28 +737,46 @@ def summarize(res: dict[str, Any]) -> dict[str, Any]: out[kind] = { "rounds": len(rounds), "writes": sum(r["apply"]["writes"] for r in rounds), - "apply_verified_rounds": sum(1 for r in rounds if r["apply_outcome"] in ("VERIFIED", "COMPLETED_UNVERIFIED")), + "apply_verified_rounds": sum( + 1 + for r in rounds + if r["apply_outcome"] in ("VERIFIED", "COMPLETED_UNVERIFIED") + ), "missed_effects": sum(r["apply"].get("missed_effects", 0) for r in rounds), "false_diffs": sum(r["apply"].get("false_diffs", 0) for r in rounds), "undo_supported": sup, "undo_verified": ver, "undo_success_rate": round(ver / sup, 4) if sup else None, "cancelled_in_holdback": sum(r["undo"].get("cancelled", 0) for r in rounds), - "irreversible_released": sum(r["undo"].get("irreversible_released", 0) for r in rounds), - "release_double_sends": sum((r["release"] or {}).get("double", 0) for r in rounds), - **{k: sum((r.get("mailbox") or {}).get(k, 0) for r in rounds) - for k in ("cancelled_never_sent", "cancelled_sent", "released_exactly_once", "released_other")}, + "irreversible_released": sum( + r["undo"].get("irreversible_released", 0) for r in rounds + ), + "release_double_sends": sum( + (r["release"] or {}).get("double", 0) for r in rounds + ), + **{ + k: sum((r.get("mailbox") or {}).get(k, 0) for r in rounds) + for k in ( + "cancelled_never_sent", + "cancelled_sent", + "released_exactly_once", + "released_other", + ) + }, } acr = res.get("acrfence", {}) crash = res.get("crash", {}) - out["double_effects_through"] = sum(v["double_effects_through"] for v in acr.values()) + sum( - v["double_effects_through"] for v in crash.values()) + out["double_effects_through"] = sum( + v["double_effects_through"] for v in acr.values() + ) + sum(v["double_effects_through"] for v in crash.values()) out["blocked_double_effects"] = sum(v["blocked"] for v in acr.values()) out["control_duplicates"] = sum(v["control_duplicates"] for v in acr.values()) kills = [] m = out.get("mail") or {} if m.get("cancelled_sent") or m.get("released_other"): - kills.append("mail: a cancelled email was sent or a released one was not sent exactly once") + kills.append( + "mail: a cancelled email was sent or a released one was not sent exactly once" + ) for kind in ("rest", "sql"): k = out.get(kind) or {} if k.get("undo_success_rate") is not None and k["undo_success_rate"] < 0.95: diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index c63f45564e..4040f4827b 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -59,7 +59,11 @@ def _shape(diff: Mapping[str, Any]) -> tuple[Any, ...]: for rid in diff["added"]: t = rid.split("/", 1)[0] added[t] = added.get(t, 0) + 1 - return (sorted(added.items()), sorted(diff["removed"]), sorted((k, tuple(v)) for k, v in diff["changed"].items())) + return ( + sorted(added.items()), + sorted(diff["removed"]), + sorted((k, tuple(v)) for k, v in diff["changed"].items()), + ) # -- values -------------------------------------------------------------------- @@ -105,16 +109,27 @@ def same(a: Any, b: Any) -> bool: """Equal as values (``1`` and ``1.0`` are equal; ``"1"`` and ``1`` aren't; a datetime equals its ISO text).""" a, b = untag(a), untag(b) - if isinstance(a, (_dt.date, _dt.datetime)) or isinstance(b, (_dt.date, _dt.datetime)): + if isinstance(a, (_dt.date, _dt.datetime)) or isinstance( + b, (_dt.date, _dt.datetime) + ): + def text(v: Any) -> str: - return v.isoformat() if isinstance(v, (_dt.date, _dt.datetime)) else str(v).replace(" ", "T") + return ( + v.isoformat() + if isinstance(v, (_dt.date, _dt.datetime)) + else str(v).replace(" ", "T") + ) return text(a) == text(b) if isinstance(a, bool) or isinstance(b, bool): return a is b or a == b and type(a) is type(b) - if isinstance(a, (int, float, decimal.Decimal)) and isinstance(b, (int, float, decimal.Decimal)): + if isinstance(a, (int, float, decimal.Decimal)) and isinstance( + b, (int, float, decimal.Decimal) + ): return decimal.Decimal(str(a)) == decimal.Decimal(str(b)) - return json.dumps(a, sort_keys=True, default=str) == json.dumps(b, sort_keys=True, default=str) + return json.dumps(a, sort_keys=True, default=str) == json.dumps( + b, sort_keys=True, default=str + ) # -- diffs --------------------------------------------------------------------- @@ -133,10 +148,16 @@ def diff_frames( cols = sorted(c for c in set(a) | set(b) if a.get(c) != b.get(c)) if cols: changed[rid] = cols - return {"added": added, "removed": removed, "changed": dict(sorted(changed.items()))} + return { + "added": added, + "removed": removed, + "changed": dict(sorted(changed.items())), + } -def column_digests(record: Mapping[str, Any], drop: Sequence[str] = ()) -> dict[str, str]: +def column_digests( + record: Mapping[str, Any], drop: Sequence[str] = () +) -> dict[str, str]: return {k: digest(tag(v)) for k, v in record.items() if k not in drop} @@ -155,7 +176,9 @@ def __init__(self, system: RestSystem, client: Any = None) -> None: if system.auth is not None: secret = os.environ.get(system.auth.value_env, "") if not secret: - raise TxSpecError(f"system {system.name}: ${system.auth.value_env} is not set") + raise TxSpecError( + f"system {system.name}: ${system.auth.value_env} is not set" + ) headers[system.auth.header] = system.auth.prefix + secret self.http = client or httpx.Client( base_url=system.url(), headers=headers, timeout=system.timeout_s @@ -184,7 +207,9 @@ def _call( if key and self.system.idempotency_header: headers[self.system.idempotency_header] = key try: - resp = self.http.request(method, path, json=body, params=params, headers=headers) + resp = self.http.request( + method, path, json=body, params=params, headers=headers + ) except Exception as exc: # noqa: BLE001 - transport failure: delivery unknown raise AdapterError(f"{method} failed: {type(exc).__name__}") from exc if resp.status_code == 404 and method == "GET": @@ -215,7 +240,7 @@ def read(self, collection: Optional[str], rid: str) -> Optional[Record]: def frame(self, collection: Optional[str]) -> dict[str, dict[str, str]]: coll = self.coll(collection) - route = coll.list + route = coll.list_ out: dict[str, dict[str, str]] = {} page = 1 while True: @@ -240,18 +265,27 @@ def frame(self, collection: Optional[str]) -> dict[str, dict[str, str]]: if page > 10_000: raise AdapterError("the list never ended") - def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + def predict( + self, write: Mapping[str, Any], baseline: Optional[Record] + ) -> dict[str, Any]: coll = self.coll(write.get("collection")) fields = dict(write.get("fields") or {}) op = write["op"] if op == "create": - return {"added": {coll.name: 1}, "changed": {}, "removed": [], "derived": {}} + return { + "added": {coll.name: 1}, + "changed": {}, + "removed": [], + "derived": {}, + } rid = f"{coll.name}/{write['id']}" if op == "delete": return {"added": {}, "changed": {}, "removed": [rid], "derived": {}} base = baseline or {} cols = sorted( - k for k, v in fields.items() if k not in coll.server_fields and not same(base.get(k), v) + k + for k, v in fields.items() + if k not in coll.server_fields and not same(base.get(k), v) ) derived = sorted({d for c in cols for d in coll.derived.get(c, [])} - set(cols)) return { @@ -261,14 +295,22 @@ def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[ "derived": {rid: derived} if derived else {}, } - def _body(self, coll: Collection, route: Any, base: Optional[Record], fields: Mapping[str, Any]) -> Record: + def _body( + self, + coll: Collection, + route: Any, + base: Optional[Record], + fields: Mapping[str, Any], + ) -> Record: if route.replace and base is not None: body = {k: v for k, v in base.items() if k not in coll.server_fields} body.update(fields) return body return dict(fields) - def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) -> dict[str, Any]: + def apply( + self, write: Mapping[str, Any], baseline: Optional[Record], key: str + ) -> dict[str, Any]: coll = self.coll(write.get("collection")) op = write["op"] fields = dict(write.get("fields") or {}) @@ -290,7 +332,11 @@ def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) return {"id": str(write["id"])} def compensate( - self, write: Mapping[str, Any], baseline: Optional[Record], result: Mapping[str, Any], key: str + self, + write: Mapping[str, Any], + baseline: Optional[Record], + result: Mapping[str, Any], + key: str, ) -> None: coll = self.coll(write.get("collection")) op = write["op"] @@ -298,8 +344,12 @@ def compensate( if op == "create": route = coll.delete if route is None: - raise AdapterError(f"{coll.name} declares no delete, so a create can't be undone") - self._call(route.method, self._fill(route.path, {"id": rid}), key=key + ":undo") + raise AdapterError( + f"{coll.name} declares no delete, so a create can't be undone" + ) + self._call( + route.method, self._fill(route.path, {"id": rid}), key=key + ":undo" + ) return if op == "update": route = coll.update @@ -311,7 +361,10 @@ def compensate( else {k: baseline.get(k) for k in changed} ) self._call( - route.method, self._fill(route.path, {**baseline, "id": rid}), restore, key=key + ":undo" + route.method, + self._fill(route.path, {**baseline, "id": rid}), + restore, + key=key + ":undo", ) return raise AdapterError(f"no exact undo for a REST {op}") @@ -323,7 +376,11 @@ def expected_after( if write["op"] == "delete": return None coll = self.coll(write.get("collection")) - return {k: v for k, v in (write.get("fields") or {}).items() if k not in coll.server_fields} + return { + k: v + for k, v in (write.get("fields") or {}).items() + if k not in coll.server_fields + } def frame_id(self, write: Mapping[str, Any], result: Mapping[str, Any]) -> str: return f"{write.get('collection')}/{result.get('id') or write.get('id')}" @@ -398,14 +455,18 @@ def _ident(self, name: str) -> str: def _tables(self, cur: Any) -> list[str]: d = self.system.dialect if d == "sqlite": - cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") + cur.execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" + ) elif d == "mysql": cur.execute( "SELECT table_name FROM information_schema.tables " "WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'" ) else: - cur.execute("SELECT tablename FROM pg_tables WHERE schemaname = current_schema()") + cur.execute( + "SELECT tablename FROM pg_tables WHERE schemaname = current_schema()" + ) names = sorted(str(r[0]) for r in cur.fetchall()) return [n for n in names if n not in self.system.frame_ignore_tables] @@ -457,7 +518,11 @@ def frame_cur( seen: dict[str, int] = {} for row in rows: rec = dict(zip(cols, row)) - digs = {c: digest(tag(v)) for c, v in rec.items() if not self._ignored(table, c)} + digs = { + c: digest(tag(v)) + for c, v in rec.items() + if not self._ignored(table, c) + } if pk and all(c in rec for c in pk): rid = "|".join(str(rec[c]) for c in pk) else: # no key: the whole row is its identity @@ -467,7 +532,8 @@ def frame_cur( out[f"{table}/{rid}"] = digs if rows_out is not None: rows_out[f"{table}/{rid}"] = { - "pk": pk, "row": {c: tag(v) for c, v in rec.items()} + "pk": pk, + "row": {c: tag(v) for c, v in rec.items()}, } return out @@ -488,7 +554,8 @@ def _read_cur(self, cur: Any, table: str, rid: str) -> Optional[Record]: if key is None: raise AdapterError(f"table {table} is not declared") cur.execute( - f"SELECT * FROM {self._ident(table)} WHERE {self._ident(key)} = {self.ph}", (rid,) + f"SELECT * FROM {self._ident(table)} WHERE {self._ident(key)} = {self.ph}", + (rid,), ) cols = [str(d[0]) for d in cur.description] rows = cur.fetchall() @@ -513,7 +580,9 @@ def normalize(self, coll: Any, record: Mapping[str, Any]) -> Record: # writing ---------------------------------------------------------------- - def _exec(self, cur: Any, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + def _exec( + self, cur: Any, write: Mapping[str, Any], baseline: Optional[Record] + ) -> dict[str, Any]: table = str(write["collection"]) key = self.system.tables.get(table) if key is None and write["op"] != "sql": @@ -523,6 +592,7 @@ def _exec(self, cur: Any, write: Mapping[str, Any], baseline: Optional[Record]) cur.execute(str((write.get("fields") or {})["sql"])) return {"rows": max(0, int(cur.rowcount or 0))} fields = {k: untag(v) for k, v in (write.get("fields") or {}).items()} + assert key is not None t = self._ident(table) if op == "create": cols = list(fields) @@ -551,7 +621,9 @@ def _exec(self, cur: Any, write: Mapping[str, Any], baseline: Optional[Record]) cur.execute(f"DELETE FROM {t} WHERE {self._ident(key)} = {self.ph}", (rid,)) else: raise AdapterError(f"no SQL {op}") - if cur.rowcount != 1 and not (op == "update" and self.system.dialect == "mysql"): + if cur.rowcount != 1 and not ( + op == "update" and self.system.dialect == "mysql" + ): raise AdapterError(f"the {op} touched {cur.rowcount} rows, not one") return {"id": rid} @@ -577,7 +649,10 @@ def stage( result["staged_diff"] = diff_frames(prev, now_) result["before_rows"] = { rid: rows[rid]["row"] - for rid in [*result["staged_diff"]["removed"], *result["staged_diff"]["changed"]] + for rid in [ + *result["staged_diff"]["removed"], + *result["staged_diff"]["changed"], + ] if rid in rows } prev = now_ @@ -589,10 +664,14 @@ def stage( con.close() return diff_frames(before, after), results - def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + def predict( + self, write: Mapping[str, Any], baseline: Optional[Record] + ) -> dict[str, Any]: raise NotImplementedError("SQL plans are staged as one transaction") - def apply(self, write: Mapping[str, Any], baseline: Optional[Record], key: str) -> dict[str, Any]: + def apply( + self, write: Mapping[str, Any], baseline: Optional[Record], key: str + ) -> dict[str, Any]: if write["op"] == "sql": return self._apply_sql(write) con = self.connect() @@ -628,9 +707,13 @@ def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: diff = diff_frames(before, after) if _shape(diff) != _shape(want): con.rollback() - raise Diverged("the statement's diff is not the planned diff; rolled back") + raise Diverged( + "the statement's diff is not the planned diff; rolled back" + ) images = { - "before": {r: rows[r] for r in [*diff["removed"], *diff["changed"]]}, + "before": { + r: rows[r] for r in [*diff["removed"], *diff["changed"]] + }, "after": {r: after[r] for r in [*diff["added"], *diff["changed"]]}, "added_pk": {r: after_rows[r] for r in diff["added"]}, } @@ -679,7 +762,9 @@ def compensate_sql(self, images: Mapping[str, Any]) -> None: cur.execute(f"ROLLBACK TO SAVEPOINT {sp}") failed.append(step) if len(failed) == len(left): - raise AdapterError(f"{len(failed)} row(s) could not be restored") + raise AdapterError( + f"{len(failed)} row(s) could not be restored" + ) left = failed except Exception: con.rollback() @@ -694,7 +779,10 @@ def _restore_row(self, cur: Any, rid: str, item: Mapping[str, Any]) -> None: if not pk: raise AdapterError(f"{table} has no primary key: no generated undo") where = " AND ".join(f"{self._ident(c)} = {self.ph}" for c in pk) - cur.execute(f"SELECT 1 FROM {self._ident(table)} WHERE {where}", tuple(untag(row[c]) for c in pk)) + cur.execute( + f"SELECT 1 FROM {self._ident(table)} WHERE {where}", + tuple(untag(row[c]) for c in pk), + ) if cur.fetchall(): cols = [c for c in row if c not in pk] if cols: @@ -717,15 +805,24 @@ def _delete_row(self, cur: Any, rid: str, item: Mapping[str, Any]) -> None: if not pk: raise AdapterError(f"{table} has no primary key: no generated undo") where = " AND ".join(f"{self._ident(c)} = {self.ph}" for c in pk) - cur.execute(f"DELETE FROM {self._ident(table)} WHERE {where}", tuple(untag(row[c]) for c in pk)) + cur.execute( + f"DELETE FROM {self._ident(table)} WHERE {where}", + tuple(untag(row[c]) for c in pk), + ) - def current_digests(self, rids: Sequence[str]) -> dict[str, Optional[dict[str, str]]]: + def current_digests( + self, rids: Sequence[str] + ) -> dict[str, Optional[dict[str, str]]]: """The current column digests of some frame rows (None when gone).""" frame = self.frame() return {r: frame.get(r) for r in rids} def compensate( - self, write: Mapping[str, Any], baseline: Optional[Record], result: Mapping[str, Any], key: str + self, + write: Mapping[str, Any], + baseline: Optional[Record], + result: Mapping[str, Any], + key: str, ) -> None: op = write["op"] rid = str(result.get("id") or write.get("id")) @@ -738,12 +835,23 @@ def compensate( # same row) is restored too, by naming its old value explicitly. current = self.read(write["collection"], rid) or {} fields = { - k: v for k, v in baseline.items() if k in current and not same(current.get(k), v) + k: v + for k, v in baseline.items() + if k in current and not same(current.get(k), v) } or {k: baseline.get(k) for k in (write.get("fields") or {})} - inverse = {"op": "update", "collection": write["collection"], "id": rid, "fields": fields} + inverse = { + "op": "update", + "collection": write["collection"], + "id": rid, + "fields": fields, + } elif op == "delete": assert baseline is not None - inverse = {"op": "create", "collection": write["collection"], "fields": dict(baseline)} + inverse = { + "op": "create", + "collection": write["collection"], + "fields": dict(baseline), + } else: raise AdapterError(f"no SQL undo for {op}") self.apply(inverse, None, key + ":undo") @@ -780,7 +888,9 @@ def _messages(self) -> list[dict[str, Any]]: out: list[dict[str, Any]] = [] start = 0 while True: - resp = self.http.get("/api/v1/messages", params={"start": start, "limit": 250}) + resp = self.http.get( + "/api/v1/messages", params={"start": start, "limit": 250} + ) if resp.status_code >= 400: raise AdapterError(f"the mailbox returned {resp.status_code}") page = resp.json().get("messages") or [] @@ -803,12 +913,24 @@ def frame(self, collection: Optional[str] = None) -> dict[str, dict[str, str]]: def count(self, key: str) -> int: mid = self.message_id(key).strip("<>") - return sum(1 for m in self._messages() if str(m.get("MessageID", "")).strip("<>") == mid) + return sum( + 1 + for m in self._messages() + if str(m.get("MessageID", "")).strip("<>") == mid + ) - def predict(self, write: Mapping[str, Any], baseline: Optional[Record]) -> dict[str, Any]: + def predict( + self, write: Mapping[str, Any], baseline: Optional[Record] + ) -> dict[str, Any]: return {"added": {}, "changed": {}, "removed": [], "derived": {}, "queued": 1} - def send(self, write: Mapping[str, Any], key: str, *, smtp_factory: Optional[Callable[..., Any]] = None) -> None: + def send( + self, + write: Mapping[str, Any], + key: str, + *, + smtp_factory: Optional[Callable[..., Any]] = None, + ) -> None: import smtplib from email.message import EmailMessage @@ -823,7 +945,9 @@ def send(self, write: Mapping[str, Any], key: str, *, smtp_factory: Optional[Cal msg.set_content(str(fields.get("body", ""))) factory = smtp_factory or smtplib.SMTP try: - with factory(self.system.smtp.host, self.system.smtp.port, timeout=20) as smtp: + with factory( + self.system.smtp.host, self.system.smtp.port, timeout=20 + ) as smtp: smtp.send_message(msg) except Exception as exc: # noqa: BLE001 - delivery unknown raise AdapterError(f"SMTP failed: {type(exc).__name__}") from exc diff --git a/packages/flow/openadapt_flow/txplan/cli.py b/packages/flow/openadapt_flow/txplan/cli.py index d5de556154..c6062c04e2 100644 --- a/packages/flow/openadapt_flow/txplan/cli.py +++ b/packages/flow/openadapt_flow/txplan/cli.py @@ -46,13 +46,29 @@ def _fill(p: argparse.ArgumentParser) -> None: def common(q: argparse.ArgumentParser, tx: bool = True) -> None: if tx: - q.add_argument("--tx", default="openadapt.tx.yaml", help="the tx file (default: ./openadapt.tx.yaml)") - q.add_argument("--state", help="the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)") + q.add_argument( + "--tx", + default="openadapt.tx.yaml", + help="the tx file (default: ./openadapt.tx.yaml)", + ) + q.add_argument( + "--state", + help="the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)", + ) q.add_argument("--json", action="store_true", help="print JSON") - q = verbs.add_parser("create", help="read the baseline and print the predicted diff") - q.add_argument("--task", required=True, help="the task this batch belongs to (OpenAdapt's id, not the model's)") - q.add_argument("writes", help="a JSON file: a list of writes, or {\"writes\": [...]}; - for stdin") + q = verbs.add_parser( + "create", help="read the baseline and print the predicted diff" + ) + q.add_argument( + "--task", + required=True, + help="the task this batch belongs to (OpenAdapt's id, not the model's)", + ) + q.add_argument( + "writes", + help='a JSON file: a list of writes, or {"writes": [...]}; - for stdin', + ) common(q) for verb, text in ( ("show", "print a plan"), @@ -64,9 +80,13 @@ def common(q: argparse.ArgumentParser, tx: bool = True) -> None: q = verbs.add_parser(verb, help=text) q.add_argument("plan", help="a plan digest or its prefix") common(q, tx=verb not in ("show", "cancel")) - q = verbs.add_parser("approve", help="approve one plan digest, once (a person at a terminal)") + q = verbs.add_parser( + "approve", help="approve one plan digest, once (a person at a terminal)" + ) q.add_argument("plan") - q.add_argument("--as", dest="approver", default=None, help="who approves (default: $USER)") + q.add_argument( + "--as", dest="approver", default=None, help="who approves (default: $USER)" + ) q.add_argument( "--automation", action="store_true", @@ -104,12 +124,22 @@ def cmd_plan(args: argparse.Namespace) -> int: print(json.dumps(out, indent=2, sort_keys=True)) return 0 if verb == "create": - raw = sys.stdin.read() if args.writes == "-" else Path(args.writes).read_text(encoding="utf-8") + raw = ( + sys.stdin.read() + if args.writes == "-" + else Path(args.writes).read_text(encoding="utf-8") + ) data = json.loads(raw) writes = data.get("writes") if isinstance(data, dict) else data plan = engine.make_plan(ctx, args.task, writes or []) if args.json: - print(json.dumps({k: v for k, v in plan.items() if k != "anomaly_details"}, indent=2, sort_keys=True)) + print( + json.dumps( + {k: v for k, v in plan.items() if k != "anomaly_details"}, + indent=2, + sort_keys=True, + ) + ) else: print("\n".join(engine.summary_lines(plan))) print(f"approve: openadapt plan approve {plan['digest'][:16]}") @@ -118,38 +148,66 @@ def cmd_plan(args: argparse.Namespace) -> int: if verb == "show": plan, priv = engine.load_plan(ctx.state, digest) plan["anomaly_details"] = priv.get("anomalies", []) - print(json.dumps(plan, indent=2, sort_keys=True) if args.json else "\n".join(engine.summary_lines(plan))) + print( + json.dumps(plan, indent=2, sort_keys=True) + if args.json + else "\n".join(engine.summary_lines(plan)) + ) return 0 if verb == "approve": if args.automation: decided_by = "automation" else: if not (sys.stdin.isatty() and sys.stdout.isatty()): - print("approve needs a person at a terminal (or --automation for a lab run)", file=sys.stderr) + print( + "approve needs a person at a terminal (or --automation for a lab run)", + file=sys.stderr, + ) return 2 plan, priv = engine.load_plan(ctx.state, digest) plan["anomaly_details"] = priv.get("anomalies", []) print("\n".join(engine.summary_lines(plan))) - typed = input(f"Type the first 8 characters of the plan digest ({digest[:4]}...) to approve: ") + typed = input( + f"Type the first 8 characters of the plan digest ({digest[:4]}...) to approve: " + ) if typed.strip() != digest[:8]: print("not approved", file=sys.stderr) return 1 decided_by = "human" approver = args.approver or os.environ.get("USER") or "unknown" - engine.approve_plan(ctx.state, digest, approver=approver, decided_by=decided_by) + engine.approve_plan( + ctx.state, digest, approver=approver, decided_by=decided_by + ) print(f"approved plan {digest[:12]} once") return 0 - fn = {"apply": engine.apply_plan, "undo": engine.undo_plan, "release": engine.release}.get(verb) + fn = { + "apply": engine.apply_plan, + "undo": engine.undo_plan, + "release": engine.release, + }.get(verb) if verb == "cancel": n = engine.cancel(ctx, digest) print(f"cancelled {n} held write(s)") return 0 assert fn is not None result = fn(ctx, digest) - print(json.dumps({k: result[k] for k in ("outcome", "tx", "run_dir")}, indent=2, sort_keys=True)) - return 0 if result["outcome"] in ("VERIFIED", "ROLLED_BACK", "COMPLETED_UNVERIFIED") else 1 + print( + json.dumps( + {k: result[k] for k in ("outcome", "tx", "run_dir")}, + indent=2, + sort_keys=True, + ) + ) + return ( + 0 + if result["outcome"] in ("VERIFIED", "ROLLED_BACK", "COMPLETED_UNVERIFIED") + else 1 + ) except engine.TxRefused as exc: - print(f"refused: {exc.code}" + (f" ({exc.detail})" if exc.detail else ""), file=sys.stderr) + print( + f"refused: {exc.code}" + (f" ({exc.detail})" if exc.detail else ""), + file=sys.stderr, + ) if exc.report: print(json.dumps(exc.report, indent=2, sort_keys=True)) return 3 diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index f3e59086f1..8cbcddfe7d 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -34,7 +34,13 @@ diff_frames, same, ) -from openadapt_flow.txplan.spec import Collection, MailSystem, RestSystem, SqlSystem, TxSpec +from openadapt_flow.txplan.spec import ( + Collection, + MailSystem, + RestSystem, + SqlSystem, + TxSpec, +) from openadapt_flow.txplan.state import ( State, StateError, @@ -50,14 +56,18 @@ OPS = ("create", "update", "delete", "send", "sql") #: Ledger states after which a key is free again. FREE = ("undone", "cancelled", "refused") -_DDL = re.compile(r"^\s*(create|alter|drop|truncate|rename|comment|grant|revoke)\b", re.I) +_DDL = re.compile( + r"^\s*(create|alter|drop|truncate|rename|comment|grant|revoke)\b", re.I +) _READ = re.compile(r"^\s*(select|with|show|explain|pragma|values)\b", re.I) #: Test hook: exit right after the Nth send, before its outcome is recorded. CRASH_ENV = "OPENADAPT_TX_CRASH_AFTER_SEND" class TxRefused(RuntimeError): - def __init__(self, code: str, detail: str = "", report: Optional[dict] = None) -> None: + def __init__( + self, code: str, detail: str = "", report: Optional[dict] = None + ) -> None: super().__init__(f"{code}: {detail}" if detail else code) self.code = code self.detail = detail @@ -75,17 +85,25 @@ def _scope(write: Mapping[str, Any], system: Any) -> str: def _coll(system: Any, write: Mapping[str, Any]) -> Optional[Collection]: - return system.collection(write.get("collection")) if isinstance(system, RestSystem) else None + return ( + system.collection(write.get("collection")) + if isinstance(system, RestSystem) + else None + ) def _irreversible(system: Any, write: Mapping[str, Any]) -> bool: if isinstance(system, MailSystem): return True coll = _coll(system, write) - return bool(coll is not None and write["op"] == "delete" and not coll.delete_reversible) + return bool( + coll is not None and write["op"] == "delete" and not coll.delete_reversible + ) -def _norm(system: Any, write: Mapping[str, Any], record: Optional[Mapping[str, Any]]) -> Optional[dict]: +def _norm( + system: Any, write: Mapping[str, Any], record: Optional[Mapping[str, Any]] +) -> Optional[dict]: if record is None: return None coll = _coll(system, write) @@ -142,7 +160,9 @@ def compare(predicted: Mapping[str, Any], actual: Mapping[str, Any]) -> dict[str missed += [f"{coll}/+new"] * max(0, extra) false += [f"{coll}/+new"] * max(0, -extra) for rid, cols in actual["changed"].items(): - allowed = set(predicted["changed"].get(rid, [])) | set(predicted["derived"].get(rid, [])) + allowed = set(predicted["changed"].get(rid, [])) | set( + predicted["derived"].get(rid, []) + ) if set(cols) - allowed: missed.append(rid) for rid, cols in predicted["changed"].items(): @@ -179,8 +199,14 @@ def _spec_sha(spec: TxSpec) -> str: # -- receipts ------------------------------------------------------------------ -def _approval_block(approval: Optional[Mapping[str, Any]], digest: str) -> dict[str, Any]: - block: dict[str, Any] = {"schema": "openadapt.approval-mode-item/v1", "mode": "each_item", "approvals": []} +def _approval_block( + approval: Optional[Mapping[str, Any]], digest: str +) -> dict[str, Any]: + block: dict[str, Any] = { + "schema": "openadapt.approval-mode-item/v1", + "mode": "each_item", + "approvals": [], + } if approval: block["approvals"].append( { @@ -223,8 +249,14 @@ def _write_run( "results": results, "approval": _approval_block(approval, digest), "outcome_envelope": { - "required_contracts": {"effect": len(writes), "authorization": 1 if approval else 0}, - "passed_contracts": {"effect": confirmed, "authorization": 1 if approval else 0}, + "required_contracts": { + "effect": len(writes), + "authorization": 1 if approval else 0, + }, + "passed_contracts": { + "effect": confirmed, + "authorization": 1 if approval else 0, + }, }, "tx": dict(tx), } @@ -237,7 +269,10 @@ def _write_run( write_receipt_record(run_dir, signer=signer_for(seal_home())) except Exception as exc: # noqa: BLE001 - the outcome stands without it - write_private(run_dir / "receipt.error.json", {"error": f"{type(exc).__name__}: {exc}"}) + write_private( + run_dir / "receipt.error.json", + {"error": f"{type(exc).__name__}: {exc}"}, + ) return run_dir @@ -267,15 +302,23 @@ def _counts(diff: Optional[Mapping[str, Any]]) -> Optional[dict[str, Any]]: out: dict[str, dict[str, int]] = {} for what in ("added", "removed"): for rid in diff[what]: - t = out.setdefault(rid.split("/", 1)[0], {"added": 0, "changed": 0, "removed": 0}) + t = out.setdefault( + rid.split("/", 1)[0], {"added": 0, "changed": 0, "removed": 0} + ) t[what] += 1 for rid in diff["changed"]: - t = out.setdefault(rid.split("/", 1)[0], {"added": 0, "changed": 0, "removed": 0}) + t = out.setdefault( + rid.split("/", 1)[0], {"added": 0, "changed": 0, "removed": 0} + ) t["changed"] += 1 return out -def _row_anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], rows: Mapping[int, Mapping[str, Any]]) -> list[dict[str, Any]]: +def _row_anomalies( + spec: TxSpec, + writes: Sequence[Mapping[str, Any]], + rows: Mapping[int, Mapping[str, Any]], +) -> list[dict[str, Any]]: """Blast-radius and row-value rules, from the staged transaction's rows.""" found = [] touched = sum( @@ -285,19 +328,35 @@ def _row_anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], rows: Mapp ) for rule in spec.anomalies: if rule.max_rows is not None and touched > rule.max_rows: - found.append({"label": rule.label, "write": None, "detail": "rows", "value": touched}) + found.append( + {"label": rule.label, "write": None, "detail": "rows", "value": touched} + ) if rule.table and rule.column: hits = sum( 1 for n, before in rows.items() for rid, row in before.items() - if rid.split("/", 1)[0] == rule.table and same(row.get(rule.column), rule.equals) + if rid.split("/", 1)[0] == rule.table + and same(row.get(rule.column), rule.equals) ) if hits: - found.append({"label": rule.label, "write": None, "detail": f"{rule.table}.{rule.column}", "value": hits}) + found.append( + { + "label": rule.label, + "write": None, + "detail": f"{rule.table}.{rule.column}", + "value": hits, + } + ) for n, w in enumerate(writes): if w.get("ddl"): - found.append({"label": "schema change: no generated undo", "write": n, "detail": "ddl"}) + found.append( + { + "label": "schema change: no generated undo", + "write": n, + "detail": "ddl", + } + ) return found @@ -308,7 +367,14 @@ def _row_digests(adapter: Any, rid: str, row: Mapping[str, Any]) -> dict[str, st return {c: _d(v) for c, v in row.items() if not adapter._ignored(table, c)} -def _undo_sql(state: State, adapter: Any, w: Mapping[str, Any], entry: Any, images: Any, digest: str) -> str: +def _undo_sql( + state: State, + adapter: Any, + w: Mapping[str, Any], + entry: Any, + images: Any, + digest: str, +) -> str: if w.get("ddl") or not images: return "no_undo" rids = [*images.get("after", {}), *images.get("before", {})] @@ -323,11 +389,18 @@ def _undo_sql(state: State, adapter: Any, w: Mapping[str, Any], entry: Any, imag try: adapter.compensate_sql(images) except AdapterError as exc: - state.record(w["key"], "uncertain", plan=digest, payload=entry.payload, reason=f"undo: {exc}"[:120]) + state.record( + w["key"], + "uncertain", + plan=digest, + payload=entry.payload, + reason=f"undo: {exc}"[:120], + ) return "undo_failed" now_ = adapter.current_digests(rids + list(images.get("added_pk", {}))) ok = all(now_.get(r) is None for r in images.get("added_pk", {})) and all( - now_.get(r) == _row_digests(adapter, r, item["row"]) for r, item in images.get("before", {}).items() + now_.get(r) == _row_digests(adapter, r, item["row"]) + for r, item in images.get("before", {}).items() ) state.record(w["key"], "undone", plan=digest, payload=entry.payload, read_back=ok) return "undone" if ok else "undo_refuted" @@ -345,32 +418,56 @@ def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: raise TxRefused("bad_write", f"write {n}: op must be one of {OPS}") if op == "sql": if not isinstance(system, SqlSystem): - raise TxRefused("bad_write", f"write {n}: a SQL statement needs a sql system") - sql = (w.get("fields") or {}).get("sql") if isinstance(w.get("fields"), Mapping) else None + raise TxRefused( + "bad_write", f"write {n}: a SQL statement needs a sql system" + ) + sql = ( + (w.get("fields") or {}).get("sql") + if isinstance(w.get("fields"), Mapping) + else None + ) if not isinstance(sql, str) or not sql.strip(): raise TxRefused("bad_write", f"write {n}: sql needs fields.sql") sql = sql.strip().rstrip(";").strip() if ";" in sql: raise TxRefused("bad_write", f"write {n}: one statement per write") if _READ.match(sql): - raise TxRefused("bad_write", f"write {n}: a read is not a write (use a query)") + raise TxRefused( + "bad_write", f"write {n}: a read is not a write (use a query)" + ) ddl = bool(_DDL.match(sql)) if ddl and system.dialect == "mysql": - raise TxRefused("bad_write", f"write {n}: MySQL commits DDL at once, so it can't be staged") - return {"system": system.name, "collection": "statement", "op": "sql", "id": None, - "fields": {"sql": sql}, "label": str(w.get("label") or "")[:80], "ddl": ddl} + raise TxRefused( + "bad_write", + f"write {n}: MySQL commits DDL at once, so it can't be staged", + ) + return { + "system": system.name, + "collection": "statement", + "op": "sql", + "id": None, + "fields": {"sql": sql}, + "label": str(w.get("label") or "")[:80], + "ddl": ddl, + } if isinstance(system, MailSystem) != (op == "send"): - raise TxRefused("bad_write", f"write {n}: {op} doesn't fit a {system.kind} system") + raise TxRefused( + "bad_write", f"write {n}: {op} doesn't fit a {system.kind} system" + ) if isinstance(system, RestSystem): coll = system.collection(w.get("collection")) if getattr(coll, op) is None: raise TxRefused("bad_write", f"write {n}: {coll.name} declares no {op}") if isinstance(system, SqlSystem) and w.get("collection") not in system.tables: - raise TxRefused("bad_write", f"write {n}: table {w.get('collection')!r} is not declared") + raise TxRefused( + "bad_write", f"write {n}: table {w.get('collection')!r} is not declared" + ) if op in ("update", "delete") and w.get("id") in (None, ""): raise TxRefused("bad_write", f"write {n}: {op} needs id") if op in ("create", "send") and w.get("id") not in (None, ""): - raise TxRefused("bad_write", f"write {n}: {op} takes no id (the slot is its ordinal)") + raise TxRefused( + "bad_write", f"write {n}: {op} takes no id (the slot is its ordinal)" + ) if op != "delete" and not isinstance(w.get("fields"), Mapping): raise TxRefused("bad_write", f"write {n}: {op} needs fields") return { @@ -383,7 +480,9 @@ def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: } -def _anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], baselines: Sequence[Any]) -> list[dict[str, Any]]: +def _anomalies( + spec: TxSpec, writes: Sequence[Mapping[str, Any]], baselines: Sequence[Any] +) -> list[dict[str, Any]]: found: list[dict[str, Any]] = [] for rule in spec.anomalies: if rule.max_writes is None and not (rule.field or rule.op or rule.clears): @@ -391,7 +490,9 @@ def _anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], baselines: Seq if rule.max_writes is not None: if len(writes) <= rule.max_writes: continue - found.append({"label": rule.label, "write": None, "detail": f"{len(writes)} writes"}) + found.append( + {"label": rule.label, "write": None, "detail": f"{len(writes)} writes"} + ) continue for n, (w, base) in enumerate(zip(writes, baselines)): if rule.op is not None and w["op"] != rule.op: @@ -407,16 +508,24 @@ def _anomalies(spec: TxSpec, writes: Sequence[Mapping[str, Any]], baselines: Seq continue except (TypeError, ValueError): continue - if rule.clears and not ((base or {}).get(rule.field) not in (None, "") and value in (None, "")): + if rule.clears and not ( + (base or {}).get(rule.field) not in (None, "") + and value in (None, "") + ): continue elif rule.clears: if not any( - (base or {}).get(k) not in (None, "") and v in (None, "") for k, v in fields.items() + (base or {}).get(k) not in (None, "") and v in (None, "") + for k, v in fields.items() ): continue found.append( - {"label": rule.label, "write": n, "detail": rule.field or w["op"], - "value": fields.get(rule.field) if rule.field else None} + { + "label": rule.label, + "write": n, + "detail": rule.field or w["op"], + "value": fields.get(rule.field) if rule.field else None, + } ) return found @@ -465,15 +574,27 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str slots[i] = "insert:" + ",".join(tables) if tables else "noop" for w, slot in zip(writes, slots): if w["op"] in ("update", "delete"): - dup = [x for x in writes if x is not w and x["system"] == w["system"] - and x["collection"] == w["collection"] and x["id"] == w["id"]] + dup = [ + x + for x in writes + if x is not w + and x["system"] == w["system"] + and x["collection"] == w["collection"] + and x["id"] == w["id"] + ] if dup: raise TxRefused("bad_write", "a plan writes each record once") w["slot"] = slot w["key"] = state.key_for( - task=task, system=w["system"], collection=str(w["collection"]), op=w["op"], slot=slot + task=task, + system=w["system"], + collection=str(w["collection"]), + op=w["op"], + slot=slot, + ) + w["payload_sha256"] = sha256( + {"op": w["op"], "fields": w["fields"], "id": w["id"]} ) - w["payload_sha256"] = sha256({"op": w["op"], "fields": w["fields"], "id": w["id"]}) w["irreversible"] = _irreversible(spec.system(w["system"]), w) # The ledger first: a key already used under another payload is a replay. replays = [] @@ -481,19 +602,25 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str entry = state.entry(w["key"]) w["ledger"] = "free" if entry is not None and entry.status not in FREE: - w["ledger"] = "replay" if entry.payload == w["payload_sha256"] else "replay_mismatch" + w["ledger"] = ( + "replay" if entry.payload == w["payload_sha256"] else "replay_mismatch" + ) if w["ledger"] == "replay_mismatch" and w["op"] == "sql": # A raw statement's identity is the rows it touches, which new work # can share: a person decides, and policy never approves it. w["ledger"] = "possible_replay" - replays.append({"write": n, "status": w["ledger"], "prior_plan": entry.plan[:12]}) + replays.append( + {"write": n, "status": w["ledger"], "prior_plan": entry.plan[:12]} + ) baselines: list[Optional[dict]] = [] for w in writes: base = None if w["op"] in ("update", "delete"): base = ctx.adapter(w["system"]).read(w["collection"], w["id"]) if base is None and w["ledger"] == "free": - raise TxRefused("record_missing", f"{w['system']} {w['collection']} {w['id']}") + raise TxRefused( + "record_missing", f"{w['system']} {w['collection']} {w['id']}" + ) baselines.append(base) scopes = [_scope(w, spec.system(w["system"])) for w in writes] frames = ctx.frames(scopes) @@ -514,7 +641,9 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str else: _merge(predicted[scope], adapter.predict(w, base)) for name, idx in staged.items(): - diff, results = ctx.adapter(name).stage([writes[i] for i in idx], [baselines[i] for i in idx]) + diff, results = ctx.adapter(name).stage( + [writes[i] for i in idx], [baselines[i] for i in idx] + ) _merge(predicted[f"{name}:*"], _staged_to_prediction(diff)) for i, res in zip(idx, results): if writes[i]["op"] == "sql": @@ -523,33 +652,56 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str staged_rows[i] = res.get("before_rows", {}) summary: dict[str, int] = {} for w in writes: - verb = {"create": "created", "update": "updated", "delete": "deleted", "send": "queued", - "sql": "statements"}[w["op"]] + verb = { + "create": "created", + "update": "updated", + "delete": "deleted", + "send": "queued", + "sql": "statements", + }[w["op"]] if w["irreversible"] and w["op"] == "delete": verb = "deleted after holdback" - k = f"SQL statement(s) on {w['system']}" if w["op"] == "sql" else f"{w['system']}.{w['collection']} {verb}" + k = ( + f"SQL statement(s) on {w['system']}" + if w["op"] == "sql" + else f"{w['system']}.{w['collection']} {verb}" + ) summary[k] = summary.get(k, 0) + 1 anomalies = _anomalies(spec, writes, baselines) anomalies += _row_anomalies(spec, writes, staged_rows) for r in replays: if r["status"] == "possible_replay": anomalies.append( - {"label": "possible replay: this task already wrote these rows (or this table) with another statement", "write": r["write"], "detail": "possible_replay"} + { + "label": "possible replay: this task already wrote these rows (or this table) with another statement", + "write": r["write"], + "detail": "possible_replay", + } ) if r["status"] == "replay_mismatch": anomalies.append( - {"label": "replays an applied write with a different payload", "write": r["write"], "detail": "replay_mismatch"} + { + "label": "replays an applied write with a different payload", + "write": r["write"], + "detail": "replay_mismatch", + } ) for scope, pred in predicted.items(): name = scope.split(":", 1)[0] if isinstance(spec.system(name), SqlSystem): declared = set(spec.system(name).tables) # type: ignore[union-attr] - other = {rid.split("/", 1)[0] for rid in pred["changed"]} | set(pred["added"]) | { - rid.split("/", 1)[0] for rid in pred["removed"] - } + other = ( + {rid.split("/", 1)[0] for rid in pred["changed"]} + | set(pred["added"]) + | {rid.split("/", 1)[0] for rid in pred["removed"]} + ) if declared and other - declared: anomalies.append( - {"label": "side effects in undeclared tables", "write": None, "detail": str(len(other - declared))} + { + "label": "side effects in undeclared tables", + "write": None, + "detail": str(len(other - declared)), + } ) core = { "schema_version": PLAN_SCHEMA, @@ -560,8 +712,25 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str "holdback_s": spec.holdback_s, "writes": [ { - **{k: w[k] for k in ("system", "collection", "op", "id", "slot", "key", "payload_sha256", "irreversible", "ledger")}, - **({"ddl": w["ddl"], "staged_diff": _counts(w.get("staged_diff"))} if w["op"] == "sql" else {}), + **{ + k: w[k] + for k in ( + "system", + "collection", + "op", + "id", + "slot", + "key", + "payload_sha256", + "irreversible", + "ledger", + ) + }, + **( + {"ddl": w["ddl"], "staged_diff": _counts(w.get("staged_diff"))} + if w["op"] == "sql" + else {} + ), } for w in writes ], @@ -578,19 +747,33 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str write_private(pdir / "plan.json", {**core, "digest": digest}) write_private( pdir / "private.json", - {"writes": writes, "baselines": baselines, "frames": frames, "anomalies": anomalies}, + { + "writes": writes, + "baselines": baselines, + "frames": frames, + "anomalies": anomalies, + }, ) tx = { "phase": "plan", "writes": len(writes), "queued": queued, "replays": sum(1 for r in replays if r["status"] == "replay"), - "replay_mismatches": sum(1 for r in replays if r["status"] == "replay_mismatch"), + "replay_mismatches": sum( + 1 for r in replays if r["status"] == "replay_mismatch" + ), "anomalies": len(anomalies), "dry_run": sorted(set(dry_run.values())), } run = _write_run( - state, digest, "plan", outcome="COMPLETED_UNVERIFIED", results=[], tx=tx, approval=None, started=started + state, + digest, + "plan", + outcome="COMPLETED_UNVERIFIED", + results=[], + tx=tx, + approval=None, + started=started, ) return {**core, "digest": digest, "run_dir": str(run), "anomaly_details": anomalies} @@ -602,7 +785,9 @@ def load_plan(state: State, digest: str) -> tuple[dict[str, Any], dict[str, Any] return read_json(pdir / "plan.json"), read_json(pdir / "private.json") -def approve_plan(state: State, digest: str, *, approver: str, decided_by: str) -> dict[str, Any]: +def approve_plan( + state: State, digest: str, *, approver: str, decided_by: str +) -> dict[str, Any]: load_plan(state, digest) return state.approve(digest, approver=approver, decided_by=decided_by) @@ -610,7 +795,9 @@ def approve_plan(state: State, digest: str, *, approver: str, decided_by: str) - # -- apply --------------------------------------------------------------------- -def _readback(ctx: Ctx, w: Mapping[str, Any], base: Any, result: Mapping[str, Any]) -> tuple[Optional[bool], Optional[dict]]: +def _readback( + ctx: Ctx, w: Mapping[str, Any], base: Any, result: Mapping[str, Any] +) -> tuple[Optional[bool], Optional[dict]]: adapter = ctx.adapter(w["system"]) if isinstance(adapter, MailAdapter): return None, None @@ -638,8 +825,14 @@ def apply_plan(ctx: Ctx, digest: str) -> dict[str, Any]: def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: tx["refused"] = code run = _write_run( - state, digest, "apply", outcome="HALTED", results=[], tx=tx, - approval=approval or state.approval_record(digest), started=started, + state, + digest, + "apply", + outcome="HALTED", + results=[], + tx=tx, + approval=approval or state.approval_record(digest), + started=started, ) return TxRefused(code, detail, {"run_dir": str(run), "tx": tx}) @@ -657,7 +850,10 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: tx["blocked_double_effects"] = tx.get("blocked_double_effects", 0) + 1 approval_peek = state.approval_record(digest) or {} for w in writes: - if w.get("ledger") == "possible_replay" and approval_peek.get("decided_by") != "human": + if ( + w.get("ledger") == "possible_replay" + and approval_peek.get("decided_by") != "human" + ): tx["blocked_double_effects"] = tx.get("blocked_double_effects", 0) + 1 if tx.get("blocked_double_effects"): raise refuse( @@ -666,7 +862,9 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: ) # The frame must be what the plan read: anything else is a stale plan. now_frames = ctx.frames(list(priv["frames"])) - moved = [s for s, f in now_frames.items() if sha256(f) != plan["frame_sha256"].get(s)] + moved = [ + s for s, f in now_frames.items() if sha256(f) != plan["frame_sha256"].get(s) + ] if moved: raise refuse("plan_stale", f"{len(moved)} scope(s) changed since the plan") try: @@ -683,50 +881,149 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: key, payload = w["key"], w["payload_sha256"] entry = state.entry(key) if stop: - results.append(_line(ok=False, verified=None, irreversible=w["irreversible"], payload=payload, code="not_sent")) + results.append( + _line( + ok=False, + verified=None, + irreversible=w["irreversible"], + payload=payload, + code="not_sent", + ) + ) continue - if w.get("ledger") == "possible_replay" and entry is not None and entry.status == "applied": + if ( + w.get("ledger") == "possible_replay" + and entry is not None + and entry.status == "applied" + ): entry = None # a person approved it as new work: a new attempt under the key if entry is not None and entry.status not in FREE: if entry.status in ("applied", "held", "released"): tx["replays"] = tx.get("replays", 0) + 1 - results.append(_line(ok=True, verified=None, irreversible=w["irreversible"], payload=payload, code="replay_not_sent")) + results.append( + _line( + ok=True, + verified=None, + irreversible=w["irreversible"], + payload=payload, + code="replay_not_sent", + ) + ) continue # begun / uncertain / undo_begun: an earlier attempt may have landed. verified, got = ( - _readback(ctx, w, base, {"id": w["id"]}) if w["op"] == "update" else (None, None) + _readback(ctx, w, base, {"id": w["id"]}) + if w["op"] == "update" + else (None, None) ) if verified: - state.record(key, "applied", plan=digest, payload=payload, result={"id": w["id"]}, by="read_back") - images[key] = {"result": {"id": w["id"]}, "after": _norm(spec.system(w["system"]), w, got)} - results.append(_line(ok=True, verified=True, irreversible=False, payload=payload, code="adopted_by_read_back")) + state.record( + key, + "applied", + plan=digest, + payload=payload, + result={"id": w["id"]}, + by="read_back", + ) + images[key] = { + "result": {"id": w["id"]}, + "after": _norm(spec.system(w["system"]), w, got), + } + results.append( + _line( + ok=True, + verified=True, + irreversible=False, + payload=payload, + code="adopted_by_read_back", + ) + ) continue - state.record(key, "uncertain", plan=digest, payload=payload, reason="open_attempt") + state.record( + key, + "uncertain", + plan=digest, + payload=payload, + reason="open_attempt", + ) stop = "open_attempt" tx["held_uncertain"] = tx.get("held_uncertain", 0) + 1 - results.append(_line(ok=False, verified=None, irreversible=w["irreversible"], payload=payload, code="held_uncertain")) + results.append( + _line( + ok=False, + verified=None, + irreversible=w["irreversible"], + payload=payload, + code="held_uncertain", + ) + ) continue - state.record(key, "begun", plan=digest, payload=payload, op=w["op"], slot=w["slot"]) + state.record( + key, "begun", plan=digest, payload=payload, op=w["op"], slot=w["slot"] + ) if w["irreversible"]: release_at = now() + float(plan["holdback_s"]) - state.hold(key, {"key": key, "plan": digest, "write": plan["writes"].index( - next(x for x in plan["writes"] if x["key"] == key)), "release_at": release_at}) - state.record(key, "held", plan=digest, payload=payload, release_at=release_at) + state.hold( + key, + { + "key": key, + "plan": digest, + "write": plan["writes"].index( + next(x for x in plan["writes"] if x["key"] == key) + ), + "release_at": release_at, + }, + ) + state.record( + key, "held", plan=digest, payload=payload, release_at=release_at + ) tx["held"] = tx.get("held", 0) + 1 - results.append(_line(ok=True, verified=None, irreversible=True, payload=payload, code="held")) + results.append( + _line( + ok=True, + verified=None, + irreversible=True, + payload=payload, + code="held", + ) + ) continue try: result = ctx.adapter(w["system"]).apply(w, base, key) except Diverged: - state.record(key, "refused", plan=digest, payload=payload, reason="diverged") + state.record( + key, "refused", plan=digest, payload=payload, reason="diverged" + ) stop = "diverged" tx["diverged"] = tx.get("diverged", 0) + 1 - results.append(_line(ok=False, verified=False, irreversible=False, payload=payload, code="diverged_rolled_back")) + results.append( + _line( + ok=False, + verified=False, + irreversible=False, + payload=payload, + code="diverged_rolled_back", + ) + ) continue except AdapterError as exc: - state.record(key, "uncertain", plan=digest, payload=payload, reason=str(exc)[:120]) + state.record( + key, + "uncertain", + plan=digest, + payload=payload, + reason=str(exc)[:120], + ) stop = "send_failed" - results.append(_line(ok=False, verified=None, irreversible=False, payload=payload, code="send_failed")) + results.append( + _line( + ok=False, + verified=None, + irreversible=False, + payload=payload, + code="send_failed", + ) + ) continue sent += 1 if crash_after and sent >= crash_after: @@ -734,11 +1031,21 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: rows_image = result.pop("_images", None) state.record(key, "applied", plan=digest, payload=payload, result=result) verified, got = _readback(ctx, w, base, result) - images[key] = {"result": result, "after": _norm(spec.system(w["system"]), w, got)} + images[key] = { + "result": result, + "after": _norm(spec.system(w["system"]), w, got), + } if rows_image is not None: images[key]["rows"] = rows_image - results.append(_line(ok=bool(verified), verified=verified, irreversible=False, payload=payload, - code="confirmed" if verified else "refuted")) + results.append( + _line( + ok=bool(verified), + verified=verified, + irreversible=False, + payload=payload, + code="confirmed" if verified else "refuted", + ) + ) after = ctx.frames(list(priv["frames"])) missed: list[str] = [] false: list[str] = [] @@ -757,11 +1064,33 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: "stopped": stop, } ) - write_private(state.plan_dir(digest) / "applied.json", {"images": images, "frames_after": after}) + write_private( + state.plan_dir(digest) / "applied.json", + {"images": images, "frames_after": after}, + ) ok = not stop and not missed and not tx["refuted"] - outcome = "VERIFIED" if ok and not tx.get("held") else ("COMPLETED_UNVERIFIED" if ok else "RECONCILIATION_REQUIRED") - run = _write_run(state, digest, "apply", outcome=outcome, results=results, tx=tx, approval=approval, started=started) - return {"outcome": outcome, "tx": tx, "run_dir": str(run), "missed": missed, "false": false} + outcome = ( + "VERIFIED" + if ok and not tx.get("held") + else ("COMPLETED_UNVERIFIED" if ok else "RECONCILIATION_REQUIRED") + ) + run = _write_run( + state, + digest, + "apply", + outcome=outcome, + results=results, + tx=tx, + approval=approval, + started=started, + ) + return { + "outcome": outcome, + "tx": tx, + "run_dir": str(run), + "missed": missed, + "false": false, + } # -- undo ---------------------------------------------------------------------- @@ -807,27 +1136,48 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: result = entry.result or {"id": w.get("id")} adapter = ctx.adapter(w["system"]) if w["op"] == "sql": - per_write[key] = _undo_sql(state, adapter, w, entry, (images.get(key) or {}).get("rows"), digest) + per_write[key] = _undo_sql( + state, + adapter, + w, + entry, + (images.get(key) or {}).get("rows"), + digest, + ) continue rid = str(result.get("id") or w.get("id")) current = adapter.read(w["collection"], rid) want = (images.get(key) or {}).get("after") - if w["op"] != "delete" and (want is None or _norm(system, w, current) != want): + if w["op"] != "delete" and ( + want is None or _norm(system, w, current) != want + ): per_write[key] = "changed_since_apply" continue state.record(key, "undo_begun", plan=digest, payload=entry.payload) try: adapter.compensate(w, base, result, key) except AdapterError as exc: - state.record(key, "uncertain", plan=digest, payload=entry.payload, reason=f"undo: {exc}"[:120]) + state.record( + key, + "uncertain", + plan=digest, + payload=entry.payload, + reason=f"undo: {exc}"[:120], + ) per_write[key] = "undo_failed" continue - back = adapter.read(w["collection"], rid if w["op"] != "delete" else str(w["id"])) + back = adapter.read( + w["collection"], rid if w["op"] != "delete" else str(w["id"]) + ) if w["op"] == "create": ok = back is None else: - ok = back is not None and _norm(system, w, back) == _norm(system, w, base) - state.record(key, "undone", plan=digest, payload=entry.payload, read_back=ok) + ok = back is not None and _norm(system, w, back) == _norm( + system, w, base + ) + state.record( + key, "undone", plan=digest, payload=entry.payload, read_back=ok + ) per_write[key] = "undone" if ok else "undo_refuted" # The whole frame back to the baseline: the records and the collateral. after = ctx.frames(list(priv["frames"])) @@ -840,7 +1190,19 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: e = state.entry(w["key"]) rid = f"{w['collection']}/{(e.result.get('id') if e else None) or w.get('id')}" own[rid] = w["key"] - counted = [k for k, v in per_write.items() if v in ("undone", "undo_refuted", "frame_differs", "changed_since_apply", "undo_failed", "unresolved")] + counted = [ + k + for k, v in per_write.items() + if v + in ( + "undone", + "undo_refuted", + "frame_differs", + "changed_since_apply", + "undo_failed", + "unresolved", + ) + ] # Undo images name the rows a statement touched: those are the write's own. for w in writes: img = (images.get(w["key"]) or {}).get("rows") or {} @@ -853,12 +1215,20 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: verified = [k for k in counted if per_write[k] == "undone" and not collateral] for w in writes: code = per_write.get(w["key"]) - if code in (None, "not_this_plan", "cancelled", "already_undone", "no_undo"): + if code in ( + None, + "not_this_plan", + "cancelled", + "already_undone", + "no_undo", + ): continue results.append( _line( ok=w["key"] in verified, - verified=(w["key"] in verified) if code != "irreversible_released" else None, + verified=(w["key"] in verified) + if code != "irreversible_released" + else None, irreversible=w["irreversible"], payload=w["payload_sha256"], code=code, @@ -869,17 +1239,38 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: "undo_supported": len(counted), "undo_verified": len(verified), "cancelled": sum(1 for v in per_write.values() if v == "cancelled"), - "irreversible_released": sum(1 for v in per_write.values() if v == "irreversible_released"), - "no_generated_undo": sum(1 for v in per_write.values() if v == "no_undo"), + "irreversible_released": sum( + 1 for v in per_write.values() if v == "irreversible_released" + ), + "no_generated_undo": sum( + 1 for v in per_write.values() if v == "no_undo" + ), "collateral_changes": len(collateral), - "codes": {c: sum(1 for v in per_write.values() if v == c) for c in sorted(set(per_write.values()))}, + "codes": { + c: sum(1 for v in per_write.values() if v == c) + for c in sorted(set(per_write.values())) + }, } ) ok = len(verified) == len(counted) and not collateral outcome = "ROLLED_BACK" if ok else "RECONCILIATION_REQUIRED" approval = state.approval_record(digest) - run = _write_run(state, digest, "undo", outcome=outcome, results=results, tx=tx, approval=approval, started=started) - return {"outcome": outcome, "tx": tx, "run_dir": str(run), "collateral": collateral} + run = _write_run( + state, + digest, + "undo", + outcome=outcome, + results=results, + tx=tx, + approval=approval, + started=started, + ) + return { + "outcome": outcome, + "tx": tx, + "run_dir": str(run), + "collateral": collateral, + } # -- holdback ------------------------------------------------------------------ @@ -894,7 +1285,12 @@ def cancel(ctx: Ctx, digest: str) -> int: continue entry = state.entry(item["key"]) state.unhold(item["key"]) - state.record(item["key"], "cancelled", plan=digest, payload=entry.payload if entry else "") + state.record( + item["key"], + "cancelled", + plan=digest, + payload=entry.payload if entry else "", + ) n += 1 return n @@ -902,13 +1298,19 @@ def cancel(ctx: Ctx, digest: str) -> int: def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, Any]: """Release the plan's held writes whose holdback has passed.""" started = now() - state, spec = ctx.state, ctx.spec + state = ctx.state at = now() if at is None else at with state.lock(): plan, priv = load_plan(state, digest) writes = {w["key"]: (w, b) for w, b in zip(priv["writes"], priv["baselines"])} results = [] - tx: dict[str, Any] = {"phase": "release", "released": 0, "waiting": 0, "adopted": 0, "double": 0} + tx: dict[str, Any] = { + "phase": "release", + "released": 0, + "waiting": 0, + "adopted": 0, + "double": 0, + } for item in state.held(): if item["plan"] != digest: continue @@ -926,8 +1328,22 @@ def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, A try: adapter.send(w, key) except AdapterError: - state.record(key, "uncertain", plan=digest, payload=w["payload_sha256"], reason="smtp") - results.append(_line(ok=False, verified=None, irreversible=True, payload=w["payload_sha256"], code="send_failed")) + state.record( + key, + "uncertain", + plan=digest, + payload=w["payload_sha256"], + reason="smtp", + ) + results.append( + _line( + ok=False, + verified=None, + irreversible=True, + payload=w["payload_sha256"], + code="send_failed", + ) + ) continue else: tx["adopted"] += 1 @@ -938,14 +1354,38 @@ def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, A adapter.apply(w, base, key) verified, _ = _readback(ctx, w, base, {"id": w.get("id")}) state.unhold(key) - state.record(key, "released", plan=digest, payload=w["payload_sha256"], read_back=verified) + state.record( + key, + "released", + plan=digest, + payload=w["payload_sha256"], + read_back=verified, + ) tx["released"] += 1 - results.append(_line(ok=bool(verified), verified=verified, irreversible=True, payload=w["payload_sha256"], - code="released" if verified else "release_refuted")) - outcome = "VERIFIED" if results and all(r["effect_verified"] for r in results) else ( - "COMPLETED_UNVERIFIED" if not results else "RECONCILIATION_REQUIRED") - run = _write_run(state, digest, "release", outcome=outcome, results=results, tx=tx, - approval=state.approval_record(digest), started=started) + results.append( + _line( + ok=bool(verified), + verified=verified, + irreversible=True, + payload=w["payload_sha256"], + code="released" if verified else "release_refuted", + ) + ) + outcome = ( + "VERIFIED" + if results and all(r["effect_verified"] for r in results) + else ("COMPLETED_UNVERIFIED" if not results else "RECONCILIATION_REQUIRED") + ) + run = _write_run( + state, + digest, + "release", + outcome=outcome, + results=results, + tx=tx, + approval=state.approval_record(digest), + started=started, + ) return {"outcome": outcome, "tx": tx, "run_dir": str(run)} @@ -955,7 +1395,9 @@ def summary_lines(plan: Mapping[str, Any]) -> list[str]: for what, n in sorted(plan["summary"].items()): lines.append(f" {n} {what}") if plan.get("queued"): - lines.append(f" irreversible writes wait {plan['holdback_s']:.0f}s in a cancelable holdback queue") + lines.append( + f" irreversible writes wait {plan['holdback_s']:.0f}s in a cancelable holdback queue" + ) for system, how in sorted(plan["dry_run"].items()): lines.append(f" {system}: diff from {how.replace('_', ' ')}") for scope, pred in sorted(plan["predicted"].items()): @@ -963,8 +1405,18 @@ def summary_lines(plan: Mapping[str, Any]) -> list[str]: lines.append( f" {scope}: predicted {added} added, {len(pred['changed'])} changed, {len(pred['removed'])} removed" ) - tables = _counts({"added": [f"{t}/+{i}" for t, n in pred["added"].items() for i in range(n)], - "removed": pred["removed"], "changed": pred["changed"]}) or {} + tables = ( + _counts( + { + "added": [ + f"{t}/+{i}" for t, n in pred["added"].items() for i in range(n) + ], + "removed": pred["removed"], + "changed": pred["changed"], + } + ) + or {} + ) if len(tables) > 1 or scope.endswith(":*"): for table, c in sorted(tables.items()): parts = [f"{v} rows {k}" for k, v in c.items() if v] diff --git a/packages/flow/openadapt_flow/txplan/proxy.py b/packages/flow/openadapt_flow/txplan/proxy.py index 868d0fe35c..9c8ca76a40 100644 --- a/packages/flow/openadapt_flow/txplan/proxy.py +++ b/packages/flow/openadapt_flow/txplan/proxy.py @@ -59,11 +59,23 @@ PATH = "/mcp" MAX_QUERY_ROWS = 200 #: Environment variables that carry database credentials, removed from the child. -SCRUB = ("DATABASE_URL", "PGPASSWORD", "PGPASSFILE", "PGSERVICE", "PGSERVICEFILE", "PGHOST", - "PGUSER", "PGDATABASE", "PGPORT", "MYSQL_PWD") - - -def child_environment(environ: Mapping[str, str], secrets_: Sequence[str]) -> dict[str, str]: +SCRUB = ( + "DATABASE_URL", + "PGPASSWORD", + "PGPASSFILE", + "PGSERVICE", + "PGSERVICEFILE", + "PGHOST", + "PGUSER", + "PGDATABASE", + "PGPORT", + "MYSQL_PWD", +) + + +def child_environment( + environ: Mapping[str, str], secrets_: Sequence[str] +) -> dict[str, str]: """The command's environment: credentials and their copies removed.""" out = {} for k, v in environ.items(): @@ -73,31 +85,61 @@ def child_environment(environ: Mapping[str, str], secrets_: Sequence[str]) -> di return out -def sql_spec(*, postgres: Optional[str] = None, sqlite: Optional[str] = None, - max_rows: int = 0, flags: Sequence[str] = ()) -> TxSpec: +def sql_spec( + *, + postgres: Optional[str] = None, + sqlite: Optional[str] = None, + max_rows: int = 0, + flags: Sequence[str] = (), +) -> TxSpec: """A one-system tx spec for a database URL or a SQLite file.""" if bool(postgres) == bool(sqlite): raise ValueError("give exactly one of --postgres or --sqlite") if postgres: - system = SqlSystem(name="db", kind="sql", dialect="postgresql", driver="psycopg", - connect_args={"conninfo": postgres}) + system = SqlSystem( + name="db", + kind="sql", + dialect="postgresql", + driver="psycopg", + connect_args={"conninfo": postgres}, + ) else: - system = SqlSystem(name="db", kind="sql", dialect="sqlite", path=str(Path(str(sqlite)).resolve())) - anomalies = [Anomaly(label="more rows than the auto-approve limit", max_rows=max_rows)] + system = SqlSystem( + name="db", + kind="sql", + dialect="sqlite", + path=str(Path(str(sqlite)).resolve()), + ) + anomalies = [ + Anomaly(label="more rows than the auto-approve limit", max_rows=max_rows) + ] for flag in flags: target, _, value = flag.partition("=") table, _, column = target.partition(".") if not (table and column and value): raise ValueError(f"--flag {flag!r}: use table.column=value") - anomalies.append(Anomaly(label=f"rows where {table}.{column} = {value}", table=table, - column=column, equals=value)) - return TxSpec(schema_version="openadapt.tx/v1", holdback_s=0, anomalies=anomalies, systems=[system]) + anomalies.append( + Anomaly( + label=f"rows where {table}.{column} = {value}", + table=table, + column=column, + equals=value, + ) + ) + return TxSpec( + schema_version="openadapt.tx/v1", + holdback_s=0, + anomalies=anomalies, + systems=[system], + ) class Proxy: """The tools, over one database, for one task (this proxy session).""" - def __init__(self, ctx: Ctx, *, task: str, system: str = "db", interactive: bool = False) -> None: + def __init__( + self, ctx: Ctx, *, task: str, system: str = "db", interactive: bool = False + ) -> None: self.ctx = ctx self.task = task self.system = system @@ -136,24 +178,36 @@ def query(self, sql: str) -> dict[str, Any]: def preview(self, sql: str) -> dict[str, Any]: with self.lock: - plan = engine.make_plan(self.ctx, self.task, [{"system": self.system, "op": "sql", "fields": {"sql": sql}}]) + plan = engine.make_plan( + self.ctx, + self.task, + [{"system": self.system, "op": "sql", "fields": {"sql": sql}}], + ) digest = plan["digest"] w = plan["writes"][0] counts = w.get("staged_diff") or {} auto = not plan["anomalies"] and w["ledger"] == "free" and not w.get("ddl") if auto: - engine.approve_plan(self.ctx.state, digest, approver="policy", decided_by="automation") + engine.approve_plan( + self.ctx.state, digest, approver="policy", decided_by="automation" + ) else: self.pending.append(digest) text = "\n".join(engine.summary_lines(plan)) if self.interactive and not auto: - print("\n" + text + "\n press y to approve, n to decline", file=sys.stderr, flush=True) + print( + "\n" + text + "\n press y to approve, n to decline", + file=sys.stderr, + flush=True, + ) return { "plan": digest[:16], "tables": counts, "ledger": w["ledger"], "anomalies": [a["label"] for a in plan["anomaly_details"]], - "approval": "approved by policy" if auto else ( + "approval": "approved by policy" + if auto + else ( "waiting for a person (y in the proxy terminal, or `openadapt plan approve " f"{digest[:16]}`)" ), @@ -166,13 +220,21 @@ def apply(self, plan: str) -> dict[str, Any]: out = engine.apply_plan(self.ctx, digest) if out["outcome"] in ("VERIFIED", "COMPLETED_UNVERIFIED"): self.applied.append(digest) - return {"outcome": out["outcome"], "tx": out["tx"], "receipt": out["run_dir"]} + return { + "outcome": out["outcome"], + "tx": out["tx"], + "receipt": out["run_dir"], + } def undo(self, plan: str) -> dict[str, Any]: with self.lock: digest = self.ctx.state.find_plan(plan) out = engine.undo_plan(self.ctx, digest) - return {"outcome": out["outcome"], "tx": out["tx"], "receipt": out["run_dir"]} + return { + "outcome": out["outcome"], + "tx": out["tx"], + "receipt": out["run_dir"], + } def call(self, name: str, args: Mapping[str, Any]) -> tuple[str, bool]: try: @@ -189,9 +251,13 @@ def call(self, name: str, args: Mapping[str, Any]) -> tuple[str, bool]: except TxRefused as exc: return json.dumps({"refused": exc.code, "detail": exc.detail}), True except (AdapterError, StateError, KeyError, ValueError) as exc: - return json.dumps({"error": type(exc).__name__, "detail": str(exc)[:300]}), True + return json.dumps( + {"error": type(exc).__name__, "detail": str(exc)[:300]} + ), True except Exception as exc: # noqa: BLE001 - a database error is the tool's answer - return json.dumps({"error": type(exc).__name__, "detail": str(exc)[:300]}), True + return json.dumps( + {"error": type(exc).__name__, "detail": str(exc)[:300]} + ), True return json.dumps(got, default=str), False # the person's keys --------------------------------------------------------- @@ -202,8 +268,12 @@ def key(self, ch: str) -> str: with self.lock: if ch == "y" and self.pending: digest = self.pending.pop(0) - engine.approve_plan(self.ctx.state, digest, approver=os.environ.get("USER", "person"), - decided_by="human") + engine.approve_plan( + self.ctx.state, + digest, + approver=os.environ.get("USER", "person"), + decided_by="human", + ) return f"approved {digest[:16]}" if ch == "n" and self.pending: return f"declined {self.pending.pop(0)[:16]}" @@ -215,17 +285,46 @@ def key(self, ch: str) -> str: TOOLS = [ - {"name": "sql_query", "description": "Run a read-only SQL query (rolled back; at most 200 rows).", - "inputSchema": {"type": "object", "properties": {"sql": {"type": "string"}}, "required": ["sql"]}}, - {"name": "sql_preview", "description": ( - "Dry-run one SQL write statement: OpenAdapt runs it in a transaction, returns the exact " - "row-level diff and a plan id, and rolls back. Small plans are approved by policy; others " - "wait for a person."), - "inputSchema": {"type": "object", "properties": {"sql": {"type": "string"}}, "required": ["sql"]}}, - {"name": "sql_apply", "description": "Apply an approved plan once; it commits only if the diff is the planned diff.", - "inputSchema": {"type": "object", "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, - {"name": "sql_undo", "description": "Undo an applied plan and verify it by reading every table back.", - "inputSchema": {"type": "object", "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, + { + "name": "sql_query", + "description": "Run a read-only SQL query (rolled back; at most 200 rows).", + "inputSchema": { + "type": "object", + "properties": {"sql": {"type": "string"}}, + "required": ["sql"], + }, + }, + { + "name": "sql_preview", + "description": ( + "Dry-run one SQL write statement: OpenAdapt runs it in a transaction, returns the exact " + "row-level diff and a plan id, and rolls back. Small plans are approved by policy; others " + "wait for a person." + ), + "inputSchema": { + "type": "object", + "properties": {"sql": {"type": "string"}}, + "required": ["sql"], + }, + }, + { + "name": "sql_apply", + "description": "Apply an approved plan once; it commits only if the diff is the planned diff.", + "inputSchema": { + "type": "object", + "properties": {"plan": {"type": "string"}}, + "required": ["plan"], + }, + }, + { + "name": "sql_undo", + "description": "Undo an applied plan and verify it by reading every table back.", + "inputSchema": { + "type": "object", + "properties": {"plan": {"type": "string"}}, + "required": ["plan"], + }, + }, ] @@ -238,7 +337,9 @@ def __init__(self, proxy: Proxy, *, port: int = 0) -> None: outer = self class H(BaseHTTPRequestHandler): - def log_message(self, *a: Any) -> None: # no access log: never log the token + def log_message( + self, *a: Any + ) -> None: # no access log: never log the token pass def _send(self, code: int, body: Any = None) -> None: @@ -268,12 +369,22 @@ def do_POST(self) -> None: # noqa: N802 if not self._authorized(): return self._send(401) try: - msg = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0))) + msg = json.loads( + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + ) except ValueError: - return self._send(400, {"jsonrpc": "2.0", "id": None, - "error": {"code": -32700, "message": "parse error"}}) + return self._send( + 400, + { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "parse error"}, + }, + ) if isinstance(msg, list): - replies = [r for r in (outer.handle(m) for m in msg) if r is not None] + replies = [ + r for r in (outer.handle(m) for m in msg) if r is not None + ] return self._send(200, replies) if replies else self._send(202) reply = outer.handle(msg) return self._send(202) if reply is None else self._send(200, reply) @@ -288,18 +399,27 @@ def handle(self, msg: Mapping[str, Any]) -> Optional[dict[str, Any]]: return None # a notification if method == "initialize": asked = (msg.get("params") or {}).get("protocolVersion") or PROTOCOL - result: Any = {"protocolVersion": asked, "capabilities": {"tools": {}}, - "serverInfo": {"name": "openadapt-proxy", "version": "1"}} + result: Any = { + "protocolVersion": asked, + "capabilities": {"tools": {}}, + "serverInfo": {"name": "openadapt-proxy", "version": "1"}, + } elif method == "ping": result = {} elif method == "tools/list": result = {"tools": TOOLS} elif method == "tools/call": params = msg.get("params") or {} - text, is_error = self.proxy.call(str(params.get("name")), params.get("arguments") or {}) + text, is_error = self.proxy.call( + str(params.get("name")), params.get("arguments") or {} + ) result = {"content": [{"type": "text", "text": text}], "isError": is_error} else: - return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "method not found"}} + return { + "jsonrpc": "2.0", + "id": mid, + "error": {"code": -32601, "message": "method not found"}, + } return {"jsonrpc": "2.0", "id": mid, "result": result} def start(self) -> None: @@ -314,15 +434,30 @@ def mcp_config(server: McpServer, folder: Path) -> Path: path = folder / "openadapt-mcp.json" fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w") as f: - json.dump({"mcpServers": {"openadapt": { - "type": "http", "url": server.url, - "headers": {"Authorization": f"Bearer {server.token}"}, - }}}, f) + json.dump( + { + "mcpServers": { + "openadapt": { + "type": "http", + "url": server.url, + "headers": {"Authorization": f"Bearer {server.token}"}, + } + } + }, + f, + ) return path -def run(argv_command: Sequence[str], *, spec: TxSpec, state: State, task: str, - secrets_: Sequence[str], port: int = 0) -> int: +def run( + argv_command: Sequence[str], + *, + spec: TxSpec, + state: State, + task: str, + secrets_: Sequence[str], + port: int = 0, +) -> int: ctx = Ctx(spec=spec, state=state) proxy = Proxy(ctx, task=task, interactive=not argv_command) server = McpServer(proxy, port=port) @@ -330,11 +465,18 @@ def run(argv_command: Sequence[str], *, spec: TxSpec, state: State, task: str, tmp = Path(tempfile.mkdtemp(prefix="openadapt-proxy-")) try: config = mcp_config(server, tmp) - print(f"openadapt proxy: MCP endpoint {server.url} (task {task})", file=sys.stderr, flush=True) + print( + f"openadapt proxy: MCP endpoint {server.url} (task {task})", + file=sys.stderr, + flush=True, + ) if not argv_command: - print(f"MCP config for your agent: {config}\n" - "keys: y approve the waiting plan, n decline it, u undo the last applied plan, q quit", - file=sys.stderr, flush=True) + print( + f"MCP config for your agent: {config}\n" + "keys: y approve the waiting plan, n decline it, u undo the last applied plan, q quit", + file=sys.stderr, + flush=True, + ) for line in sys.stdin: ch = line.strip()[:1].lower() if ch == "q": @@ -342,8 +484,14 @@ def run(argv_command: Sequence[str], *, spec: TxSpec, state: State, task: str, print(proxy.key(ch), file=sys.stderr, flush=True) return 0 env = child_environment(os.environ, secrets_) - env.update({"OPENADAPT_MCP_URL": server.url, "OPENADAPT_MCP_TOKEN": server.token, - "OPENADAPT_MCP_CONFIG": str(config), "OPENADAPT_TASK": task}) + env.update( + { + "OPENADAPT_MCP_URL": server.url, + "OPENADAPT_MCP_TOKEN": server.token, + "OPENADAPT_MCP_CONFIG": str(config), + "OPENADAPT_TASK": task, + } + ) cmd = list(argv_command) if Path(cmd[0]).name == "claude" and "--mcp-config" not in cmd: cmd[1:1] = ["--mcp-config", str(config)] diff --git a/packages/flow/openadapt_flow/txplan/proxy_cli.py b/packages/flow/openadapt_flow/txplan/proxy_cli.py index f6b38c1c4f..67c3d28cc5 100644 --- a/packages/flow/openadapt_flow/txplan/proxy_cli.py +++ b/packages/flow/openadapt_flow/txplan/proxy_cli.py @@ -16,33 +16,67 @@ def _parser() -> argparse.ArgumentParser: - p = argparse.ArgumentParser(prog="openadapt proxy", description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) + p = argparse.ArgumentParser( + prog="openadapt proxy", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + allow_abbrev=False, + ) _fill(p) return p def _fill(p: argparse.ArgumentParser) -> None: db = p.add_mutually_exclusive_group(required=True) - db.add_argument("--postgres", metavar="URL", help="a PostgreSQL URL (needs the psycopg package)") + db.add_argument( + "--postgres", metavar="URL", help="a PostgreSQL URL (needs the psycopg package)" + ) db.add_argument("--sqlite", metavar="PATH", help="a SQLite file") - p.add_argument("--task", help="the task these writes belong to (default: one per proxy run)") - p.add_argument("--auto-approve-max-rows", type=int, default=0, metavar="N", - help="approve by policy a plan that touches at most N rows and has no anomaly (default 0)") - p.add_argument("--flag", action="append", default=[], metavar="TABLE.COLUMN=VALUE", - help="show rows the statement touches where TABLE.COLUMN = VALUE (repeatable)") - p.add_argument("--state", help="the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)") - p.add_argument("--port", type=int, default=0, help="the MCP port on 127.0.0.1 (default: random)") + p.add_argument( + "--task", help="the task these writes belong to (default: one per proxy run)" + ) + p.add_argument( + "--auto-approve-max-rows", + type=int, + default=0, + metavar="N", + help="approve by policy a plan that touches at most N rows and has no anomaly (default 0)", + ) + p.add_argument( + "--flag", + action="append", + default=[], + metavar="TABLE.COLUMN=VALUE", + help="show rows the statement touches where TABLE.COLUMN = VALUE (repeatable)", + ) + p.add_argument( + "--state", + help="the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)", + ) + p.add_argument( + "--port", + type=int, + default=0, + help="the MCP port on 127.0.0.1 (default: random)", + ) def add_parser(sub: argparse._SubParsersAction) -> None: - p = sub.add_parser("proxy", help=( - "Hold the database credentials; give the agent MCP tools that preview, apply " - "once and undo each write"), description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) + p = sub.add_parser( + "proxy", + help=( + "Hold the database credentials; give the agent MCP tools that preview, apply " + "once and undo each write" + ), + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + allow_abbrev=False, + ) _fill(p) - p.add_argument("command", nargs=argparse.REMAINDER, help="-- COMMAND ... (the agent)") - p.set_defaults(func=lambda a: _run(a, [x for x in a.command if x != "--"][: None])) + p.add_argument( + "command", nargs=argparse.REMAINDER, help="-- COMMAND ... (the agent)" + ) + p.set_defaults(func=lambda a: _run(a, [x for x in a.command if x != "--"][:None])) def _run(args: argparse.Namespace, command: Sequence[str]) -> int: @@ -50,14 +84,24 @@ def _run(args: argparse.Namespace, command: Sequence[str]) -> int: from openadapt_flow.txplan.state import State try: - spec = sql_spec(postgres=args.postgres, sqlite=args.sqlite, - max_rows=args.auto_approve_max_rows, flags=args.flag) + spec = sql_spec( + postgres=args.postgres, + sqlite=args.sqlite, + max_rows=args.auto_approve_max_rows, + flags=args.flag, + ) except ValueError as exc: print(f"error: {exc}", file=sys.stderr) return 2 state = State(Path(args.state) if args.state else None) - return run(command, spec=spec, state=state, task=args.task or default_task(), - secrets_=[args.postgres] if args.postgres else [], port=args.port) + return run( + command, + spec=spec, + state=state, + task=args.task or default_task(), + secrets_=[args.postgres] if args.postgres else [], + port=args.port, + ) def main(argv: Optional[Sequence[str]] = None) -> int: diff --git a/packages/flow/openadapt_flow/txplan/spec.py b/packages/flow/openadapt_flow/txplan/spec.py index 69cdd6cc3a..801c4a93f0 100644 --- a/packages/flow/openadapt_flow/txplan/spec.py +++ b/packages/flow/openadapt_flow/txplan/spec.py @@ -93,8 +93,11 @@ def placeholders(self) -> list[str]: class Collection(_Closed): name: str = Field(pattern=_NAME) + model_config = ConfigDict(extra="forbid", populate_by_name=True) + id_field: str = "id" - list: Route + #: ``list`` in the file: the route that lists the whole collection. + list_: Route = Field(alias="list") read: Route create: Optional[Route] = None update: Optional[Route] = None @@ -229,7 +232,16 @@ def _check(self) -> "Anomaly": raise ValueError(f"anomaly {self.label}: above needs field") if (self.table is None) != (self.column is None): raise ValueError(f"anomaly {self.label}: table and column go together") - if not any([self.field, self.op, self.max_writes, self.clears, self.max_rows is not None, self.table]): + if not any( + [ + self.field, + self.op, + self.max_writes, + self.clears, + self.max_rows is not None, + self.table, + ] + ): raise ValueError(f"anomaly {self.label}: says nothing to check") return self diff --git a/packages/flow/openadapt_flow/txplan/state.py b/packages/flow/openadapt_flow/txplan/state.py index 34f9579ae6..41ec9b7db3 100644 --- a/packages/flow/openadapt_flow/txplan/state.py +++ b/packages/flow/openadapt_flow/txplan/state.py @@ -67,7 +67,12 @@ def write_private(path: Path, payload: Any) -> None: tmp = path.with_name(path.name + f".{os.getpid()}.tmp") fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) try: - os.write(fd, (json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n").encode()) + os.write( + fd, + ( + json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n" + ).encode(), + ) os.fsync(fd) finally: os.close(fd) @@ -132,7 +137,13 @@ def key_for( self, *, task: str, system: str, collection: str, op: str, slot: str ) -> str: body = canonical( - {"task": task, "system": system, "collection": collection, "op": op, "slot": slot} + { + "task": task, + "system": system, + "collection": collection, + "op": op, + "slot": slot, + } ) return "ik-" + hmac.new(self.secret(), body, hashlib.sha256).hexdigest()[:40] @@ -147,7 +158,7 @@ def lock(self) -> Iterator[None]: if os.name == "nt": # pragma: no cover - Windows import msvcrt - msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) # type: ignore[attr-defined] else: import fcntl @@ -165,8 +176,12 @@ def _ledger_path(self, key: str) -> Path: def record(self, key: str, event: str, **fields: Any) -> None: """Append one event, durably, before the caller acts on it.""" - line = json.dumps({"event": event, "at": now(), **fields}, sort_keys=True, default=str) - fd = os.open(self._ledger_path(key), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + line = json.dumps( + {"event": event, "at": now(), **fields}, sort_keys=True, default=str + ) + fd = os.open( + self._ledger_path(key), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600 + ) try: os.write(fd, (line + "\n").encode()) os.fsync(fd) @@ -206,7 +221,9 @@ def plan_dir(self, digest: str) -> Path: def find_plan(self, prefix: str) -> str: prefix = prefix.removeprefix("pl-") - hits = [p.name for p in (self.root / "plans").iterdir() if p.name.startswith(prefix)] + hits = [ + p.name for p in (self.root / "plans").iterdir() if p.name.startswith(prefix) + ] if len(hits) != 1: raise StateError("plan_not_found" if not hits else "plan_ambiguous", prefix) return hits[0] @@ -215,7 +232,10 @@ def find_plan(self, prefix: str) -> str: def approve(self, digest: str, *, approver: str, decided_by: str) -> dict[str, Any]: path = self.root / "approvals" / f"{digest}.json" - if path.exists() or (self.root / "approvals" / f"{digest}.consumed.json").exists(): + if ( + path.exists() + or (self.root / "approvals" / f"{digest}.consumed.json").exists() + ): raise StateError("already_approved", digest[:12]) record = { "plan": digest, @@ -256,7 +276,9 @@ def hold(self, key: str, item: Mapping[str, Any]) -> None: write_private(self.root / "holdback" / f"{key}.json", dict(item)) def held(self) -> list[dict[str, Any]]: - return [read_json(p) for p in sorted((self.root / "holdback").glob("ik-*.json"))] + return [ + read_json(p) for p in sorted((self.root / "holdback").glob("ik-*.json")) + ] def unhold(self, key: str) -> None: with contextlib.suppress(FileNotFoundError): diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 479ab55a3d..33412b23f9 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -53,7 +53,9 @@ def _db(path: Path, *, trigger: bool = False) -> Path: """ ) for i in range(1, 21): - con.execute("INSERT INTO customers VALUES (?, ?, ?, ?)", (i, f"cust {i}", 10.0 * i, "")) + con.execute( + "INSERT INTO customers VALUES (?, ?, ?, ?)", (i, f"cust {i}", 10.0 * i, "") + ) con.execute("INSERT INTO orders VALUES (?, ?, ?)", (i, i, 5.0 * i)) if trigger: con.execute( @@ -97,38 +99,77 @@ def mail() -> Iterator[MailSink]: sink.close() -def _spec(tmp_path: Path, *, db: Path | None = None, rest_url: str | None = None, - mail: MailSink | None = None, holdback: float = 60) -> Path: +def _spec( + tmp_path: Path, + *, + db: Path | None = None, + rest_url: str | None = None, + mail: MailSink | None = None, + holdback: float = 60, +) -> Path: systems: list[dict[str, Any]] = [] if db is not None: - systems.append({"name": "crm", "kind": "sql", "dialect": "sqlite", "path": str(db), - "tables": {"customers": "id", "orders": "id"}}) + systems.append( + { + "name": "crm", + "kind": "sql", + "dialect": "sqlite", + "path": str(db), + "tables": {"customers": "id", "orders": "id"}, + } + ) if rest_url is not None: - systems.append({ - "name": "tasks", "kind": "rest", "base_url": rest_url, - "collections": [{ - "name": "item", "id_field": "id", - "list": {"path": "/api/items", "page_param": "page", "per_page": 4}, - "read": {"path": "/api/items/{id}"}, - "create": {"method": "POST", "path": "/api/items"}, - "update": {"method": "PATCH", "path": "/api/items/{id}", "replace": True}, - "delete": {"method": "DELETE", "path": "/api/items/{id}"}, - "server_fields": ["updated"], - "derived": {"done": ["done_at"]}, - }], - }) + systems.append( + { + "name": "tasks", + "kind": "rest", + "base_url": rest_url, + "collections": [ + { + "name": "item", + "id_field": "id", + "list": { + "path": "/api/items", + "page_param": "page", + "per_page": 4, + }, + "read": {"path": "/api/items/{id}"}, + "create": {"method": "POST", "path": "/api/items"}, + "update": { + "method": "PATCH", + "path": "/api/items/{id}", + "replace": True, + }, + "delete": {"method": "DELETE", "path": "/api/items/{id}"}, + "server_fields": ["updated"], + "derived": {"done": ["done_at"]}, + } + ], + } + ) if mail is not None: - systems.append({"name": "outbox", "kind": "mail", - "smtp": {"host": "127.0.0.1", "port": mail.smtp_port}, - "mailbox": {"kind": "mailpit", "base_url": mail.api_url}}) + systems.append( + { + "name": "outbox", + "kind": "mail", + "smtp": {"host": "127.0.0.1", "port": mail.smtp_port}, + "mailbox": {"kind": "mailpit", "base_url": mail.api_url}, + } + ) path = tmp_path / "openadapt.tx.yaml" - path.write_text(yaml.safe_dump({ - "schema_version": "openadapt.tx/v1", - "holdback_s": holdback, - "anomalies": [{"field": "amount", "above": 10000, "label": "large refund"}, - {"op": "delete", "label": "delete"}], - "systems": systems, - })) + path.write_text( + yaml.safe_dump( + { + "schema_version": "openadapt.tx/v1", + "holdback_s": holdback, + "anomalies": [ + {"field": "amount", "above": 10000, "label": "large refund"}, + {"op": "delete", "label": "delete"}, + ], + "systems": systems, + } + ) + ) return path @@ -138,7 +179,9 @@ def _ctx(spec: Path) -> Ctx: def _go(ctx: Ctx, task: str, writes: list[dict[str, Any]]) -> dict[str, Any]: plan = engine.make_plan(ctx, task, writes) - engine.approve_plan(ctx.state, plan["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, plan["digest"], approver="lab", decided_by="automation" + ) return plan @@ -150,10 +193,19 @@ def test_sql_plan_apply_undo_round_trip(tmp_path: Path) -> None: before = _rows(db) ctx = _ctx(_spec(tmp_path, db=db)) writes = [ - {"system": "crm", "collection": "customers", "op": "update", "id": 3, - "fields": {"balance": 99.5, "note": SECRET_NOTE}}, - {"system": "crm", "collection": "customers", "op": "create", - "fields": {"name": "new cust", "balance": 1.0, "note": ""}}, + { + "system": "crm", + "collection": "customers", + "op": "update", + "id": 3, + "fields": {"balance": 99.5, "note": SECRET_NOTE}, + }, + { + "system": "crm", + "collection": "customers", + "op": "create", + "fields": {"name": "new cust", "balance": 1.0, "note": ""}, + }, {"system": "crm", "collection": "orders", "op": "delete", "id": 7}, ] plan = _go(ctx, "T-sql", writes) @@ -172,33 +224,67 @@ def test_sql_plan_apply_undo_round_trip(tmp_path: Path) -> None: undone = engine.undo_plan(ctx, plan["digest"]) assert undone["outcome"] == "ROLLED_BACK", undone - assert undone["tx"]["undo_verified"] == 3 and undone["tx"]["collateral_changes"] == 0 + assert ( + undone["tx"]["undo_verified"] == 3 and undone["tx"]["collateral_changes"] == 0 + ) assert _rows(db) == before -def test_staged_dry_run_sees_a_trigger_and_undo_reports_its_collateral(tmp_path: Path) -> None: +def test_staged_dry_run_sees_a_trigger_and_undo_reports_its_collateral( + tmp_path: Path, +) -> None: db = _db(tmp_path / "crm.sqlite", trigger=True) ctx = _ctx(_spec(tmp_path, db=db)) - plan = _go(ctx, "T-trig", [{"system": "crm", "collection": "customers", "op": "update", - "id": 2, "fields": {"balance": 1.0}}]) + plan = _go( + ctx, + "T-trig", + [ + { + "system": "crm", + "collection": "customers", + "op": "update", + "id": 2, + "fields": {"balance": 1.0}, + } + ], + ) assert plan["predicted"]["crm:*"]["added"] == {"audit": 1} - assert any(a["label"] == "side effects in undeclared tables" for a in plan["anomalies"]) + assert any( + a["label"] == "side effects in undeclared tables" for a in plan["anomalies"] + ) applied = engine.apply_plan(ctx, plan["digest"]) assert applied["tx"]["missed_effects"] == 0, applied undone = engine.undo_plan(ctx, plan["digest"]) # The undo's own UPDATE fires the trigger again: not back to the baseline. assert undone["outcome"] == "RECONCILIATION_REQUIRED" - assert undone["tx"]["undo_verified"] == 0 and undone["tx"]["collateral_changes"] >= 1 + assert ( + undone["tx"]["undo_verified"] == 0 and undone["tx"]["collateral_changes"] >= 1 + ) -def test_missed_effect_is_counted_when_something_else_moves(tmp_path: Path, rest) -> None: +def test_missed_effect_is_counted_when_something_else_moves( + tmp_path: Path, rest +) -> None: store, url = rest ctx = _ctx(_spec(tmp_path, rest_url=url)) - plan = _go(ctx, "T-miss", [{"system": "tasks", "collection": "item", "op": "update", - "id": 1, "fields": {"title": "renamed"}}]) + plan = _go( + ctx, + "T-miss", + [ + { + "system": "tasks", + "collection": "item", + "op": "update", + "id": 1, + "fields": {"title": "renamed"}, + } + ], + ) real = RestAdapter.apply - def apply_and_touch(self, w, base, key): # a server-side cascade the plan didn't see + def apply_and_touch( + self, w, base, key + ): # a server-side cascade the plan didn't see out = real(self, w, base, key) store.records[5]["title"] = "cascaded" return out @@ -208,7 +294,10 @@ def apply_and_touch(self, w, base, key): # a server-side cascade the plan didn' applied = engine.apply_plan(ctx, plan["digest"]) finally: RestAdapter.apply = real # type: ignore[method-assign] - assert applied["tx"]["missed_effects"] == 1 and applied["outcome"] == "RECONCILIATION_REQUIRED" + assert ( + applied["tx"]["missed_effects"] == 1 + and applied["outcome"] == "RECONCILIATION_REQUIRED" + ) # -- approval binding ---------------------------------------------------------- @@ -217,7 +306,15 @@ def apply_and_touch(self, w, base, key): # a server-side cascade the plan didn' def test_approval_binds_to_one_digest_and_is_single_use(tmp_path: Path) -> None: db = _db(tmp_path / "crm.sqlite") ctx = _ctx(_spec(tmp_path, db=db)) - w = [{"system": "crm", "collection": "customers", "op": "update", "id": 1, "fields": {"balance": 7}}] + w = [ + { + "system": "crm", + "collection": "customers", + "op": "update", + "id": 1, + "fields": {"balance": 7}, + } + ] a = engine.make_plan(ctx, "T-a", w) b = engine.make_plan(ctx, "T-b", w) engine.approve_plan(ctx.state, a["digest"], approver="lab", decided_by="automation") @@ -232,8 +329,19 @@ def test_approval_binds_to_one_digest_and_is_single_use(tmp_path: Path) -> None: def test_stale_plan_is_refused_before_any_send(tmp_path: Path) -> None: db = _db(tmp_path / "crm.sqlite") ctx = _ctx(_spec(tmp_path, db=db)) - plan = _go(ctx, "T-stale", [{"system": "crm", "collection": "customers", "op": "update", - "id": 4, "fields": {"balance": 0}}]) + plan = _go( + ctx, + "T-stale", + [ + { + "system": "crm", + "collection": "customers", + "op": "update", + "id": 4, + "fields": {"balance": 0}, + } + ], + ) con = sqlite3.connect(db) con.execute("UPDATE orders SET total = 1 WHERE id = 9") con.commit() @@ -243,18 +351,26 @@ def test_stale_plan_is_refused_before_any_send(tmp_path: Path) -> None: engine.apply_plan(ctx, plan["digest"]) assert exc.value.code == "plan_stale" assert _rows(db) == snapshot - assert ctx.state.approval_record(plan["digest"])["plan"] == plan["digest"] # not consumed + assert ( + ctx.state.approval_record(plan["digest"])["plan"] == plan["digest"] + ) # not consumed # -- ACRFence: semantic rollback, action replay ------------------------------- def _payment(ref: str, amount: int = 100) -> dict[str, Any]: - return {"system": "tasks", "collection": "item", "op": "create", - "fields": {"title": f"refund {ref}", "amount": amount, "reference": ref}} + return { + "system": "tasks", + "collection": "item", + "op": "create", + "fields": {"title": f"refund {ref}", "amount": amount, "reference": ref}, + } -def test_acrfence_control_arm_without_the_guard_double_charges(tmp_path: Path, rest) -> None: +def test_acrfence_control_arm_without_the_guard_double_charges( + tmp_path: Path, rest +) -> None: store, url = rest spec = load_spec(_spec(tmp_path, rest_url=url)) raw = RestAdapter(spec.system("tasks")) # type: ignore[arg-type] @@ -265,7 +381,9 @@ def test_acrfence_control_arm_without_the_guard_double_charges(tmp_path: Path, r assert len(store.records) == n0 + 2 -def test_acrfence_regenerated_payload_after_restore_is_blocked(tmp_path: Path, rest) -> None: +def test_acrfence_regenerated_payload_after_restore_is_blocked( + tmp_path: Path, rest +) -> None: store, url = rest workspace = tmp_path / "workspace" workspace.mkdir() @@ -283,7 +401,9 @@ def test_acrfence_regenerated_payload_after_restore_is_blocked(tmp_path: Path, r again = engine.make_plan(ctx, "T-refund", [_payment("uuid-b")]) assert again["writes"][0]["ledger"] == "replay_mismatch" assert any("different payload" in a["label"] for a in again["anomalies"]) - engine.approve_plan(ctx.state, again["digest"], approver="lab", decided_by="automation") + engine.approve_plan( + ctx.state, again["digest"], approver="lab", decided_by="automation" + ) with pytest.raises(TxRefused) as exc: engine.apply_plan(ctx, again["digest"]) assert exc.value.code == "replay_mismatch" @@ -300,18 +420,42 @@ def test_acrfence_regenerated_payload_after_restore_is_blocked(tmp_path: Path, r def test_acrfence_mutated_update_replay_is_blocked(tmp_path: Path, rest) -> None: store, url = rest ctx = _ctx(_spec(tmp_path, rest_url=url)) - p = _go(ctx, "T-upd", [{"system": "tasks", "collection": "item", "op": "update", "id": 2, - "fields": {"amount": 500}}]) + p = _go( + ctx, + "T-upd", + [ + { + "system": "tasks", + "collection": "item", + "op": "update", + "id": 2, + "fields": {"amount": 500}, + } + ], + ) engine.apply_plan(ctx, p["digest"]) - q = _go(ctx, "T-upd", [{"system": "tasks", "collection": "item", "op": "update", "id": 2, - "fields": {"amount": 5000}}]) + q = _go( + ctx, + "T-upd", + [ + { + "system": "tasks", + "collection": "item", + "op": "update", + "id": 2, + "fields": {"amount": 5000}, + } + ], + ) with pytest.raises(TxRefused) as exc: engine.apply_plan(ctx, q["digest"]) assert exc.value.code == "replay_mismatch" assert store.records[2]["amount"] == 500 -def test_crash_after_send_then_regenerated_retry_makes_no_second_effect(tmp_path: Path, rest) -> None: +def test_crash_after_send_then_regenerated_retry_makes_no_second_effect( + tmp_path: Path, rest +) -> None: store, url = rest spec_path = _spec(tmp_path, rest_url=url) ctx = _ctx(spec_path) @@ -323,9 +467,13 @@ def test_crash_after_send_then_regenerated_retry_makes_no_second_effect(tmp_path f"engine.apply_plan(engine.Ctx(load_spec(Path({str(spec_path)!r})), State()), {plan['digest']!r})" ) env = {**os.environ, engine.CRASH_ENV: "1"} - proc = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, timeout=120) + proc = subprocess.run( + [sys.executable, "-c", code], env=env, capture_output=True, timeout=120 + ) assert proc.returncode == 70, proc.stderr.decode()[-2000:] - assert len(store.records) == n0 + 1 # the send landed; its outcome was never recorded + assert ( + len(store.records) == n0 + 1 + ) # the send landed; its outcome was never recorded key = plan["writes"][0]["key"] assert ctx.state.entry(key).status == "begun" @@ -334,37 +482,77 @@ def test_crash_after_send_then_regenerated_retry_makes_no_second_effect(tmp_path engine.apply_plan(ctx, mutated["digest"]) same = _go(ctx, "T-crash", [_payment("uuid-c")]) out = engine.apply_plan(ctx, same["digest"]) - assert out["tx"]["held_uncertain"] == 1 and out["tx"]["sent"] == 0 # read back, never resent + assert ( + out["tx"]["held_uncertain"] == 1 and out["tx"]["sent"] == 0 + ) # read back, never resent assert len(store.records) == n0 + 1 # -- REST: computed dry run, replace-style update, derived fields -------------- -def test_rest_replace_update_with_derived_field_round_trip(tmp_path: Path, rest) -> None: +def test_rest_replace_update_with_derived_field_round_trip( + tmp_path: Path, rest +) -> None: store, url = rest - snapshot = {k: {f: v for f, v in r.items() if f != "updated"} for k, r in store.records.items()} + snapshot = { + k: {f: v for f, v in r.items() if f != "updated"} + for k, r in store.records.items() + } ctx = _ctx(_spec(tmp_path, rest_url=url)) - plan = _go(ctx, "T-rest", [ - {"system": "tasks", "collection": "item", "op": "update", "id": 3, "fields": {"done": True}}, - {"system": "tasks", "collection": "item", "op": "create", "fields": {"title": "x", "amount": 1}}, - ]) + plan = _go( + ctx, + "T-rest", + [ + { + "system": "tasks", + "collection": "item", + "op": "update", + "id": 3, + "fields": {"done": True}, + }, + { + "system": "tasks", + "collection": "item", + "op": "create", + "fields": {"title": "x", "amount": 1}, + }, + ], + ) pred = plan["predicted"]["tasks:item"] - assert pred["changed"] == {"item/3": ["done"]} and pred["derived"] == {"item/3": ["done_at"]} + assert pred["changed"] == {"item/3": ["done"]} and pred["derived"] == { + "item/3": ["done_at"] + } applied = engine.apply_plan(ctx, plan["digest"]) assert applied["outcome"] == "VERIFIED", applied - assert store.records[3]["title"] == "item 3" # replace-style: the baseline was merged + assert ( + store.records[3]["title"] == "item 3" + ) # replace-style: the baseline was merged undone = engine.undo_plan(ctx, plan["digest"]) assert undone["outcome"] == "ROLLED_BACK", undone - now = {k: {f: v for f, v in r.items() if f != "updated"} for k, r in store.records.items()} + now = { + k: {f: v for f, v in r.items() if f != "updated"} + for k, r in store.records.items() + } assert now == snapshot def test_undo_refuses_a_record_changed_since_apply(tmp_path: Path, rest) -> None: store, url = rest ctx = _ctx(_spec(tmp_path, rest_url=url)) - plan = _go(ctx, "T-chg", [{"system": "tasks", "collection": "item", "op": "update", "id": 4, - "fields": {"amount": 1}}]) + plan = _go( + ctx, + "T-chg", + [ + { + "system": "tasks", + "collection": "item", + "op": "update", + "id": 4, + "fields": {"amount": 1}, + } + ], + ) engine.apply_plan(ctx, plan["digest"]) store.records[4]["amount"] = 2 # a person edited it after the apply undone = engine.undo_plan(ctx, plan["digest"]) @@ -372,7 +560,9 @@ def test_undo_refuses_a_record_changed_since_apply(tmp_path: Path, rest) -> None assert store.records[4]["amount"] == 2 -def test_large_amount_anomaly_is_shown_in_the_terminal_only(tmp_path: Path, rest) -> None: +def test_large_amount_anomaly_is_shown_in_the_terminal_only( + tmp_path: Path, rest +) -> None: _, url = rest ctx = _ctx(_spec(tmp_path, rest_url=url)) plan = engine.make_plan(ctx, "T-big", [_payment("r", amount=42_000)]) @@ -386,10 +576,16 @@ def test_large_amount_anomaly_is_shown_in_the_terminal_only(tmp_path: Path, rest def _mail(to: str = "a@example.test") -> dict[str, Any]: - return {"system": "outbox", "op": "send", "fields": {"to": to, "subject": "Invoice", "body": SECRET_NOTE}} + return { + "system": "outbox", + "op": "send", + "fields": {"to": to, "subject": "Invoice", "body": SECRET_NOTE}, + } -def test_email_waits_in_holdback_and_cancel_sends_nothing(tmp_path: Path, mail: MailSink) -> None: +def test_email_waits_in_holdback_and_cancel_sends_nothing( + tmp_path: Path, mail: MailSink +) -> None: ctx = _ctx(_spec(tmp_path, mail=mail, holdback=3600)) plan = _go(ctx, "T-mail", [_mail(), _mail("b@example.test")]) applied = engine.apply_plan(ctx, plan["digest"]) @@ -399,7 +595,9 @@ def test_email_waits_in_holdback_and_cancel_sends_nothing(tmp_path: Path, mail: assert undone["tx"]["cancelled"] == 2 and mail.messages == [] -def test_email_release_sends_once_even_after_a_crash(tmp_path: Path, mail: MailSink) -> None: +def test_email_release_sends_once_even_after_a_crash( + tmp_path: Path, mail: MailSink +) -> None: ctx = _ctx(_spec(tmp_path, mail=mail, holdback=0)) plan = _go(ctx, "T-rel", [_mail()]) engine.apply_plan(ctx, plan["digest"]) @@ -409,10 +607,18 @@ def test_email_release_sends_once_even_after_a_crash(tmp_path: Path, mail: MailS adapter = ctx.adapter("outbox") assert isinstance(adapter, MailAdapter) - w = json.loads((ctx.state.plan_dir(plan["digest"]) / "private.json").read_text())["writes"][0] + w = json.loads((ctx.state.plan_dir(plan["digest"]) / "private.json").read_text())[ + "writes" + ][0] adapter.send(w, key) out = engine.release(ctx, plan["digest"]) - assert out["tx"] == {"phase": "release", "released": 1, "waiting": 0, "adopted": 1, "double": 0} + assert out["tx"] == { + "phase": "release", + "released": 1, + "waiting": 0, + "adopted": 1, + "double": 0, + } assert len(mail.messages) == 1 and out["outcome"] == "VERIFIED" undone = engine.undo_plan(ctx, plan["digest"]) assert undone["tx"]["irreversible_released"] == 1 @@ -421,18 +627,34 @@ def test_email_release_sends_once_even_after_a_crash(tmp_path: Path, mail: MailS # -- receipts ------------------------------------------------------------------ -def test_each_phase_gets_a_signed_receipt_with_the_approval_bound(tmp_path: Path) -> None: +def test_each_phase_gets_a_signed_receipt_with_the_approval_bound( + tmp_path: Path, +) -> None: from openadapt_flow.receipt_record import local_registry, verify_run_receipt db = _db(tmp_path / "crm.sqlite") ctx = _ctx(_spec(tmp_path, db=db)) - plan = _go(ctx, "T-rcpt", [{"system": "crm", "collection": "customers", "op": "update", "id": 5, - "fields": {"note": SECRET_NOTE}}]) + plan = _go( + ctx, + "T-rcpt", + [ + { + "system": "crm", + "collection": "customers", + "op": "update", + "id": 5, + "fields": {"note": SECRET_NOTE}, + } + ], + ) applied = engine.apply_plan(ctx, plan["digest"]) undone = engine.undo_plan(ctx, plan["digest"]) registry = local_registry(Path(os.environ["OPENADAPT_SEAL_HOME"])) - for run_dir, outcome in ((plan["run_dir"], "UNKNOWN"), (applied["run_dir"], "VERIFIED"), - (undone["run_dir"], "STOPPED")): + for run_dir, outcome in ( + (plan["run_dir"], "UNKNOWN"), + (applied["run_dir"], "VERIFIED"), + (undone["run_dir"], "STOPPED"), + ): run = Path(run_dir) got = verify_run_receipt(run, registry) assert got.ok, (run, got) @@ -446,14 +668,29 @@ def test_each_phase_gets_a_signed_receipt_with_the_approval_bound(tmp_path: Path assert stmt["predicate"]["approval"]["approver_kind"] == "agent" -def test_cli_create_show_approve_apply(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: +def test_cli_create_show_approve_apply( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: from openadapt_flow.txplan.cli import main db = _db(tmp_path / "crm.sqlite") spec = _spec(tmp_path, db=db) writes = tmp_path / "w.json" - writes.write_text(json.dumps({"writes": [{"system": "crm", "collection": "customers", "op": "update", - "id": 6, "fields": {"balance": 3}}]})) + writes.write_text( + json.dumps( + { + "writes": [ + { + "system": "crm", + "collection": "customers", + "op": "update", + "id": 6, + "fields": {"balance": 3}, + } + ] + } + ) + ) assert main(["create", "--tx", str(spec), "--task", "T-cli", str(writes)]) == 0 out = capsys.readouterr().out assert "1 crm.customers updated" in out @@ -469,10 +706,15 @@ def test_cli_create_show_approve_apply(tmp_path: Path, capsys: pytest.CaptureFix def _users(path: Path, n: int = 500) -> Path: con = sqlite3.connect(path) - con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT, active INTEGER)") + con.execute( + "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT, active INTEGER)" + ) con.execute("CREATE TABLE logins (id INTEGER PRIMARY KEY, user_id INTEGER)") for i in range(1, n + 1): - con.execute("INSERT INTO users VALUES (?, ?, ?, 1)", (i, f"user {i}", "admin" if i in (3, 30, 300) else "member")) + con.execute( + "INSERT INTO users VALUES (?, ?, ?, 1)", + (i, f"user {i}", "admin" if i in (3, 30, 300) else "member"), + ) con.commit() con.close() return path @@ -493,14 +735,19 @@ def _all(db: Path) -> list[tuple]: con.close() -def test_proxy_bulk_update_shows_exact_diff_then_applies_once_and_undoes(tmp_path: Path) -> None: +def test_proxy_bulk_update_shows_exact_diff_then_applies_once_and_undoes( + tmp_path: Path, +) -> None: db = _users(tmp_path / "app.sqlite") before = _all(db) proxy = _proxy(db) got = proxy.preview("UPDATE users SET active = 0 WHERE id <= 412") assert got["tables"] == {"users": {"added": 0, "changed": 412, "removed": 0}} assert "rows where users.role = admin" in got["anomalies"] - assert "users: 412 rows changed" in got["summary"] and "= admin: users.role = 3" in got["summary"] + assert ( + "users: 412 rows changed" in got["summary"] + and "= admin: users.role = 3" in got["summary"] + ) assert got["approval"].startswith("waiting for a person") and _all(db) == before with pytest.raises(TxRefused): proxy.apply(got["plan"]) @@ -508,18 +755,24 @@ def test_proxy_bulk_update_shows_exact_diff_then_applies_once_and_undoes(tmp_pat out = proxy.apply(got["plan"]) assert out["outcome"] == "VERIFIED" and out["tx"]["missed_effects"] == 0 con = sqlite3.connect(db) - assert con.execute("SELECT count(*) FROM users WHERE active = 0").fetchone()[0] == 412 + assert ( + con.execute("SELECT count(*) FROM users WHERE active = 0").fetchone()[0] == 412 + ) con.close() undone = proxy.undo(got["plan"]) assert undone["outcome"] == "ROLLED_BACK", undone assert _all(db) == before -def test_proxy_insert_and_delete_round_trip_and_policy_auto_approve(tmp_path: Path) -> None: +def test_proxy_insert_and_delete_round_trip_and_policy_auto_approve( + tmp_path: Path, +) -> None: db = _users(tmp_path / "app.sqlite", n=20) before = _all(db) proxy = _proxy(db, max_rows=5) - a = proxy.preview("INSERT INTO users (name, role, active) VALUES ('new', 'member', 1)") + a = proxy.preview( + "INSERT INTO users (name, role, active) VALUES ('new', 'member', 1)" + ) assert a["approval"] == "approved by policy" assert proxy.apply(a["plan"])["outcome"] == "VERIFIED" b = proxy.preview("DELETE FROM users WHERE id IN (4, 5)") @@ -544,7 +797,9 @@ def test_proxy_commits_only_the_planned_diff(tmp_path: Path) -> None: assert exc.value.code == "plan_stale" and _all(db) == snapshot -def test_proxy_regenerated_statement_after_restore_is_held_not_applied(tmp_path: Path) -> None: +def test_proxy_regenerated_statement_after_restore_is_held_not_applied( + tmp_path: Path, +) -> None: db = _users(tmp_path / "app.sqlite", n=50) proxy = _proxy(db, max_rows=100) a = proxy.preview("UPDATE users SET name = 'refund 100' WHERE id = 9") @@ -556,14 +811,18 @@ def test_proxy_regenerated_statement_after_restore_is_held_not_applied(tmp_path: proxy.apply(b["plan"]) assert exc.value.code in ("not_approved", "replay_mismatch") con = sqlite3.connect(db) - assert con.execute("SELECT name FROM users WHERE id = 9").fetchone()[0] == "refund 100" + assert ( + con.execute("SELECT name FROM users WHERE id = 9").fetchone()[0] == "refund 100" + ) con.close() # The identical statement now changes nothing: its dry run is empty. c = proxy.preview("UPDATE users SET name = 'refund 100' WHERE id = 9") assert c["tables"] == {} -def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child(tmp_path: Path) -> None: +def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child( + tmp_path: Path, +) -> None: import httpx from openadapt_flow.txplan.proxy import McpServer, child_environment @@ -572,20 +831,57 @@ def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child(tmp_path: Path) server = McpServer(_proxy(db, max_rows=10)) server.start() try: - assert httpx.post(server.url, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}).status_code == 401 + assert ( + httpx.post( + server.url, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"} + ).status_code + == 401 + ) h = {"Authorization": f"Bearer {server.token}"} - init = httpx.post(server.url, headers=h, json={"jsonrpc": "2.0", "id": 1, "method": "initialize", - "params": {"protocolVersion": "2025-06-18"}}).json() + init = httpx.post( + server.url, + headers=h, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": {"protocolVersion": "2025-06-18"}, + }, + ).json() assert init["result"]["capabilities"] == {"tools": {}} - names = [t["name"] for t in httpx.post(server.url, headers=h, json={ - "jsonrpc": "2.0", "id": 2, "method": "tools/list"}).json()["result"]["tools"]] + names = [ + t["name"] + for t in httpx.post( + server.url, + headers=h, + json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + ).json()["result"]["tools"] + ] assert names == ["sql_query", "sql_preview", "sql_apply", "sql_undo"] - call = httpx.post(server.url, headers=h, json={"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { - "name": "sql_preview", "arguments": {"sql": "UPDATE users SET active = 0 WHERE id = 2"}}}).json() + call = httpx.post( + server.url, + headers=h, + json={ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "sql_preview", + "arguments": {"sql": "UPDATE users SET active = 0 WHERE id = 2"}, + }, + }, + ).json() body = json.loads(call["result"]["content"][0]["text"]) assert body["approval"] == "approved by policy" finally: server.stop() - env = child_environment({"DATABASE_URL": "postgres://u:pw@h/db", "X": "postgres://u:pw@h/db", - "PGPASSWORD": "pw", "PATH": "/bin"}, ["postgres://u:pw@h/db"]) + env = child_environment( + { + "DATABASE_URL": "postgres://u:pw@h/db", + "X": "postgres://u:pw@h/db", + "PGPASSWORD": "pw", + "PATH": "/bin", + }, + ["postgres://u:pw@h/db"], + ) assert env == {"PATH": "/bin"} diff --git a/packages/flow/tests/txplan_servers.py b/packages/flow/tests/txplan_servers.py index 0ffae1e73d..f4285cedd5 100644 --- a/packages/flow/tests/txplan_servers.py +++ b/packages/flow/tests/txplan_servers.py @@ -29,7 +29,13 @@ def add(self, **fields: Any) -> dict[str, Any]: with self.lock: rid = self.next_id self.next_id += 1 - rec = {"id": rid, "done": False, "done_at": None, **fields, "updated": time.time()} + rec = { + "id": rid, + "done": False, + "done_at": None, + **fields, + "updated": time.time(), + } self.records[rid] = rec return dict(rec) @@ -173,7 +179,11 @@ def _store(self, raw: bytes) -> None: "ID": str(len(self.messages) + 1), "MessageID": str(msg["Message-ID"] or "").strip("<>"), "Subject": str(msg["Subject"] or ""), - "To": [{"Address": a.strip()} for a in str(msg["To"] or "").split(",") if a.strip()], + "To": [ + {"Address": a.strip()} + for a in str(msg["To"] or "").split(",") + if a.strip() + ], } ) From 722fad7534d17706ff6529f9e263cebef4f163d6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:08:03 -0500 Subject: [PATCH 05/21] docs(plan): proxy and transaction docs, CAPABILITIES rows, lab results --- CAPABILITIES.md | 3 + llms-full.txt | 4 + .../ext_tx/results/2026-11-21-apps.json | 1447 +++++++++++ .../ext_tx/results/2026-11-21-apps.log | 93 + .../ext_tx/results/2026-11-21-proxy.json | 2115 +++++++++++++++++ .../ext_tx/results/2026-11-21-proxy.log | 62 + packages/flow/docs/HOOKS.md | 6 + packages/flow/docs/TRANSACTIONS.md | 118 +- 8 files changed, 3843 insertions(+), 5 deletions(-) create mode 100644 packages/flow/benchmark/ext_tx/results/2026-11-21-apps.json create mode 100644 packages/flow/benchmark/ext_tx/results/2026-11-21-apps.log create mode 100644 packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.json create mode 100644 packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.log diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 98ced845b8..c856f2c002 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -324,6 +324,8 @@ improvising or retrying when something is off. | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, this PR | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command, against a local SQLite file and a local HTTP API; no live Claude Code or Codex session) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](packages/flow/docs/HOOKS.md) | +| Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-10 s from empty venv to first diff; one real MCP SDK session | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | +| Dry-run, apply, undo and release a batch of writes to external systems: `openadapt plan create/approve/apply/undo/release/cancel` over an `openadapt.tx.yaml` of REST collections, SQL tables and mail. The diff comes from a staged transaction (SQL), a computed shadow with declared server-set and derived fields (REST) or the holdback queue (email). Approval is single-use and bound to the plan digest, a stale plan is refused, each write's idempotency key comes from the task and the record slot (never the payload), and a retry with a different payload is refused (the ACRFence action-replay attack). The undo is verified by reading back each record and the whole frame. Irreversible writes wait in a cancelable holdback queue | Experimental, this PR | Lab: Vikunja 2.7.1, Dolibarr 21.0.4 on MariaDB, Mailpit; 100 writes each; 0 missed effects, 0 false diffs, 200/200 verified undos (REST, SQL), 50/50 cancelled emails never sent, 50/50 released exactly once, 0/60 regenerated retries through (control 60/60 doubled), 0/10 after a crash after send; seeded faults caught 20/20 | `openadapt plan`, `openadapt_flow/txplan/`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](packages/flow/docs/THREAT_MODEL.md) | | Teach authorization: a person signs what a teaching agent may do (task, origins, inputs, the one write, forbidden actions and controls) with their approver key, and every teach path is bound to it or refused. Verified with the approver roster's own verifier, so an unknown, removed or wrong key, an unpinned root, a changed statement or another task refuses. Admission of every JIT draft needs one (`teach_auth_not_recorded` otherwise), as do an agent-demonstrated fix's approval and self-repair of an agent-taught program; browser-teach writes are bound to it, and the airbag handoff's drafts are refused | On main ([#1436](https://github.com/OpenAdaptAI/OpenAdapt/pull/1436)) | Synthetic (real approver keys, real roster, real admission) | `openadapt-flow teach-authorization`, [TEACH_AUTHORIZATION.md](packages/flow/docs/TEACH_AUTHORIZATION.md) | @@ -489,6 +491,7 @@ A test fails when a command has no file or this list is out of date. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. +- `proxy`: Holds the database credentials and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/llms-full.txt b/llms-full.txt index 6105822f9d..1f1241468c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -763,6 +763,8 @@ improvising or retrying when something is off. | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, this PR | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command, against a local SQLite file and a local HTTP API; no live Claude Code or Codex session) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HOOKS.md) | +| Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-10 s from empty venv to first diff; one real MCP SDK session | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | +| Dry-run, apply, undo and release a batch of writes to external systems: `openadapt plan create/approve/apply/undo/release/cancel` over an `openadapt.tx.yaml` of REST collections, SQL tables and mail. The diff comes from a staged transaction (SQL), a computed shadow with declared server-set and derived fields (REST) or the holdback queue (email). Approval is single-use and bound to the plan digest, a stale plan is refused, each write's idempotency key comes from the task and the record slot (never the payload), and a retry with a different payload is refused (the ACRFence action-replay attack). The undo is verified by reading back each record and the whole frame. Irreversible writes wait in a cancelable holdback queue | Experimental, this PR | Lab: Vikunja 2.7.1, Dolibarr 21.0.4 on MariaDB, Mailpit; 100 writes each; 0 missed effects, 0 false diffs, 200/200 verified undos (REST, SQL), 50/50 cancelled emails never sent, 50/50 released exactly once, 0/60 regenerated retries through (control 60/60 doubled), 0/10 after a crash after send; seeded faults caught 20/20 | `openadapt plan`, `openadapt_flow/txplan/`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/THREAT_MODEL.md) | | Teach authorization: a person signs what a teaching agent may do (task, origins, inputs, the one write, forbidden actions and controls) with their approver key, and every teach path is bound to it or refused. Verified with the approver roster's own verifier, so an unknown, removed or wrong key, an unpinned root, a changed statement or another task refuses. Admission of every JIT draft needs one (`teach_auth_not_recorded` otherwise), as do an agent-demonstrated fix's approval and self-repair of an agent-taught program; browser-teach writes are bound to it, and the airbag handoff's drafts are refused | On main ([#1436](https://github.com/OpenAdaptAI/OpenAdapt/pull/1436)) | Synthetic (real approver keys, real roster, real admission) | `openadapt-flow teach-authorization`, [TEACH_AUTHORIZATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TEACH_AUTHORIZATION.md) | @@ -927,6 +929,8 @@ A test fails when a command has no file or this list is out of date. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +- `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. +- `proxy`: Holds the database credentials and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.json b/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.json new file mode 100644 index 0000000000..c781b8f9fc --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.json @@ -0,0 +1,1447 @@ +{ + "acrfence": { + "mail": { + "blocked": 20, + "control_duplicates": 20, + "double_effects_through": 0, + "identical_replays_not_sent": 20, + "trials": 20 + }, + "rest": { + "blocked": 20, + "control_duplicates": 20, + "double_effects_through": 0, + "identical_replays_not_sent": 20, + "trials": 20 + }, + "sql": { + "blocked": 20, + "control_duplicates": 20, + "double_effects_through": 0, + "identical_replays_not_sent": 20, + "trials": 20 + } + }, + "apps": { + "database": "Dolibarr 21.0.4 on MariaDB 11.4.13", + "email": "Mailpit v1.27.10", + "rest": "Vikunja 2.7.1" + }, + "crash": { + "rest": { + "crashed_after_send": 5, + "double_effects_through": 0, + "trials": 5 + }, + "sql": { + "crashed_after_send": 5, + "double_effects_through": 0, + "trials": 5 + } + }, + "finished_at": "2026-11-21T06:59:55Z", + "phase": "measured", + "rounds": { + "mail": [ + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-3725021886a0a11df63bdf5db0ddc1de4f930296@openadapt.tx#1", + "message/ik-5ea10c281fd20efb9a2879e287fba49ad280ebd5@openadapt.tx#1", + "message/ik-6d8c7f5d05815b2e1392b10b8ebf627a3d69edb5@openadapt.tx#1", + "message/ik-71d62f1da6752e80dafb7e23163bb8e3eb0c3195@openadapt.tx#1", + "message/ik-7256acae4f5147e688fcfa0855eded7fcf70d6d0@openadapt.tx#1" + ], + "digest": "cd9375a2ae2c9818", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-1a8894bd714560ca860b0e91b3ebdd9e289707e5@openadapt.tx#1", + "message/ik-2d0ab4e10eed91d89a627bdf46ac6546d1dfcbd4@openadapt.tx#1", + "message/ik-4248391d0c733e74fdf6deae31482ce68b9a3329@openadapt.tx#1", + "message/ik-4dc495c4b087ef0389397dc5b21ad42d9b09b26d@openadapt.tx#1", + "message/ik-4dcf5ee80d7eee6478e460a9f4c3da7202805c5f@openadapt.tx#1" + ], + "digest": "fcc1e9ba57ef26de", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-22387dca0e214887f808e6c9835237651aee98b6@openadapt.tx#1", + "message/ik-34c65163ae408c191b56996c05659382a63f468e@openadapt.tx#1", + "message/ik-691d57e43dc1815f13de15b4e34fb75461b2bfc1@openadapt.tx#1", + "message/ik-6edba430ed4e314492680c23359bb8965c778b0b@openadapt.tx#1", + "message/ik-89d7d7d0ed5575441afd67a153e0cecf082d045d@openadapt.tx#1" + ], + "digest": "4ce6cd3a713bc2fc", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-091ed5f68cc44586a7c1ea84832a490bda399d17@openadapt.tx#1", + "message/ik-2a10cb52b2e6ca791560b400985c9d4452e5944f@openadapt.tx#1", + "message/ik-430c49a1f9ac5f4cc168a8850117b1877b019942@openadapt.tx#1", + "message/ik-4e204ce076070f7bb4d2d921c753aee725d63f1b@openadapt.tx#1", + "message/ik-561318fff1dfca7ebf126b34d19f77e487ea03a9@openadapt.tx#1" + ], + "digest": "11cb4e870ae89be9", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-02537869218f1990260c52d329615031dc63ac1a@openadapt.tx#1", + "message/ik-0d7b4e283c0cc807e8d27bbb7f32d8c7ba4104ae@openadapt.tx#1", + "message/ik-207837bca468e0d94f950e080f4728e625212e51@openadapt.tx#1", + "message/ik-21657aa732213cc2afd61e0842fdf7f388e64c7f@openadapt.tx#1", + "message/ik-344dc6263cc82f42a0bb72c408730c88de108070@openadapt.tx#1" + ], + "digest": "5314c8543a6ac821", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-239b9101a0f6edf0d1c7eeaee5f6226a03ab4d8a@openadapt.tx#1", + "message/ik-4df710a0fa19136aa18c692215ffbc2740c4df7b@openadapt.tx#1", + "message/ik-7e773d78a6f247d1c8f75264cc82f089ebabc5bb@openadapt.tx#1", + "message/ik-886d8bb3ba18e429c9eee7aeea5ab58432679a43@openadapt.tx#1", + "message/ik-93f2bdbbc2ae93f57eae183c4e5cf447b0c30b9c@openadapt.tx#1" + ], + "digest": "91f84680bb1c9340", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-189512c9cd0b314383d9ffb6ea01f27844fce913@openadapt.tx#1", + "message/ik-3c49aafe87e9e399a5e3e6b297a43f0502b3c622@openadapt.tx#1", + "message/ik-4728d58854ceace3be2900436a2bd7e89c1d521f@openadapt.tx#1", + "message/ik-4fbcc4cb5b2452aea277b61d371a38248daa5956@openadapt.tx#1", + "message/ik-8424392a1d59ae57759a7f0086265e97bdba8cc4@openadapt.tx#1" + ], + "digest": "d11879db93d1b932", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-15d1c3d7e28ca6830f94046d37ac861fdcb35c2c@openadapt.tx#1", + "message/ik-177fdc6b2acfe5777ea148d26df3181b30337cab@openadapt.tx#1", + "message/ik-26b158b699428dc0dccf54c3f1d0a1febb46243e@openadapt.tx#1", + "message/ik-2a20043d7cbb11c9ef86e1f4b309821b9afa9d5c@openadapt.tx#1", + "message/ik-c18a18ac37c3c064cb177ff804c976f243dcb1b3@openadapt.tx#1" + ], + "digest": "0f735f423d8b00d1", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-03bd8dafd3f9bbbf526a15d8060c325a30db6a4f@openadapt.tx#1", + "message/ik-759c2172b48bb1843bdb2302447e454668c45b53@openadapt.tx#1", + "message/ik-79ad9a45c7ca7e7e360370867ce2298a1ca85fe6@openadapt.tx#1", + "message/ik-7cc624df2dc9c6cdcb69d030922516dc5eb1cf3a@openadapt.tx#1", + "message/ik-8f9c6827be564f8a203e267e8eed0557404549ee@openadapt.tx#1" + ], + "digest": "05fc3bb95be6ab33", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-00056e8f1bf54f83734f132925416fb1bd7d9b16@openadapt.tx#1", + "message/ik-0c06849c2241756d897f2d6607104e8d93169d46@openadapt.tx#1", + "message/ik-518fb8ecfcc5b96f3b7d77a422a1a4503257bcb1@openadapt.tx#1", + "message/ik-86310c707c3c9951a78366787f1cc15af8c9b36a@openadapt.tx#1", + "message/ik-9f555e46078bea4ca81c2c133e7db7124af8e96e@openadapt.tx#1" + ], + "digest": "77271b5a992a249b", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + } + ], + "rest": [ + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "6b9e75092d6a6976", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "da3c35e4af01fd3b", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "fc178ed082b6d8ff", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "d0d0b5d3fea39881", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "7eacf181464db861", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "94721fc78d219b0f", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "79c871a7de6d8b23", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "65b169a084e61ac4", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "303e106764a9bb2a", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "2c93cb1c1b5329a1", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + } + ], + "sql": [ + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "8476f1e79828e8dd", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "81f1d60da24cef1d", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "042d3ea9b64a4c51", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "a22a0f2b76a16aa0", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "2b50975877418ad8", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "7b7ed92d267a5123", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "931d3e297f24b606", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "e9199430760f2a18", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "e19d8a8e2bc09d0d", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "8431a58bb0c63fd3", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + } + ] + }, + "schema": "openadapt.ext-tx-lab/v1", + "seeded_faults": { + "rest": { + "collateral_caught": 4, + "missed_effect_caught": 5, + "not_caught": [ + { + "codes": { + "changed_since_apply": 1 + }, + "collateral": 0, + "planned": { + "vikunja:task": { + "added": {}, + "changed": { + "task/119": [ + "priority" + ] + }, + "derived": {}, + "removed": [] + } + }, + "trial": 0, + "undo": "RECONCILIATION_REQUIRED" + } + ], + "trials": 5 + }, + "sql": { + "collateral_caught": 5, + "missed_effect_caught": 5, + "not_caught": [], + "trials": 5 + } + }, + "spec_sha256": "8eeaa89d5cf2f8e6ebf87e692fa966edd628668f9d2a4204328fd603d5ea4088", + "started_at": "2026-11-21T06:49:35Z", + "summary": { + "blocked_double_effects": 60, + "control_duplicates": 60, + "double_effects_through": 0, + "kill_criteria_tripped": [], + "mail": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 50, + "cancelled_never_sent": 50, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 50, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 50, + "released_other": 0, + "rounds": 10, + "undo_success_rate": null, + "undo_supported": 0, + "undo_verified": 0, + "writes": 100 + }, + "rest": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + }, + "sql": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + } + } +} diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.log b/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.log new file mode 100644 index 0000000000..3a8c8a678f --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.log @@ -0,0 +1,93 @@ +[22:49:35] vikunja: 40 tasks; project 6 +[22:49:35] dolibarr: seeded 60 thirdparties +[22:49:36] rest 0: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:37] rest 1: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:38] rest 2: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:39] rest 3: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:40] rest 4: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:41] rest 5: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:42] rest 6: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:42] rest 7: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:43] rest 8: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:44] rest 9: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:49:52] sql 0: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:00] sql 1: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:09] sql 2: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:17] sql 3: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:23] sql 4: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:31] sql 5: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:37] sql 6: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:46] sql 7: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:50:52] sql 8: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:51:01] sql 9: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[22:51:03] mail 0: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:05] mail 1: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:07] mail 2: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:09] mail 3: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:11] mail 4: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:14] mail 5: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:16] mail 6: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:18] mail 7: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:21] mail 8: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:51:23] mail 9: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[22:57:17] acrfence {'rest': {'trials': 20, 'control_duplicates': 20, 'blocked': 20, 'identical_replays_not_sent': 20, 'double_effects_through': 0}, 'sql': {'trials': 20, 'control_duplicates': 20, 'blocked': 20, 'identical_replays_not_sent': 20, 'double_effects_through': 0}, 'mail': {'trials': 20, 'control_duplicates': 20, 'blocked': 20, 'identical_replays_not_sent': 20, 'double_effects_through': 0}} +[22:58:30] crash {'rest': {'trials': 5, 'crashed_after_send': 5, 'double_effects_through': 0}, 'sql': {'trials': 5, 'crashed_after_send': 5, 'double_effects_through': 0}} +[22:59:55] faults {'rest': {'trials': 5, 'missed_effect_caught': 5, 'collateral_caught': 4, 'not_caught': [{'trial': 0, 'undo': 'RECONCILIATION_REQUIRED', 'codes': {'changed_since_apply': 1}, 'collateral': 0, 'planned': {'vikunja:task': {'added': {}, 'changed': {'task/119': ['priority']}, 'removed': [], 'derived': {}}}}]}, 'sql': {'trials': 5, 'missed_effect_caught': 5, 'collateral_caught': 5, 'not_caught': []}} +[22:59:55] dolibarr cleanup: removed 125 lab rows +[22:59:55] { + "blocked_double_effects": 60, + "control_duplicates": 60, + "double_effects_through": 0, + "kill_criteria_tripped": [], + "mail": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 50, + "cancelled_never_sent": 50, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 50, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 50, + "released_other": 0, + "rounds": 10, + "undo_success_rate": null, + "undo_supported": 0, + "undo_verified": 0, + "writes": 100 + }, + "rest": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + }, + "sql": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + } +} diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.json b/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.json new file mode 100644 index 0000000000..aaa22da9f2 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.json @@ -0,0 +1,2115 @@ +{ + "app": "PostgreSQL 16 (synthetic schema)", + "rows": [ + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 1.322, + "rows_touched": 17, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.78, + "rows_touched": 20, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.829, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.778, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.534, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.622, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.585, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 1.004, + "rows_touched": 8, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.628, + "rows_touched": 16, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.537, + "rows_touched": 18, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 1.21, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.893, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.054, + "rows_touched": 9, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 1.414, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 1.122, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 1.017, + "rows_touched": 10, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.938, + "rows_touched": 15, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 1.04, + "rows_touched": 28, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.904, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.861, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.406, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.864, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 2.277, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.793, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.887, + "rows_touched": 61, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.887, + "rows_touched": 40, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 3.01, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 1.106, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.169, + "rows_touched": 10, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 1.043, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.79, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.966, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.804, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 1.889, + "rows_touched": 27, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.868, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.81, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.015, + "rows_touched": 10, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.639, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.651, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.97, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.759, + "rows_touched": 57, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 1.029, + "rows_touched": 18, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.689, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.6, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.577, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.638, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.63, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.613, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.542, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.546, + "rows_touched": 20, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.64, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.599, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.633, + "rows_touched": 4, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.454, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.605, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.687, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.616, + "rows_touched": 39, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.657, + "rows_touched": 15, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.5, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.587, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 0, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.626, + "rows_touched": 0, + "tables": [], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.849, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.874, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 2.399, + "rows_touched": 8, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.852, + "rows_touched": 53, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 1.595, + "rows_touched": 75, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 1.24, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.961, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.843, + "rows_touched": 18, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 1.57, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.844, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.814, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.714, + "rows_touched": 49, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.555, + "rows_touched": 60, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.66, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.87, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.809, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.813, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.723, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.723, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.901, + "rows_touched": 45, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.823, + "rows_touched": 30, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.892, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.692, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 0, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.185, + "rows_touched": 0, + "tables": [], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.836, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.548, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.71, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.68, + "rows_touched": 25, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.564, + "rows_touched": 25, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.78, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.592, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.631, + "rows_touched": 18, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.582, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.612, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.567, + "rows_touched": 8, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.639, + "rows_touched": 40, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.534, + "rows_touched": 15, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.544, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.556, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.604, + "rows_touched": 11, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.549, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.575, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.676, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.95, + "rows_touched": 57, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.651, + "rows_touched": 24, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.64, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.665, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.59, + "rows_touched": 7, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.556, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.594, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.485, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.6, + "rows_touched": 14, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.968, + "rows_touched": 27, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.611, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.812, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.723, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.797, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 1.163, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 1.151, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + } + ], + "schema": "openadapt.ext-tx-proxy-lab/v1", + "started": "2026-11-21T07:05:41Z", + "summary": { + "acrfence": { + "control_duplicates": 20, + "double_effects_through": 0, + "held_not_applied": 20, + "trials": 20 + }, + "apply_verified": 120, + "by_kind": { + "bulk_update": 15, + "delete_cascade": 15, + "delete_where": 15, + "expr_update": 15, + "insert_select": 15, + "insert_values": 15, + "migration_like": 15, + "update_join": 15 + }, + "db_back_to_start": 120, + "false_diffs": 0, + "independent_disagreements": 0, + "mcp_sdk_session": { + "apply": "VERIFIED", + "tools": [ + "sql_query", + "sql_preview", + "sql_apply", + "sql_undo" + ], + "undo": "ROLLED_BACK" + }, + "missed_effects": 0, + "preview_s_median": 0.778, + "rows_touched": 1490, + "statements": 120, + "trigger_probe": { + "apply": "VERIFIED", + "collateral": 5, + "missed": 0, + "predicted_tables": { + "audit": { + "added": 5, + "changed": 0, + "removed": 0 + }, + "users": { + "added": 0, + "changed": 5, + "removed": 0 + } + }, + "undo": "RECONCILIATION_REQUIRED" + }, + "undo_success_rate": 1.0, + "undo_supported": 120, + "undo_verified": 120 + } +} diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.log b/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.log new file mode 100644 index 0000000000..1c5f51dda9 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.log @@ -0,0 +1,62 @@ +NOTICE: database "oa_ext_tx" does not exist, skipping +[23:04:47] 120 statements done +[23:05:37] acrfence {'trials': 20, 'held_not_applied': 20, 'double_effects_through': 0, 'control_duplicates': 20} +[23:05:39] trigger {'predicted_tables': {'audit': {'added': 5, 'changed': 0, 'removed': 0}, 'users': {'added': 0, 'changed': 5, 'removed': 0}}, 'apply': 'VERIFIED', 'missed': 0, 'undo': 'RECONCILIATION_REQUIRED', 'collateral': 5} +[23:05:41] mcp {'tools': ['sql_query', 'sql_preview', 'sql_apply', 'sql_undo'], 'apply': 'VERIFIED', 'undo': 'ROLLED_BACK'} +[23:05:41] { + "acrfence": { + "control_duplicates": 20, + "double_effects_through": 0, + "held_not_applied": 20, + "trials": 20 + }, + "apply_verified": 120, + "by_kind": { + "bulk_update": 15, + "delete_cascade": 15, + "delete_where": 15, + "expr_update": 15, + "insert_select": 15, + "insert_values": 15, + "migration_like": 15, + "update_join": 15 + }, + "db_back_to_start": 120, + "false_diffs": 0, + "independent_disagreements": 0, + "mcp_sdk_session": { + "apply": "VERIFIED", + "tools": [ + "sql_query", + "sql_preview", + "sql_apply", + "sql_undo" + ], + "undo": "ROLLED_BACK" + }, + "missed_effects": 0, + "preview_s_median": 0.778, + "rows_touched": 1490, + "statements": 120, + "trigger_probe": { + "apply": "VERIFIED", + "collateral": 5, + "missed": 0, + "predicted_tables": { + "audit": { + "added": 5, + "changed": 0, + "removed": 0 + }, + "users": { + "added": 0, + "changed": 5, + "removed": 0 + } + }, + "undo": "RECONCILIATION_REQUIRED" + }, + "undo_success_rate": 1.0, + "undo_supported": 120, + "undo_verified": 120 +} diff --git a/packages/flow/docs/HOOKS.md b/packages/flow/docs/HOOKS.md index ca94fe464a..84566c9da4 100644 --- a/packages/flow/docs/HOOKS.md +++ b/packages/flow/docs/HOOKS.md @@ -247,6 +247,12 @@ and no browser handle. A broker for databases, HTTP APIs and MCP servers doesn't exist yet. Until it does, `--strict` refuses instead of installing advisory hooks under a strict name. +For SQL databases, that broker is `openadapt proxy --postgres URL -- claude` +(or `--sqlite`). It holds the credentials, takes them out of the agent's +environment and gives the agent only preview, apply and undo tools +([TRANSACTIONS.md](TRANSACTIONS.md)). Wiring `--strict` to it is the next +step. Until then, `--strict` stays refused. + ## Limits - Hooks are advisory (see the top of this page). diff --git a/packages/flow/docs/TRANSACTIONS.md b/packages/flow/docs/TRANSACTIONS.md index 201cf837d9..1a578d6d3b 100644 --- a/packages/flow/docs/TRANSACTIONS.md +++ b/packages/flow/docs/TRANSACTIONS.md @@ -24,6 +24,72 @@ API, a SQL database, email) four properties: Healthy runs make no model calls. +## The proxy: SQL first + +The quickest way in is a database you already have: + +``` +openadapt proxy --postgres "$DATABASE_URL" -- claude +openadapt proxy --sqlite app.db --flag users.role=admin -- claude +openadapt proxy --sqlite app.db # serve here; keys: y approve, n decline, u undo +``` + +OpenAdapt holds the credentials. The agent gets a Model Context Protocol +endpoint on `127.0.0.1` with a per-run token and four tools: `sql_query`, +`sql_preview`, `sql_apply` and `sql_undo`. The command starts with +`DATABASE_URL`, the `PG*` variables and any copy of the URL removed from its +environment. For `claude`, the proxy passes `--mcp-config`; any other agent +reads `OPENADAPT_MCP_URL`, `OPENADAPT_MCP_TOKEN` and `OPENADAPT_MCP_CONFIG`. +Each write statement goes through five stages: + +1. **Pre-read.** Open a transaction and read every table. +2. **Dry-run diff.** Run the statement, read every table again, and roll + back. The diff is exact and row-level, for example "users: 412 rows + changed" and "rows where users.role = admin: 3". +3. **Gate.** A plan that touches at most `--auto-approve-max-rows` rows (0 by + default) and has no anomaly is approved by policy, and its receipt says + `agent`. Any other plan waits for a person, who presses `y` in the proxy's + terminal or runs `openadapt plan approve` in another one. The approval + binds to the plan digest and is used once. +4. **Execute once.** The statement runs again in a transaction. It commits + only when the diff read inside that transaction is exactly the planned + diff. Otherwise it rolls back (`diverged`). A plan whose database moved + since the dry run is refused before anything runs (`plan_stale`). +5. **Read back and undo.** Every table is read again and compared with the + prediction. The undo images (each changed or removed row's before-image, + and each added row's key) give a generated undo. The undo runs in one + transaction, with each row under a savepoint, so a row that a foreign key + cascade removed is restored after its parent. It is verified when every + table reads back as it was. Each stage writes a signed receipt. + +**Idempotency for raw statements.** A statement's record is the set of rows +it changes or removes, read from the dry run. A regenerated statement after +a restore, such as `balance + 100.00 ... AND active IS NOT NULL` in place of +`balance + 100`, touches the same rows and gets the same key. Because new +work can also touch the same rows, the proxy doesn't refuse it outright. It +marks the plan `possible_replay`, never approves it by policy, and waits for +a person. A statement that only inserts is keyed by its table, with the same +rule. An identical statement after the first apply changes nothing, and its +dry run is empty. + +**What the dry run covers.** It covers SQL effects inside the transaction: +rows, triggers that write rows, and cascades. It does not cover effects +outside the database: a trigger that calls out, `NOTIFY` listeners, email +sent by the application, sequences (a rolled-back `nextval` is not returned), +or MySQL DDL (MySQL commits DDL at once, so it is refused). An app that other +clients also write to needs the read-back: the apply-time diff check refuses +a statement whose effect changed, and `plan_stale` refuses a plan whose +database moved, but a write that lands after the commit is not covered. A +schema change (DDL) on SQLite or PostgreSQL is staged and shown, but has no +generated undo. + +**The credential boundary.** The agent never receives the credentials in its +environment. An agent running as the same OS user with a shell can still read +credentials the user keeps elsewhere, such as a `.env` file or `~/.pgpass`. +For a hard boundary, keep them where the agent's user can't read them. This +is what the hook pack's `--strict` mode needs ([HOOKS.md](HOOKS.md)): with the +proxy, the agent has no write path to the database except the proxy. + ``` openadapt plan create --tx openadapt.tx.yaml --task T-42 writes.json openadapt plan approve 3f2a9c1e # a person, at a terminal; types the digest @@ -128,12 +194,54 @@ direct write is refused and batch writes go through a plan. `openadapt wrap` systems. Like the hooks, this layer is advisory against an agent that holds its own credentials to the system. -## Lab results +## Measured + +All runs took place on 21 November 2026, on the lab laptop's WSL with +synthetic data. The rules (server-set and derived fields, ignored tables) were +fixed after a pilot and before the measured run. The pilot found one engine +bug: an undo of an SQL update didn't restore a column the database sets +itself (`ON UPDATE CURRENT_TIMESTAMP`). It was fixed by restoring the whole +before-image. Results, counts and record ids only, are in +[`benchmark/ext_tx/results/`](../benchmark/ext_tx/results/). + +| Surface | Writes | Missed effects | False diffs | Verified undo | Double effects through | +|---|---|---|---|---|---| +| `openadapt proxy` on PostgreSQL 16: 8 statement kinds, including bulk updates, `INSERT ... SELECT` and cascading deletes | 120 statements, 1,490 rows | 0 | 0 | 120 of 120 (every table back to its start, checked by `psql` checksums) | 0 of 20 regenerated statements (all 20 held for a person); the control arm doubled 20 of 20 | +| Vikunja 2.7.1 (REST, computed dry run) | 100 (60 updates, 40 creates) | 0 | 0 | 100 of 100 | 0 of 20 (20 refused); the control arm doubled 20 of 20 | +| Dolibarr 21.0.4 on MariaDB 11.4.13 (SQL, staged dry run, about 400 tables) | 100 (50 updates, 20 deletes, 30 creates) | 0 | 0 | 100 of 100 | 0 of 20 (20 refused); the control arm doubled 20 of 20 | +| Mailpit v1.27.10 (email, holdback) | 100 sends | 0 | 0 | 50 cancelled in holdback and never sent; 50 released exactly once. A released email has no undo. | 0 of 20 (20 refused); the control arm doubled 20 of 20 | + +- **Crash after the send, before the outcome was recorded** (5 per app, REST + and SQL): the regenerated retry was refused, and the identical retry was + read back and held. The run had no second effect in any of the 10 cases. +- **Identical replays** sent nothing in 60 of 60 cases. +- **The independent read-back** (the verifier's `capture_database` and + `diff_database`) agreed with the proxy's dry run on every table's counts for + all 120 statements. +- **Seeded faults, to show the checks can fail:** + - A change the plan didn't predict, injected during apply, was counted as a + missed effect in 10 of 10 cases. + - A change injected before undo was caught in 10 of 10 cases: as collateral + in 9, and in 1 as `changed_since_apply`, because the injected change hit + the planned record. The undo refused to overwrite it. +- **A trigger probe** (PostgreSQL, outside the measured set): the dry run + showed the trigger's 5 audit rows, and apply found no missed effect. The undo + fires the trigger again, so it reported `RECONCILIATION_REQUIRED` with 5 + collateral rows, never `ROLLED_BACK`. +- **One session over the real MCP client SDK** (`mcp` 1.x, streamable HTTP) + listed the four tools, applied and undid a statement. +- **Setup time.** From an empty virtual environment to the first diff took 8 + to 10 seconds over three runs: install `openadapt-flow`, `openadapt-types` + and `psycopg` with no package cache, then `openadapt-flow proxy --postgres + ... -- ` and its first `sql_preview`. The target was under + 2 minutes. Not included: installing Python and uv, and building the wheels + from source, which stood in for PyPI. The machine was the lab laptop, not + a fresh one. +- **Median dry-run time:** 0.78 s for the 600-user, 1,500-order database. -`benchmark/ext_tx/run.py` runs every flow against real apps on the lab -machine: Vikunja 2.7.1 (REST), Mailpit v1.27.10 (email), and Dolibarr 21.0.4 -on MariaDB 11.4.13 (a database-backed app, written through SQL). The results -are in `benchmark/ext_tx/results/`. See [the summary below](#measured). +The kill criteria were: a verified undo failing on more than 5% of supported +writes, a dry-run diff missing an effect that the read-back found, or a double +effect getting through. None was tripped. ## References From 911ec56a8be9b36383a536a1d3fe1c20fd824aa7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:29:47 -0500 Subject: [PATCH 06/21] fix(proxy): read-only sql_query, overlap-aware replay check, stable default task, receipt status per phase; false diffs fail apply --- packages/flow/benchmark/ext_tx/run.py | 1 - .../flow/openadapt_flow/txplan/adapters.py | 5 +- packages/flow/openadapt_flow/txplan/engine.py | 62 +++++++++++++++++-- packages/flow/openadapt_flow/txplan/proxy.py | 20 ++++-- packages/flow/openadapt_flow/txplan/state.py | 6 ++ packages/flow/tests/test_txplan.py | 36 ++++++++++- tests/test_proxy_plan_commands.py | 41 ++++++++++++ 7 files changed, 159 insertions(+), 12 deletions(-) create mode 100644 tests/test_proxy_plan_commands.py diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py index 7fa9c0c157..9b94302a30 100644 --- a/packages/flow/benchmark/ext_tx/run.py +++ b/packages/flow/benchmark/ext_tx/run.py @@ -32,7 +32,6 @@ import httpx import yaml - from openadapt_flow.txplan import engine from openadapt_flow.txplan.adapters import MailAdapter, RestAdapter, SqlAdapter from openadapt_flow.txplan.engine import Ctx, TxRefused diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index 4040f4827b..df519950fc 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -401,7 +401,7 @@ def __init__(self, system: SqlSystem, root: Any = None) -> None: # connection ------------------------------------------------------------- - def connect(self) -> Any: + def connect(self, *, read_only: bool = False) -> Any: s = self.system if s.dialect == "sqlite": import sqlite3 @@ -410,6 +410,9 @@ def connect(self) -> Any: path = Path(str(s.path)) if not path.is_absolute() and self.root is not None: path = Path(self.root) / path + if read_only: + uri = path.resolve().as_uri() + "?mode=ro" + return sqlite3.connect(uri, uri=True, isolation_level=None) con = sqlite3.connect(str(path), isolation_level=None) return con module = importlib.import_module(str(s.driver)) diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 8cbcddfe7d..2cbfe030e1 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -276,6 +276,19 @@ def _write_run( return run_dir +def receipt_status(run_dir: Path | str) -> str: + """``signed``, or why the phase has no receipt.""" + run_dir = Path(run_dir) + if (run_dir / "receipt.json").exists(): + return "signed" + err = run_dir / "receipt.error.json" + return ( + f"not signed: {read_json(err).get('error', '')[:120]}" + if err.exists() + else "not signed" + ) + + def _line( *, ok: bool, verified: Optional[bool], irreversible: bool, payload: str, code: str ) -> dict[str, Any]: @@ -567,11 +580,15 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str for i, res in zip(idx, pre): d = res["staged_diff"] touched = sorted([*d["changed"], *d["removed"]]) + tables = sorted({r.split("/", 1)[0] for r in d["added"]}) if touched: slots[i] = "rows:" + sha256(touched)[:32] else: - tables = sorted({r.split("/", 1)[0] for r in d["added"]}) slots[i] = "insert:" + ",".join(tables) if tables else "noop" + writes[i]["row_tags"] = sorted( + {state.tag(r) for r in touched} + | {state.tag("insert:" + t) for t in tables} + ) for w, slot in zip(writes, slots): if w["op"] in ("update", "delete"): dup = [ @@ -597,6 +614,13 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str ) w["irreversible"] = _irreversible(spec.system(w["system"]), w) # The ledger first: a key already used under another payload is a replay. + task_tag = state.tag("task:" + task) + applied_rows: dict[str, set[str]] = {} + if any(w["op"] == "sql" for w in writes): + for e in state.entries(): + begun = next((x for x in reversed(e.events) if x["event"] == "begun"), {}) + if e.status not in FREE and begun.get("task_tag") == task_tag: + applied_rows[e.key] = set(begun.get("rows") or []) replays = [] for n, w in enumerate(writes): entry = state.entry(w["key"]) @@ -612,6 +636,14 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str replays.append( {"write": n, "status": w["ledger"], "prior_plan": entry.plan[:12]} ) + elif w["op"] == "sql": + # Overlap, not only the exact row set: `id IN (9, 10)` after `id = 9`. + mine = set(w.get("row_tags") or []) + if any(k != w["key"] and mine & rows for k, rows in applied_rows.items()): + w["ledger"] = "possible_replay" + replays.append( + {"write": n, "status": "possible_replay", "prior_plan": ""} + ) baselines: list[Optional[dict]] = [] for w in writes: base = None @@ -775,7 +807,13 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str approval=None, started=started, ) - return {**core, "digest": digest, "run_dir": str(run), "anomaly_details": anomalies} + return { + **core, + "digest": digest, + "run_dir": str(run), + "receipt": receipt_status(run), + "anomaly_details": anomalies, + } def load_plan(state: State, digest: str) -> tuple[dict[str, Any], dict[str, Any]]: @@ -959,7 +997,14 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: ) continue state.record( - key, "begun", plan=digest, payload=payload, op=w["op"], slot=w["slot"] + key, + "begun", + plan=digest, + payload=payload, + op=w["op"], + slot=w["slot"], + task_tag=state.tag("task:" + plan["task"]), + rows=w.get("row_tags"), ) if w["irreversible"]: release_at = now() + float(plan["holdback_s"]) @@ -1068,7 +1113,7 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: state.plan_dir(digest) / "applied.json", {"images": images, "frames_after": after}, ) - ok = not stop and not missed and not tx["refuted"] + ok = not stop and not missed and not false and not tx["refuted"] outcome = ( "VERIFIED" if ok and not tx.get("held") @@ -1088,6 +1133,7 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: "outcome": outcome, "tx": tx, "run_dir": str(run), + "receipt": receipt_status(run), "missed": missed, "false": false, } @@ -1269,6 +1315,7 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: "outcome": outcome, "tx": tx, "run_dir": str(run), + "receipt": receipt_status(run), "collateral": collateral, } @@ -1386,7 +1433,12 @@ def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, A approval=state.approval_record(digest), started=started, ) - return {"outcome": outcome, "tx": tx, "run_dir": str(run)} + return { + "outcome": outcome, + "tx": tx, + "run_dir": str(run), + "receipt": receipt_status(run), + } def summary_lines(plan: Mapping[str, Any]) -> list[str]: diff --git a/packages/flow/openadapt_flow/txplan/proxy.py b/packages/flow/openadapt_flow/txplan/proxy.py index 9c8ca76a40..b1f6583d3c 100644 --- a/packages/flow/openadapt_flow/txplan/proxy.py +++ b/packages/flow/openadapt_flow/txplan/proxy.py @@ -155,13 +155,22 @@ def adapter(self) -> SqlAdapter: # tools ------------------------------------------------------------------- def query(self, sql: str) -> dict[str, Any]: - """A read, in a transaction that is always rolled back.""" - con = self.adapter.connect() + """One read statement, on a read-only connection or in a read-only + transaction, always rolled back. Anything else is refused.""" + from openadapt_flow.txplan.engine import _READ + + text = sql.strip().rstrip(";").strip() + if ";" in text or not _READ.match(text): + raise ValueError( + "sql_query takes one read statement; use sql_preview for a write" + ) + con = self.adapter.connect(read_only=True) try: cur = con.cursor() self.adapter._begin(cur) if self.adapter.system.dialect == "postgresql": cur.execute("SET TRANSACTION READ ONLY") + sql = text try: cur.execute(sql) cols = [str(d[0]) for d in (cur.description or [])] @@ -510,5 +519,8 @@ def run( shutil.rmtree(tmp, ignore_errors=True) -def default_task() -> str: - return "proxy-" + sha256([os.getpid(), secrets.token_hex(8)])[:16] +def default_task(database: str) -> str: + """One task per database and project folder, stable across restarts, so a + relaunched proxy still knows what this project already wrote. ``--task`` + starts a new one.""" + return "proxy-" + sha256([database, str(Path.cwd().resolve())])[:16] diff --git a/packages/flow/openadapt_flow/txplan/state.py b/packages/flow/openadapt_flow/txplan/state.py index 41ec9b7db3..ff0796e433 100644 --- a/packages/flow/openadapt_flow/txplan/state.py +++ b/packages/flow/openadapt_flow/txplan/state.py @@ -147,6 +147,12 @@ def key_for( ) return "ik-" + hmac.new(self.secret(), body, hashlib.sha256).hexdigest()[:40] + def tag(self, text: str) -> str: + """A keyed tag for a row id or a task: comparable, never the value.""" + return hmac.new( + self.secret(), text.encode("utf-8"), hashlib.sha256 + ).hexdigest()[:20] + # -- the lock ------------------------------------------------------------ @contextlib.contextmanager diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 33412b23f9..48e53ee1f7 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -824,7 +824,6 @@ def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child( tmp_path: Path, ) -> None: import httpx - from openadapt_flow.txplan.proxy import McpServer, child_environment db = _users(tmp_path / "app.sqlite", n=5) @@ -885,3 +884,38 @@ def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child( ["postgres://u:pw@h/db"], ) assert env == {"PATH": "/bin"} + + +def test_proxy_overlapping_rows_after_apply_are_a_possible_replay( + tmp_path: Path, +) -> None: + db = _users(tmp_path / "app.sqlite", n=50) + proxy = _proxy(db, max_rows=100) + a = proxy.preview("UPDATE users SET name = 'refund' WHERE id = 9") + proxy.apply(a["plan"]) + b = proxy.preview("UPDATE users SET name = 'refund again' WHERE id IN (9, 10)") + assert b["ledger"] == "possible_replay" and b["approval"].startswith("waiting") + other = proxy.preview("UPDATE users SET name = 'other' WHERE id IN (11, 12)") + assert other["ledger"] == "free" and other["approval"] == "approved by policy" + + +def test_proxy_query_refuses_a_write(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=5) + before = _all(db) + proxy = _proxy(db) + assert proxy.query("SELECT count(*) FROM users")["rows"] == [[5]] + for bad in ( + "COMMIT; UPDATE users SET name = 'x'", + "UPDATE users SET name = 'x'", + "SELECT 1; DELETE FROM users", + ): + text, is_error = proxy.call("sql_query", {"sql": bad}) + assert is_error, bad + text, is_error = proxy.call( + "sql_query", + { + "sql": "WITH x AS (SELECT 1) INSERT INTO users (name, role, active) SELECT 'y', 'm', 1 FROM x" + }, + ) + assert is_error + assert _all(db) == before diff --git a/tests/test_proxy_plan_commands.py b/tests/test_proxy_plan_commands.py new file mode 100644 index 0000000000..08ff840757 --- /dev/null +++ b/tests/test_proxy_plan_commands.py @@ -0,0 +1,41 @@ +"""The launcher's `openadapt plan` and `openadapt proxy` pass their arguments +through, and `proxy` keeps the agent's command after `--`.""" + +from __future__ import annotations + +import sys + +from click.testing import CliRunner + +from openadapt import cli + + +def _capture(monkeypatch, calls): + monkeypatch.setattr(cli, "_require_supported_python", lambda: None) + + def load(_ctx, modules): + calls.append(("modules", modules)) + return lambda argv: calls.append(("argv", argv)) or 0 + + monkeypatch.setattr(cli, "_optional_engine_entrypoint", load) + + +def test_plan_passes_its_arguments_through(monkeypatch): + calls: list = [] + _capture(monkeypatch, calls) + result = CliRunner().invoke(cli.main, ["plan", "apply", "--tx", "t.yaml", "abc123"]) + assert result.exit_code == 0, result.output + assert calls == [ + ("modules", ("openadapt_flow.txplan.cli",)), + ("argv", ["apply", "--tx", "t.yaml", "abc123"]), + ] + + +def test_proxy_keeps_the_agent_command_after_the_separator(monkeypatch): + calls: list = [] + _capture(monkeypatch, calls) + argv = ["proxy", "--sqlite", "app.db", "--", "claude", "--model", "x"] + monkeypatch.setattr(sys, "argv", ["openadapt", *argv]) + result = CliRunner().invoke(cli.main, argv) + assert result.exit_code == 0, result.output + assert calls[-1] == ("argv", ["--sqlite", "app.db", "--", "claude", "--model", "x"]) From 56ae3c83ba0059c99bcac99a534d003037a43935 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:31:00 -0500 Subject: [PATCH 07/21] style: sort imports after merge --- tests/test_receipt_verify.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_receipt_verify.py b/tests/test_receipt_verify.py index d211695530..112071191b 100644 --- a/tests/test_receipt_verify.py +++ b/tests/test_receipt_verify.py @@ -16,7 +16,6 @@ pytest.importorskip("openadapt_flow.receipt_record") -from openadapt.cli import main # noqa: E402 from openadapt_flow.receipt_record import ( # noqa: E402 build_statement, local_registry, @@ -26,6 +25,8 @@ ) from openadapt_types import receipt as r # noqa: E402 +from openadapt.cli import main # noqa: E402 + BUNDLE = "2" * 64 From 4217bdb0c3b72a21bba690b4d46e5e833b1f5824 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:32:31 -0500 Subject: [PATCH 08/21] test(plan): lab harnesses tally receipts and leftover fixture rows --- packages/flow/benchmark/ext_tx/proxy_lab.py | 8 +++++ .../flow/benchmark/ext_tx/receipts_tally.py | 33 +++++++++++++++++++ packages/flow/benchmark/ext_tx/run.py | 9 +++++ 3 files changed, 50 insertions(+) create mode 100644 packages/flow/benchmark/ext_tx/receipts_tally.py diff --git a/packages/flow/benchmark/ext_tx/proxy_lab.py b/packages/flow/benchmark/ext_tx/proxy_lab.py index 1d33b2102a..6b3f70f98c 100644 --- a/packages/flow/benchmark/ext_tx/proxy_lab.py +++ b/packages/flow/benchmark/ext_tx/proxy_lab.py @@ -291,6 +291,14 @@ def main() -> int: "trigger_probe": trigger, "mcp_sdk_session": mcp_ok, } + try: + sys.path.insert(0, str(Path(__file__).parent)) + from receipts_tally import tally + + summary["receipts"] = tally(proxy.ctx.state.root) + except Exception as exc: # noqa: BLE001 - reported, never hidden + summary["receipts"] = {"error": f"{type(exc).__name__}: {exc}"} + summary["code_sha"] = os.environ.get("LAB_CODE_SHA", "") result = { "schema": "openadapt.ext-tx-proxy-lab/v1", "app": "PostgreSQL 16 (synthetic schema)", diff --git a/packages/flow/benchmark/ext_tx/receipts_tally.py b/packages/flow/benchmark/ext_tx/receipts_tally.py new file mode 100644 index 0000000000..8faafac0b6 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/receipts_tally.py @@ -0,0 +1,33 @@ +"""Count each phase's receipts in a state folder: signed, verified, and the +approval block's approver kind. Counts only.""" + +from __future__ import annotations + +import json +from collections import Counter +from pathlib import Path +from typing import Any + + +def tally(state_root: Path) -> dict[str, Any]: + from openadapt_flow.receipt_record import local_registry, verify_run_receipt + + registry = local_registry() + out: dict[str, Counter] = {} + for run in sorted((Path(state_root) / "runs").iterdir()): + report = json.loads((run / "report.json").read_text()) + phase = report.get("workflow_name", "?") + c = out.setdefault(phase, Counter()) + c["runs"] += 1 + if not (run / "receipt.json").exists(): + c["not_signed"] += 1 + continue + got = verify_run_receipt(run, registry) + c["verified" if got.ok else "verify_failed"] += 1 + if got.ok: + approval = got.statement["predicate"].get("approval") or {} + c[f"approver_{approval.get('approver_kind', 'absent')}"] += 1 + bound = report.get("approval", {}).get("approvals") or [] + if bound and all(a.get("request_sha256") == report.get("plan_sha256") for a in bound): + c["approval_bound_to_plan_digest"] += 1 + return {k: dict(v) for k, v in sorted(out.items())} diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py index 9b94302a30..79de113d9e 100644 --- a/packages/flow/benchmark/ext_tx/run.py +++ b/packages/flow/benchmark/ext_tx/run.py @@ -718,6 +718,15 @@ def sql_poke() -> None: finally: removed = doli_cleanup(sql) log(f"dolibarr cleanup: removed {removed} lab rows") + results["dolibarr_lab_rows_left"] = doli_cleanup(sql) + try: + sys.path.insert(0, str(Path(__file__).parent)) + from receipts_tally import tally + + results["receipts"] = tally(ctx.state.root) + except Exception as exc: # noqa: BLE001 - reported, never hidden + results["receipts"] = {"error": f"{type(exc).__name__}: {exc}"} + results["code_sha"] = os.environ.get("LAB_CODE_SHA", "") results["finished_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) results["summary"] = summarize(results) Path(args.out).parent.mkdir(parents=True, exist_ok=True) From 2668a20f6d955de4fb7cd50b5a79a91e515b9b6f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:32:43 -0500 Subject: [PATCH 09/21] style: import order --- packages/flow/benchmark/ext_tx/run.py | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py index 79de113d9e..92045a7ca6 100644 --- a/packages/flow/benchmark/ext_tx/run.py +++ b/packages/flow/benchmark/ext_tx/run.py @@ -32,6 +32,7 @@ import httpx import yaml + from openadapt_flow.txplan import engine from openadapt_flow.txplan.adapters import MailAdapter, RestAdapter, SqlAdapter from openadapt_flow.txplan.engine import Ctx, TxRefused From f8f1fde8a2ad3bf4a7a097c3b557d2a93e5e3e80 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:37:47 -0500 Subject: [PATCH 10/21] fix(proxy): default task in the flow CLI path; test the flow CLI end to end --- .../flow/openadapt_flow/txplan/proxy_cli.py | 7 +++-- packages/flow/tests/test_txplan.py | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/txplan/proxy_cli.py b/packages/flow/openadapt_flow/txplan/proxy_cli.py index 67c3d28cc5..b58b3aeb3b 100644 --- a/packages/flow/openadapt_flow/txplan/proxy_cli.py +++ b/packages/flow/openadapt_flow/txplan/proxy_cli.py @@ -76,7 +76,9 @@ def add_parser(sub: argparse._SubParsersAction) -> None: p.add_argument( "command", nargs=argparse.REMAINDER, help="-- COMMAND ... (the agent)" ) - p.set_defaults(func=lambda a: _run(a, [x for x in a.command if x != "--"][:None])) + p.set_defaults( + func=lambda a: _run(a, a.command[1:] if a.command[:1] == ["--"] else a.command) + ) def _run(args: argparse.Namespace, command: Sequence[str]) -> int: @@ -98,7 +100,8 @@ def _run(args: argparse.Namespace, command: Sequence[str]) -> int: command, spec=spec, state=state, - task=args.task or default_task(), + task=args.task + or default_task(args.postgres or str(Path(args.sqlite).resolve())), secrets_=[args.postgres] if args.postgres else [], port=args.port, ) diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 48e53ee1f7..9b88906f5c 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -824,6 +824,7 @@ def test_proxy_mcp_endpoint_needs_its_token_and_scrubs_the_child( tmp_path: Path, ) -> None: import httpx + from openadapt_flow.txplan.proxy import McpServer, child_environment db = _users(tmp_path / "app.sqlite", n=5) @@ -919,3 +920,30 @@ def test_proxy_query_refuses_a_write(tmp_path: Path) -> None: ) assert is_error assert _all(db) == before + + +def test_flow_cli_proxy_runs_the_command_with_scrubbed_env( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from openadapt_flow.__main__ import main as flow_main + + db = _users(tmp_path / "app.sqlite", n=10) + out = tmp_path / "child.json" + child = ( + "import json, os, sys; json.dump({k: os.environ.get(k) for k in " + "('OPENADAPT_MCP_URL', 'OPENADAPT_TASK', 'DATABASE_URL')}, open(sys.argv[1], 'w'))" + ) + monkeypatch.setenv("DATABASE_URL", "postgres://u:pw@h/db") + try: + code = flow_main( + ["proxy", "--sqlite", str(db), "--", sys.executable, "-c", child, str(out)] + ) + except SystemExit as exc: + code = exc.code + assert code in (0, None) + got = json.loads(out.read_text()) + assert ( + got["OPENADAPT_MCP_URL"].startswith("http://127.0.0.1:") + and got["DATABASE_URL"] is None + ) + assert got["OPENADAPT_TASK"].startswith("proxy-") From c88d728c77fa822ec1b3ffb9638b52047970cdd5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:43:12 -0500 Subject: [PATCH 11/21] fix(proxy): commit only the planned values (column digests), volatile columns from a second dry run, extra toolset hook; live Claude Code evidence --- .../results/2026-11-21-live-claude-code.md | 35 ++++++ packages/flow/docs/TRANSACTIONS.md | 13 ++- .../flow/openadapt_flow/txplan/adapters.py | 103 +++++++++++++++++- packages/flow/openadapt_flow/txplan/engine.py | 32 +++++- packages/flow/openadapt_flow/txplan/proxy.py | 20 +++- packages/flow/tests/test_txplan.py | 74 +++++++++++++ 6 files changed, 269 insertions(+), 8 deletions(-) create mode 100644 packages/flow/benchmark/ext_tx/results/2026-11-21-live-claude-code.md diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-live-claude-code.md b/packages/flow/benchmark/ext_tx/results/2026-11-21-live-claude-code.md new file mode 100644 index 0000000000..e7afb18d45 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/2026-11-21-live-claude-code.md @@ -0,0 +1,35 @@ +# Live Claude Code session through openadapt proxy (2026-11-21) + +Claude Code 2.1.305, `claude -p --model sonnet`, headless on the Mac, with `--allowedTools` limited to the proxy's MCP tools. A synthetic SQLite file of 200 users, 8 of them admins. The command was `python -m openadapt_flow proxy --sqlite app.db --flag users.role=admin -- claude -p ...`, run twice. Both runs used the same default task (one per database and folder), so the second proxy run kept the first run's plan. + +1. **Session 1** previewed `UPDATE users SET active = 0 WHERE id <= 60`. The diff showed 60 rows changed, 2 of them admins, which is over the auto-approve limit of 0, so the plan was held. `sql_apply` was refused (`not_approved`), and the database was unchanged. +2. **Approval:** `openadapt-flow plan approve --automation`. Scripted, so the receipt says agent. +3. **Session 2** applied the plan (`VERIFIED`) and counted 60 inactive users, then undid it (`ROLLED_BACK`, 0 collateral) and counted 0. + +Four receipts: plan, the refused apply, the apply and the undo. All four were signed and verified with `verify_run_receipt`. + +## Session 1 (agent final message) +``` +The update was not applied. `sql_apply` refused the plan because no person has approved it. + +**sql_preview** (`UPDATE users SET active = 0 WHERE id <= 60`) returned: +- **Plan id:** `dcb0dd063377d1b1` +- **Diff:** `users` has 0 rows added, 60 changed and 0 removed. +- **Anomalies:** + - 60 rows is more than the auto-approve limit. + - Some of the affected rows have `users.role = admin` (`users.role = 2`). +- **Approval:** waiting for a person. They can press `y` in the proxy terminal or run `openadapt plan approve dcb0dd063377d1b1`. + +**sql_apply** (`dcb0dd063377d1b1`) returned `{"refused": "not_approved", "detail": "dcb0dd063377"}`. + +I didn't try to get around the approval step. The plan includes admin accounts, so you may want to check it before approving. After someone approves it, I can call `sql_apply` again. +``` +## Session 2 (agent final message) +``` +All four calls are done, so there's nothing left to continue. + +1. **sql_apply:** The outcome was VERIFIED. It made 1 write, which was confirmed, with 0 refuted and 0 missed effects. +2. **sql_query:** 60 users had `active = 0` after the apply. +3. **sql_undo:** The outcome was ROLLED_BACK. The undo was verified, with 0 collateral changes. +4. **sql_query:** 0 users had `active = 0` after the undo. +``` diff --git a/packages/flow/docs/TRANSACTIONS.md b/packages/flow/docs/TRANSACTIONS.md index 1a578d6d3b..b4a81ae3b8 100644 --- a/packages/flow/docs/TRANSACTIONS.md +++ b/packages/flow/docs/TRANSACTIONS.md @@ -53,7 +53,13 @@ Each write statement goes through five stages: binds to the plan digest and is used once. 4. **Execute once.** The statement runs again in a transaction. It commits only when the diff read inside that transaction is exactly the planned - diff. Otherwise it rolls back (`diverged`). A plan whose database moved + diff: the same rows, the same changed columns and the same values (column + digests). Added rows are compared without their generated keys. + Otherwise it rolls back (`diverged`). The dry run is staged twice. A + column whose value differs between the two runs is *volatile* and is not + compared: `now()`, a time default, or a timestamp within ten minutes of + now. A volatile column that isn't a time, such as `random()`, is an + anomaly, so the plan waits for a person. A plan whose database moved since the dry run is refused before anything runs (`plan_stale`). 5. **Read back and undo.** Every table is read again and compared with the prediction. The undo images (each changed or removed row's before-image, @@ -68,7 +74,10 @@ a restore, such as `balance + 100.00 ... AND active IS NOT NULL` in place of `balance + 100`, touches the same rows and gets the same key. Because new work can also touch the same rows, the proxy doesn't refuse it outright. It marks the plan `possible_replay`, never approves it by policy, and waits for -a person. A statement that only inserts is keyed by its table, with the same +a person. Any overlap with rows the task already wrote counts, not only the +exact same set: `id IN (9, 10)` after `id = 9` is held too. The default task +is one per database and project folder, stable across proxy restarts. Use +`--task` to start a new one. A statement that only inserts is keyed by its table, with the same rule. An identical statement after the first apply changes nothing, and its dry run is empty. diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index df519950fc..1a1875fe3f 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -52,6 +52,94 @@ class Diverged(AdapterError): """The statement did something other than the plan showed. Nothing landed.""" +def after_raw( + diff: Mapping[str, Any], + frame: Mapping[str, Mapping[str, str]], + rows: Mapping[str, Any], +) -> dict[str, Any]: + """The column digests a statement left: each changed row by id, and each + added row without its primary key (a sequence may give it another id).""" + added: dict[str, list[dict[str, str]]] = {} + for rid in diff["added"]: + table = rid.split("/", 1)[0] + pk = set((rows.get(rid) or {}).get("pk") or []) + added.setdefault(table, []).append( + {c: d for c, d in frame[rid].items() if c not in pk} + ) + kinds: dict[str, str] = {} + recent: set[str] = set() + for rid in [*diff["added"], *diff["changed"]]: + table = rid.split("/", 1)[0] + for c, v in ((rows.get(rid) or {}).get("row") or {}).items(): + when = _as_time(v) + if kinds.get(f"{table}.{c}") != "other": + kinds[f"{table}.{c}"] = "time" if when is not None else "other" + if when is not None and abs(time.time() - when) < 600: + recent.add(f"{table}.{c}") # "now", to the second: may differ at apply + return { + "changed": {rid: dict(frame[rid]) for rid in diff["changed"]}, + "added": added, + "kinds": kinds, + "recent_time": sorted(recent), + } + + +_TIME_TEXT = re.compile( + r"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$" +) + + +def _as_time(v: Any) -> Optional[float]: + """A tagged datetime, or ISO-looking text, as epoch seconds (naive = UTC or + local, whichever is closer to now).""" + raw = v.get("v") if isinstance(v, dict) and v.get("$t") == "dt" else v + if not isinstance(raw, str) or not _TIME_TEXT.match(raw): + return None + try: + t = _dt.datetime.fromisoformat(raw.replace("Z", "+00:00").replace(" ", "T")) + except ValueError: + return None + if t.tzinfo is not None: + return t.timestamp() + utc = t.replace(tzinfo=_dt.timezone.utc).timestamp() + local = t.timestamp() + return min((utc, local), key=lambda x: abs(time.time() - x)) + + +def volatile_columns(a: Mapping[str, Any], b: Mapping[str, Any]) -> list[str]: + """``table.column`` values that differ between two staged runs of the same + statement (``now()``, ``random()``, a time default): not compared.""" + out: set[str] = set(a.get("recent_time", [])) | set(b.get("recent_time", [])) + for rid in set(a["changed"]) | set(b["changed"]): + x, y = a["changed"].get(rid, {}), b["changed"].get(rid, {}) + t = rid.split("/", 1)[0] + out |= {f"{t}.{c}" for c in set(x) | set(y) if x.get(c) != y.get(c)} + for t in set(a["added"]) | set(b["added"]): + xs, ys = a["added"].get(t, []), b["added"].get(t, []) + for c in {c for r in [*xs, *ys] for c in r}: + if sorted(r.get(c, "") for r in xs) != sorted(r.get(c, "") for r in ys): + out.add(f"{t}.{c}") + return sorted(out) + + +def after_image(raw: Mapping[str, Any], volatile: Sequence[str]) -> dict[str, Any]: + """``after_raw`` without the volatile columns, in a comparable form.""" + skip = set(volatile) + changed = { + rid: { + c: d for c, d in cols.items() if f"{rid.split('/', 1)[0]}.{c}" not in skip + } + for rid, cols in sorted(raw["changed"].items()) + } + added = { + t: sorted( + digest({c: d for c, d in r.items() if f"{t}.{c}" not in skip}) for r in rs + ) + for t, rs in sorted(raw["added"].items()) + } + return {"changed": changed, "added": added} + + def _shape(diff: Mapping[str, Any]) -> tuple[Any, ...]: """A diff, comparable across runs: ids added by a sequence can differ, so added rows count per table.""" @@ -648,8 +736,12 @@ def stage( for w, b in zip(writes, baselines): result = self._exec(cur, w, b) if w["op"] == "sql": - now_ = self.frame_cur(cur) + now_rows: dict[str, Any] = {} + now_ = self.frame_cur(cur, now_rows) result["staged_diff"] = diff_frames(prev, now_) + result["after_raw"] = after_raw( + result["staged_diff"], now_, now_rows + ) result["before_rows"] = { rid: rows[rid]["row"] for rid in [ @@ -708,10 +800,15 @@ def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: after_rows: dict[str, Any] = {} after = self.frame_cur(cur, after_rows) diff = diff_frames(before, after) - if _shape(diff) != _shape(want): + got_after = after_image( + after_raw(diff, after, after_rows), write.get("volatile") or [] + ) + if _shape(diff) != _shape(want) or ( + "staged_after" in write and got_after != write["staged_after"] + ): con.rollback() raise Diverged( - "the statement's diff is not the planned diff; rolled back" + "the statement's rows or values are not the planned ones; rolled back" ) images = { "before": { diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 2cbfe030e1..55a6113bec 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -30,9 +30,11 @@ MailAdapter, SqlAdapter, adapter_for, + after_image, column_digests, diff_frames, same, + volatile_columns, ) from openadapt_flow.txplan.spec import ( Collection, @@ -370,6 +372,15 @@ def _row_anomalies( "detail": "ddl", } ) + if w.get("volatile_other"): + found.append( + { + "label": "values differ between dry runs (not compared at apply)", + "write": n, + "detail": "volatile", + "value": ", ".join(w["volatile_other"]), + } + ) return found @@ -677,6 +688,21 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str [writes[i] for i in idx], [baselines[i] for i in idx] ) _merge(predicted[f"{name}:*"], _staged_to_prediction(diff)) + if any(writes[i]["op"] == "sql" for i in idx): + # A second staged run finds the columns a statement sets differently + # each time (now(), random(), a time default): apply doesn't compare them. + _, again = ctx.adapter(name).stage( + [writes[i] for i in idx], [baselines[i] for i in idx] + ) + for i, res, res2 in zip(idx, results, again): + if writes[i]["op"] == "sql": + vol = volatile_columns(res["after_raw"], res2["after_raw"]) + writes[i]["volatile"] = vol + kinds = res["after_raw"].get("kinds", {}) + writes[i]["volatile_other"] = [ + c for c in vol if kinds.get(c) != "time" + ] + writes[i]["staged_after"] = after_image(res["after_raw"], vol) for i, res in zip(idx, results): if writes[i]["op"] == "sql": writes[i]["staged_diff"] = res["staged_diff"] @@ -759,7 +785,11 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str ) }, **( - {"ddl": w["ddl"], "staged_diff": _counts(w.get("staged_diff"))} + { + "ddl": w["ddl"], + "staged_diff": _counts(w.get("staged_diff")), + "volatile": w.get("volatile", []), + } if w["op"] == "sql" else {} ), diff --git a/packages/flow/openadapt_flow/txplan/proxy.py b/packages/flow/openadapt_flow/txplan/proxy.py index b1f6583d3c..fae93abaef 100644 --- a/packages/flow/openadapt_flow/txplan/proxy.py +++ b/packages/flow/openadapt_flow/txplan/proxy.py @@ -138,8 +138,17 @@ class Proxy: """The tools, over one database, for one task (this proxy session).""" def __init__( - self, ctx: Ctx, *, task: str, system: str = "db", interactive: bool = False + self, + ctx: Ctx, + *, + task: str, + system: str = "db", + interactive: bool = False, + extra: Any = None, ) -> None: + #: Another toolset served by the same endpoint: an object with + #: ``tools() -> list[dict]`` and ``call(name, args) -> (text, is_error)``. + self.extra = extra self.ctx = ctx self.task = task self.system = system @@ -255,6 +264,10 @@ def call(self, name: str, args: Mapping[str, Any]) -> tuple[str, bool]: got = self.apply(str(args["plan"])) elif name == "sql_undo": got = self.undo(str(args["plan"])) + elif self.extra is not None and name in { + t["name"] for t in self.extra.tools() + }: + return self.extra.call(name, args) else: return f"unknown tool {name}", True except TxRefused as exc: @@ -269,6 +282,9 @@ def call(self, name: str, args: Mapping[str, Any]) -> tuple[str, bool]: ), True return json.dumps(got, default=str), False + def tools(self) -> list[dict[str, Any]]: + return [*TOOLS, *(self.extra.tools() if self.extra is not None else [])] + # the person's keys --------------------------------------------------------- def key(self, ch: str) -> str: @@ -416,7 +432,7 @@ def handle(self, msg: Mapping[str, Any]) -> Optional[dict[str, Any]]: elif method == "ping": result = {} elif method == "tools/list": - result = {"tools": TOOLS} + result = {"tools": self.proxy.tools()} elif method == "tools/call": params = msg.get("params") or {} text, is_error = self.proxy.call( diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 9b88906f5c..bf00f8bc36 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -947,3 +947,77 @@ def test_flow_cli_proxy_runs_the_command_with_scrubbed_env( and got["DATABASE_URL"] is None ) assert got["OPENADAPT_TASK"].startswith("proxy-") + + +def test_proxy_commits_only_the_planned_values(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=10) + proxy = _proxy(db, max_rows=100) + got = proxy.preview("UPDATE users SET role = 'viewer' WHERE id = 3") + digest = proxy.ctx.state.find_plan(got["plan"]) + priv_path = proxy.ctx.state.plan_dir(digest) / "private.json" + priv = json.loads(priv_path.read_text()) + w = priv["writes"][0] + w["fields"]["sql"] = ( + "UPDATE users SET role = 'admin' WHERE id = 3" # same row, same column + ) + priv_path.write_text(json.dumps(priv)) + before = _all(db) + with pytest.raises(TxRefused): + proxy.apply(got["plan"]) + assert _all(db) == before + + +def test_proxy_time_defaults_are_volatile_and_random_values_are_flagged( + tmp_path: Path, +) -> None: + db = tmp_path / "app.sqlite" + con = sqlite3.connect(db) + con.execute( + "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT, created TEXT DEFAULT CURRENT_TIMESTAMP)" + ) + con.commit() + con.close() + from openadapt_flow.txplan.proxy import Proxy, sql_spec + + proxy = Proxy( + Ctx(spec=sql_spec(sqlite=str(db), max_rows=10), state=State()), task="T-vol" + ) + a = proxy.preview("INSERT INTO notes (body) VALUES ('hi')") + assert a["approval"] == "approved by policy" + import time as _t + + _t.sleep(1.1) # CURRENT_TIMESTAMP moves on: still the planned row + assert proxy.apply(a["plan"])["outcome"] == "VERIFIED" + b = proxy.preview("UPDATE notes SET body = hex(randomblob(8))") + assert any("differ between dry runs" in x for x in b["anomalies"]) + assert b["approval"].startswith("waiting") + + +def test_proxy_serves_an_extra_toolset(tmp_path: Path) -> None: + class Extra: + def tools(self) -> list[dict[str, Any]]: + return [ + { + "name": "api_read", + "description": "x", + "inputSchema": {"type": "object"}, + } + ] + + def call(self, name: str, args: Any) -> tuple[str, bool]: + return json.dumps({"tool": name}), False + + from openadapt_flow.txplan.proxy import McpServer, Proxy, sql_spec + + db = _users(tmp_path / "app.sqlite", n=3) + proxy = Proxy( + Ctx(spec=sql_spec(sqlite=str(db)), state=State()), task="T-x", extra=Extra() + ) + server = McpServer(proxy) + names = [ + t["name"] + for t in server.handle({"id": 1, "method": "tools/list"})["result"]["tools"] + ] + assert names[-1] == "api_read" and "sql_preview" in names + assert proxy.call("api_read", {}) == ('{"tool": "api_read"}', False) + server.http.server_close() From 33ee1032d0e3512b1f6a96dcfd977ce7c5523bce Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:27:04 -0500 Subject: [PATCH 12/21] docs(plan): run 2 results with signed receipts, live Claude Code session, setup times --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- ...21-apps.json => run1-2026-11-21-apps.json} | 0 ...1-21-apps.log => run1-2026-11-21-apps.log} | 0 ...-proxy.json => run1-2026-11-21-proxy.json} | 0 ...21-proxy.log => run1-2026-11-21-proxy.log} | 0 .../ext_tx/results/run2-2026-11-21-apps.json | 1453 +++++++++++ .../ext_tx/results/run2-2026-11-21-apps.log | 93 + .../ext_tx/results/run2-2026-11-21-proxy.json | 2138 +++++++++++++++++ .../ext_tx/results/run2-2026-11-21-proxy.log | 85 + packages/flow/docs/TRANSACTIONS.md | 75 +- 11 files changed, 3817 insertions(+), 31 deletions(-) rename packages/flow/benchmark/ext_tx/results/{2026-11-21-apps.json => run1-2026-11-21-apps.json} (100%) rename packages/flow/benchmark/ext_tx/results/{2026-11-21-apps.log => run1-2026-11-21-apps.log} (100%) rename packages/flow/benchmark/ext_tx/results/{2026-11-21-proxy.json => run1-2026-11-21-proxy.json} (100%) rename packages/flow/benchmark/ext_tx/results/{2026-11-21-proxy.log => run1-2026-11-21-proxy.log} (100%) create mode 100644 packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.json create mode 100644 packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.log create mode 100644 packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.json create mode 100644 packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.log diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7eb3445f3d..99380e4833 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -324,7 +324,7 @@ improvising or retrying when something is off. | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, PR [#2411](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411) | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command; one run of live headless Claude Code 2.1.305 and Codex CLI 0.144.4 sessions, both against a local SQLite file and HTTP API: declared writes VERIFIED, an out-of-scope delete blocked, a broken read-back UNCERTAIN, and a Python write that builds the path at run time not seen, [hooks_live](packages/flow/benchmark/hooks_live/README.md)) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](packages/flow/docs/HOOKS.md) | -| Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-10 s from empty venv to first diff; one real MCP SDK session | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | +| Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-12 s from empty venv to first diff; one real MCP SDK session; one live headless Claude Code session (held, then applied and undone) | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | | Dry-run, apply, undo and release a batch of writes to external systems: `openadapt plan create/approve/apply/undo/release/cancel` over an `openadapt.tx.yaml` of REST collections, SQL tables and mail. The diff comes from a staged transaction (SQL), a computed shadow with declared server-set and derived fields (REST) or the holdback queue (email). Approval is single-use and bound to the plan digest, a stale plan is refused, each write's idempotency key comes from the task and the record slot (never the payload), and a retry with a different payload is refused (the ACRFence action-replay attack). The undo is verified by reading back each record and the whole frame. Irreversible writes wait in a cancelable holdback queue | Experimental, this PR | Lab: Vikunja 2.7.1, Dolibarr 21.0.4 on MariaDB, Mailpit; 100 writes each; 0 missed effects, 0 false diffs, 200/200 verified undos (REST, SQL), 50/50 cancelled emails never sent, 50/50 released exactly once, 0/60 regenerated retries through (control 60/60 doubled), 0/10 after a crash after send; seeded faults caught 20/20 | `openadapt plan`, `openadapt_flow/txplan/`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](packages/flow/docs/THREAT_MODEL.md) | diff --git a/llms-full.txt b/llms-full.txt index 19bd96f6ef..17d2c4f690 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -763,7 +763,7 @@ improvising or retrying when something is off. | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, PR [#2411](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411) | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command; one run of live headless Claude Code 2.1.305 and Codex CLI 0.144.4 sessions, both against a local SQLite file and HTTP API: declared writes VERIFIED, an out-of-scope delete blocked, a broken read-back UNCERTAIN, and a Python write that builds the path at run time not seen, [hooks_live](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/hooks_live/README.md)) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HOOKS.md) | -| Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-10 s from empty venv to first diff; one real MCP SDK session | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | +| Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-12 s from empty venv to first diff; one real MCP SDK session; one live headless Claude Code session (held, then applied and undone) | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | | Dry-run, apply, undo and release a batch of writes to external systems: `openadapt plan create/approve/apply/undo/release/cancel` over an `openadapt.tx.yaml` of REST collections, SQL tables and mail. The diff comes from a staged transaction (SQL), a computed shadow with declared server-set and derived fields (REST) or the holdback queue (email). Approval is single-use and bound to the plan digest, a stale plan is refused, each write's idempotency key comes from the task and the record slot (never the payload), and a retry with a different payload is refused (the ACRFence action-replay attack). The undo is verified by reading back each record and the whole frame. Irreversible writes wait in a cancelable holdback queue | Experimental, this PR | Lab: Vikunja 2.7.1, Dolibarr 21.0.4 on MariaDB, Mailpit; 100 writes each; 0 missed effects, 0 false diffs, 200/200 verified undos (REST, SQL), 50/50 cancelled emails never sent, 50/50 released exactly once, 0/60 regenerated retries through (control 60/60 doubled), 0/10 after a crash after send; seeded faults caught 20/20 | `openadapt plan`, `openadapt_flow/txplan/`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/THREAT_MODEL.md) | diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.json b/packages/flow/benchmark/ext_tx/results/run1-2026-11-21-apps.json similarity index 100% rename from packages/flow/benchmark/ext_tx/results/2026-11-21-apps.json rename to packages/flow/benchmark/ext_tx/results/run1-2026-11-21-apps.json diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-apps.log b/packages/flow/benchmark/ext_tx/results/run1-2026-11-21-apps.log similarity index 100% rename from packages/flow/benchmark/ext_tx/results/2026-11-21-apps.log rename to packages/flow/benchmark/ext_tx/results/run1-2026-11-21-apps.log diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.json b/packages/flow/benchmark/ext_tx/results/run1-2026-11-21-proxy.json similarity index 100% rename from packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.json rename to packages/flow/benchmark/ext_tx/results/run1-2026-11-21-proxy.json diff --git a/packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.log b/packages/flow/benchmark/ext_tx/results/run1-2026-11-21-proxy.log similarity index 100% rename from packages/flow/benchmark/ext_tx/results/2026-11-21-proxy.log rename to packages/flow/benchmark/ext_tx/results/run1-2026-11-21-proxy.log diff --git a/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.json b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.json new file mode 100644 index 0000000000..059ac2f449 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.json @@ -0,0 +1,1453 @@ +{ + "acrfence": { + "mail": { + "blocked": 20, + "control_duplicates": 20, + "double_effects_through": 0, + "identical_replays_not_sent": 20, + "trials": 20 + }, + "rest": { + "blocked": 20, + "control_duplicates": 20, + "double_effects_through": 0, + "identical_replays_not_sent": 20, + "trials": 20 + }, + "sql": { + "blocked": 20, + "control_duplicates": 20, + "double_effects_through": 0, + "identical_replays_not_sent": 20, + "trials": 20 + } + }, + "apps": { + "database": "Dolibarr 21.0.4 on MariaDB 11.4.13", + "email": "Mailpit v1.27.10", + "rest": "Vikunja 2.7.1" + }, + "code_sha": "2668a20f6d955de4fb7cd50b5a79a91e515b9b6f", + "crash": { + "rest": { + "crashed_after_send": 5, + "double_effects_through": 0, + "trials": 5 + }, + "sql": { + "crashed_after_send": 5, + "double_effects_through": 0, + "trials": 5 + } + }, + "dolibarr_lab_rows_left": 0, + "finished_at": "2026-11-21T07:44:22Z", + "phase": "measured", + "receipts": { + "tx-apply": { + "approval_bound_to_plan_digest": 250, + "approver_agent": 250, + "runs": 250, + "verified": 250 + }, + "tx-plan": { + "approver_none": 260, + "runs": 260, + "verified": 260 + }, + "tx-release": { + "approval_bound_to_plan_digest": 50, + "approver_agent": 50, + "runs": 50, + "verified": 50 + }, + "tx-undo": { + "approval_bound_to_plan_digest": 50, + "approver_agent": 50, + "runs": 50, + "verified": 50 + } + }, + "rounds": { + "mail": [ + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-212ce3fc14c65eccb470c7e6af0b47e1a4b09578@openadapt.tx#1", + "message/ik-238a5b980427bf3728cda70b51fceca24b9c3fba@openadapt.tx#1", + "message/ik-350180d9e182657ce5896ef7041ed36aacce52ad@openadapt.tx#1", + "message/ik-43993b3a70fd7c366215031ac982b4ae3da5cdf5@openadapt.tx#1", + "message/ik-726586335eb1c3ea149e1aa43a5d7002c68b91a2@openadapt.tx#1" + ], + "digest": "a8a147a2d32a84a2", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-0962988d960dac52cd8a756ad74159daae33c4e0@openadapt.tx#1", + "message/ik-0f04c6afd57267b35e8ccb27e50eba4a83af6906@openadapt.tx#1", + "message/ik-34f272154df36fae37664998b8808a0d637066fe@openadapt.tx#1", + "message/ik-37293458449fa277bd2632500fbbe9e5607f39d6@openadapt.tx#1", + "message/ik-6fbb3e956c3a87a4c848842291c71c9f348d7a78@openadapt.tx#1" + ], + "digest": "484338e0f734cf1c", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-311016aede42b37c82ebfb94ff3f3377c0725bb3@openadapt.tx#1", + "message/ik-32ed2fd64f22328d356a8d9e934908a9d461e01f@openadapt.tx#1", + "message/ik-42dc5cbc288dc48a2a23fb71c4e2f69e4672fc08@openadapt.tx#1", + "message/ik-4c6693c36355d63f488e4c9a051ba5ae36ea1292@openadapt.tx#1", + "message/ik-8a1b98d8ba02fd0a166bc7736a4178aa89e46e47@openadapt.tx#1" + ], + "digest": "f85f6e6e9544fa8e", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-0496d034bf8a2bedb911f4f3d653bd18d3184405@openadapt.tx#1", + "message/ik-06e0870b27ca13a0bb237b4ed140cfb98751b201@openadapt.tx#1", + "message/ik-266bd30f72fe37264b2f7626ce15fe53034feb6b@openadapt.tx#1", + "message/ik-40216d46e7119003a630245f4c210a36d3c70aca@openadapt.tx#1", + "message/ik-7841f4157913b940c98cc9275fc63ff0f4dcd375@openadapt.tx#1" + ], + "digest": "b5b481ccd7708818", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-2388b18e1e3f44793e24a6e3f8605f793dcbd095@openadapt.tx#1", + "message/ik-308a8ed475341b3b893966fe901a0b976b62eb0d@openadapt.tx#1", + "message/ik-61633babee15afe48d7a1dc68750d6d1a75ca847@openadapt.tx#1", + "message/ik-77edbf25ae65bf49b1dd3d11c68daf709db3acbe@openadapt.tx#1", + "message/ik-8d737d91e7fea494061d546d870b45a2a4b9c97b@openadapt.tx#1" + ], + "digest": "d3d36fb4f96d9222", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-14c47e5f56cc796f02c0ee235c7be281c4ab54c8@openadapt.tx#1", + "message/ik-1935b77e38c06666512fe46b6e329772573714d1@openadapt.tx#1", + "message/ik-2003812e082bb3a92065fe246e794f8af2c2de0d@openadapt.tx#1", + "message/ik-8709a6483d899e8171e67f5effbf3737f6b38357@openadapt.tx#1", + "message/ik-88a302c41e49b48e30562ac006a36beb0aa1c291@openadapt.tx#1" + ], + "digest": "256ec39f9af9d65a", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-002569508a96582d7a7193a506247cf31959d718@openadapt.tx#1", + "message/ik-14a492d674b663e0a5390717a10a7c11d21d60ca@openadapt.tx#1", + "message/ik-333deffd996f1ba39dabc9b38080b30b1b889a23@openadapt.tx#1", + "message/ik-339d3b7d52cea9c8e5ea5bfe0820916bfdaa3a60@openadapt.tx#1", + "message/ik-8f38897fa22229d303d3ab478793e7cc46fecc1a@openadapt.tx#1" + ], + "digest": "817fac506911eb39", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-0292a108fa14691f5ef26aa71719f1639c23a598@openadapt.tx#1", + "message/ik-0eb4fbe71b59474c13c6d733e3f735a17a4eafda@openadapt.tx#1", + "message/ik-238137802a35b2698b3dd1d741ff836b01610e5c@openadapt.tx#1", + "message/ik-29485f966bb7a315ba9ff0bd5ce46c55ad8c7c0c@openadapt.tx#1", + "message/ik-78a20bb57ea7a387ed412ecd5c57fcf402e40406@openadapt.tx#1" + ], + "digest": "a2ce720e5d14f09c", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-2b8f3147cca6e9b8408ce66b34883f516e5f8c66@openadapt.tx#1", + "message/ik-4c493af1fc9040e98782f63c3bb74e663fb4e668@openadapt.tx#1", + "message/ik-8b2de8aaca6de375a0b12fd43429f6d8c9897942@openadapt.tx#1", + "message/ik-9aaa6a702d8ab044d03b6d68741838524186fe66@openadapt.tx#1", + "message/ik-9c84cdd17df69f052b916160340a87a0255bb728@openadapt.tx#1" + ], + "digest": "cb84b19c279f8697", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 0, + "false_diffs": 0, + "held": 10, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 0, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "COMPLETED_UNVERIFIED", + "collateral": [ + "message/ik-3b292b9848c145f66886d248c866ea0e7353ce59@openadapt.tx#1", + "message/ik-58b71d8db2542a4532fb6c1805e6af0aad44f55d@openadapt.tx#1", + "message/ik-720a018417c52a5bc1c9791fea462666fd5da79e@openadapt.tx#1", + "message/ik-848334ea52cdded908ab966e3fe825ca9195061b@openadapt.tx#1", + "message/ik-8bd40722b991cb3c44f43280a3bf963a28c4d5c4@openadapt.tx#1" + ], + "digest": "8626414711df8865", + "dry_run": { + "outbox": "holdback" + }, + "false": [], + "mailbox": { + "cancelled_never_sent": 5, + "cancelled_sent": 0, + "released_exactly_once": 5, + "released_other": 0 + }, + "missed": [], + "release": { + "adopted": 0, + "double": 0, + "phase": "release", + "released": 5, + "waiting": 0 + }, + "undo": { + "cancelled": 5, + "codes": { + "cancelled": 5, + "irreversible_released": 5 + }, + "collateral_changes": 5, + "irreversible_released": 5, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 0, + "undo_verified": 0, + "writes": 10 + }, + "undo_outcome": "RECONCILIATION_REQUIRED" + } + ], + "rest": [ + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "353865e289ff6af9", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "204bdc5fcffe4130", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "737af10f84d89c75", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "6e4de5398803083e", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "997b6482f6073145", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "f82a6487df64cd5a", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "a0252b4e9b43a7f7", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "2fea2844d8394609", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "6d1bdc119d8762cb", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 0, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "ab903c539a5a0646", + "dry_run": { + "vikunja": "computed" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + } + ], + "sql": [ + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "4d3dc38f9888cec4", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "4eafddd9308d735c", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "eb89f0d6de67712a", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "3e7b0221cf51611b", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "3827a3c86405f394", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "400de555e6b9a36c", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "bdb565e1a7e59c7f", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "13e26bef1d32c6f3", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "a37bdb402a01c2e8", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + }, + { + "anomalies": 2, + "apply": { + "confirmed": 10, + "false_diffs": 0, + "missed_effects": 0, + "phase": "apply", + "refuted": 0, + "sent": 10, + "stopped": null, + "writes": 10 + }, + "apply_outcome": "VERIFIED", + "collateral": [], + "digest": "132ea6ac98115196", + "dry_run": { + "dolibarr": "staged_transaction" + }, + "false": [], + "mailbox": null, + "missed": [], + "release": null, + "undo": { + "cancelled": 0, + "codes": { + "undone": 10 + }, + "collateral_changes": 0, + "irreversible_released": 0, + "no_generated_undo": 0, + "phase": "undo", + "undo_supported": 10, + "undo_verified": 10, + "writes": 10 + }, + "undo_outcome": "ROLLED_BACK" + } + ] + }, + "schema": "openadapt.ext-tx-lab/v1", + "seeded_faults": { + "rest": { + "collateral_caught": 5, + "missed_effect_caught": 5, + "not_caught": [], + "trials": 5 + }, + "sql": { + "collateral_caught": 5, + "missed_effect_caught": 5, + "not_caught": [], + "trials": 5 + } + }, + "spec_sha256": "8eeaa89d5cf2f8e6ebf87e692fa966edd628668f9d2a4204328fd603d5ea4088", + "started_at": "2026-11-21T07:33:23Z", + "summary": { + "blocked_double_effects": 60, + "control_duplicates": 60, + "double_effects_through": 0, + "kill_criteria_tripped": [], + "mail": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 50, + "cancelled_never_sent": 50, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 50, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 50, + "released_other": 0, + "rounds": 10, + "undo_success_rate": null, + "undo_supported": 0, + "undo_verified": 0, + "writes": 100 + }, + "rest": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + }, + "sql": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + } + } +} diff --git a/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.log b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.log new file mode 100644 index 0000000000..dad10a8974 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-apps.log @@ -0,0 +1,93 @@ +[23:33:23] vikunja: 40 tasks; project 2 +[23:33:23] dolibarr: seeded 60 thirdparties +[23:33:24] rest 0: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:25] rest 1: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:26] rest 2: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:27] rest 3: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:28] rest 4: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:29] rest 5: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:29] rest 6: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:30] rest 7: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:31] rest 8: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:32] rest 9: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:41] sql 0: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:50] sql 1: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:33:59] sql 2: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:34:09] sql 3: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:34:21] sql 4: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:34:29] sql 5: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:34:37] sql 6: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:34:46] sql 7: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:34:55] sql 8: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:35:05] sql 9: apply VERIFIED missed [] false [] undo ROLLED_BACK {'undone': 10} [] +[23:35:07] mail 0: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:07] mail 1: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:10] mail 2: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:12] mail 3: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:14] mail 4: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:16] mail 5: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:19] mail 6: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:21] mail 7: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:24] mail 8: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:35:26] mail 9: apply COMPLETED_UNVERIFIED release {'phase': 'release', 'released': 5, 'waiting': 0, 'adopted': 0, 'double': 0} undo {'cancelled': 5, 'irreversible_released': 5} +[23:42:04] acrfence {'rest': {'trials': 20, 'control_duplicates': 20, 'blocked': 20, 'identical_replays_not_sent': 20, 'double_effects_through': 0}, 'sql': {'trials': 20, 'control_duplicates': 20, 'blocked': 20, 'identical_replays_not_sent': 20, 'double_effects_through': 0}, 'mail': {'trials': 20, 'control_duplicates': 20, 'blocked': 20, 'identical_replays_not_sent': 20, 'double_effects_through': 0}} +[23:43:09] crash {'rest': {'trials': 5, 'crashed_after_send': 5, 'double_effects_through': 0}, 'sql': {'trials': 5, 'crashed_after_send': 5, 'double_effects_through': 0}} +[23:44:21] faults {'rest': {'trials': 5, 'missed_effect_caught': 5, 'collateral_caught': 5, 'not_caught': []}, 'sql': {'trials': 5, 'missed_effect_caught': 5, 'collateral_caught': 5, 'not_caught': []}} +[23:44:21] dolibarr cleanup: removed 125 lab rows +[23:44:22] { + "blocked_double_effects": 60, + "control_duplicates": 60, + "double_effects_through": 0, + "kill_criteria_tripped": [], + "mail": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 50, + "cancelled_never_sent": 50, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 50, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 50, + "released_other": 0, + "rounds": 10, + "undo_success_rate": null, + "undo_supported": 0, + "undo_verified": 0, + "writes": 100 + }, + "rest": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + }, + "sql": { + "apply_verified_rounds": 10, + "cancelled_in_holdback": 0, + "cancelled_never_sent": 0, + "cancelled_sent": 0, + "false_diffs": 0, + "irreversible_released": 0, + "missed_effects": 0, + "release_double_sends": 0, + "released_exactly_once": 0, + "released_other": 0, + "rounds": 10, + "undo_success_rate": 1.0, + "undo_supported": 100, + "undo_verified": 100, + "writes": 100 + } +} diff --git a/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.json b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.json new file mode 100644 index 0000000000..ea99034aa9 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.json @@ -0,0 +1,2138 @@ +{ + "app": "PostgreSQL 16 (synthetic schema)", + "rows": [ + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 1.41, + "rows_touched": 17, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 1.055, + "rows_touched": 20, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.975, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 1.04, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.025, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.886, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.957, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.894, + "rows_touched": 8, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.914, + "rows_touched": 16, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.849, + "rows_touched": 18, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.956, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.787, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.936, + "rows_touched": 9, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.885, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.821, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.796, + "rows_touched": 10, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.853, + "rows_touched": 15, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.807, + "rows_touched": 28, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.806, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.766, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.751, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.965, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.809, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.868, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.821, + "rows_touched": 61, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.808, + "rows_touched": 40, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.897, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.884, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.804, + "rows_touched": 10, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.881, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.868, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.84, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.834, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.765, + "rows_touched": 27, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.988, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.776, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.929, + "rows_touched": 10, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.828, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.809, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.899, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.975, + "rows_touched": 57, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.77, + "rows_touched": 18, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.848, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.92, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.024, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.871, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.91, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.946, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.994, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 1.109, + "rows_touched": 20, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.768, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.867, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.762, + "rows_touched": 4, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.749, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.752, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.939, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.922, + "rows_touched": 39, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.811, + "rows_touched": 15, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.806, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.835, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 0, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.744, + "rows_touched": 0, + "tables": [], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.981, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.841, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.937, + "rows_touched": 8, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.829, + "rows_touched": 53, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.729, + "rows_touched": 75, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.878, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.985, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.427, + "rows_touched": 18, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 1.047, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.846, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.896, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 1.226, + "rows_touched": 49, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.829, + "rows_touched": 60, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.805, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.961, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 1.103, + "rows_touched": 6, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.865, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.852, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.925, + "rows_touched": 9, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.964, + "rows_touched": 45, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.874, + "rows_touched": 30, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.757, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.901, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 0, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.823, + "rows_touched": 0, + "tables": [], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.848, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 1.075, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.976, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.948, + "rows_touched": 25, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.91, + "rows_touched": 25, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.759, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.825, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.875, + "rows_touched": 18, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.849, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.917, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.919, + "rows_touched": 8, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.866, + "rows_touched": 40, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.743, + "rows_touched": 15, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.89, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.859, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.878, + "rows_touched": 11, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.741, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.709, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.799, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 2, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 1.048, + "rows_touched": 57, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.844, + "rows_touched": 24, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.909, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.847, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.735, + "rows_touched": 7, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.694, + "rows_touched": 3, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.722, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.883, + "rows_touched": 6, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "bulk_update", + "missed": 0, + "preview_s": 0.834, + "rows_touched": 14, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "expr_update", + "missed": 0, + "preview_s": 0.86, + "rows_touched": 27, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_values", + "missed": 0, + "preview_s": 0.852, + "rows_touched": 2, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "insert_select", + "missed": 0, + "preview_s": 0.821, + "rows_touched": 5, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_where", + "missed": 0, + "preview_s": 0.668, + "rows_touched": 12, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "delete_cascade", + "missed": 0, + "preview_s": 0.579, + "rows_touched": 4, + "tables": [ + "orders", + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "update_join", + "missed": 0, + "preview_s": 0.716, + "rows_touched": 8, + "tables": [ + "orders" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + }, + { + "anomalies": 1, + "apply": "VERIFIED", + "db_back_to_start": true, + "false": 0, + "independent_agrees": true, + "kind": "migration_like", + "missed": 0, + "preview_s": 0.644, + "rows_touched": 7, + "tables": [ + "users" + ], + "undo": "ROLLED_BACK", + "undo_supported": 1, + "undo_verified": 1 + } + ], + "schema": "openadapt.ext-tx-proxy-lab/v1", + "started": "2026-11-21T08:25:15Z", + "summary": { + "acrfence": { + "control_duplicates": 20, + "double_effects_through": 0, + "held_not_applied": 20, + "trials": 20 + }, + "apply_verified": 120, + "by_kind": { + "bulk_update": 15, + "delete_cascade": 15, + "delete_where": 15, + "expr_update": 15, + "insert_select": 15, + "insert_values": 15, + "migration_like": 15, + "update_join": 15 + }, + "code_sha": "c88d728c77fa822ec1b3ffb9638b52047970cdd5", + "db_back_to_start": 120, + "false_diffs": 0, + "independent_disagreements": 0, + "mcp_sdk_session": { + "apply": "VERIFIED", + "tools": [ + "sql_query", + "sql_preview", + "sql_apply", + "sql_undo" + ], + "undo": "ROLLED_BACK" + }, + "missed_effects": 0, + "preview_s_median": 0.865, + "receipts": { + "tx-apply": { + "approval_bound_to_plan_digest": 142, + "approver_agent": 3, + "approver_none": 20, + "approver_person": 139, + "runs": 162, + "verified": 162 + }, + "tx-plan": { + "approver_none": 162, + "runs": 162, + "verified": 162 + }, + "tx-undo": { + "approval_bound_to_plan_digest": 122, + "approver_agent": 3, + "approver_person": 119, + "runs": 122, + "verified": 122 + } + }, + "rows_touched": 1490, + "statements": 120, + "trigger_probe": { + "apply": "VERIFIED", + "collateral": 5, + "missed": 0, + "predicted_tables": { + "audit": { + "added": 5, + "changed": 0, + "removed": 0 + }, + "users": { + "added": 0, + "changed": 5, + "removed": 0 + } + }, + "undo": "RECONCILIATION_REQUIRED" + }, + "undo_success_rate": 1.0, + "undo_supported": 120, + "undo_verified": 120 + } +} diff --git a/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.log b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.log new file mode 100644 index 0000000000..e65c24cdd5 --- /dev/null +++ b/packages/flow/benchmark/ext_tx/results/run2-2026-11-21-proxy.log @@ -0,0 +1,85 @@ +NOTICE: database "oa_ext_tx" does not exist, skipping +[00:24:29] 120 statements done +[00:25:10] acrfence {'trials': 20, 'held_not_applied': 20, 'double_effects_through': 0, 'control_duplicates': 20} +[00:25:12] trigger {'predicted_tables': {'audit': {'added': 5, 'changed': 0, 'removed': 0}, 'users': {'added': 0, 'changed': 5, 'removed': 0}}, 'apply': 'VERIFIED', 'missed': 0, 'undo': 'RECONCILIATION_REQUIRED', 'collateral': 5} +[00:25:15] mcp {'tools': ['sql_query', 'sql_preview', 'sql_apply', 'sql_undo'], 'apply': 'VERIFIED', 'undo': 'ROLLED_BACK'} +[00:25:15] { + "acrfence": { + "control_duplicates": 20, + "double_effects_through": 0, + "held_not_applied": 20, + "trials": 20 + }, + "apply_verified": 120, + "by_kind": { + "bulk_update": 15, + "delete_cascade": 15, + "delete_where": 15, + "expr_update": 15, + "insert_select": 15, + "insert_values": 15, + "migration_like": 15, + "update_join": 15 + }, + "code_sha": "c88d728c77fa822ec1b3ffb9638b52047970cdd5", + "db_back_to_start": 120, + "false_diffs": 0, + "independent_disagreements": 0, + "mcp_sdk_session": { + "apply": "VERIFIED", + "tools": [ + "sql_query", + "sql_preview", + "sql_apply", + "sql_undo" + ], + "undo": "ROLLED_BACK" + }, + "missed_effects": 0, + "preview_s_median": 0.865, + "receipts": { + "tx-apply": { + "approval_bound_to_plan_digest": 142, + "approver_agent": 3, + "approver_none": 20, + "approver_person": 139, + "runs": 162, + "verified": 162 + }, + "tx-plan": { + "approver_none": 162, + "runs": 162, + "verified": 162 + }, + "tx-undo": { + "approval_bound_to_plan_digest": 122, + "approver_agent": 3, + "approver_person": 119, + "runs": 122, + "verified": 122 + } + }, + "rows_touched": 1490, + "statements": 120, + "trigger_probe": { + "apply": "VERIFIED", + "collateral": 5, + "missed": 0, + "predicted_tables": { + "audit": { + "added": 5, + "changed": 0, + "removed": 0 + }, + "users": { + "added": 0, + "changed": 5, + "removed": 0 + } + }, + "undo": "RECONCILIATION_REQUIRED" + }, + "undo_success_rate": 1.0, + "undo_supported": 120, + "undo_verified": 120 +} diff --git a/packages/flow/docs/TRANSACTIONS.md b/packages/flow/docs/TRANSACTIONS.md index b4a81ae3b8..72f906f428 100644 --- a/packages/flow/docs/TRANSACTIONS.md +++ b/packages/flow/docs/TRANSACTIONS.md @@ -207,11 +207,18 @@ its own credentials to the system. All runs took place on 21 November 2026, on the lab laptop's WSL with synthetic data. The rules (server-set and derived fields, ignored tables) were -fixed after a pilot and before the measured run. The pilot found one engine -bug: an undo of an SQL update didn't restore a column the database sets -itself (`ON UPDATE CURRENT_TIMESTAMP`). It was fixed by restoring the whole -before-image. Results, counts and record ids only, are in -[`benchmark/ext_tx/results/`](../benchmark/ext_tx/results/). +fixed after a pilot. The pilot found one engine bug: an undo of an SQL update +didn't restore a column the database sets itself +(`ON UPDATE CURRENT_TIMESTAMP`). It was fixed by restoring the whole +before-image. + +There were two measured runs. Run 1's receipts weren't signed, because the lab +environment's `openadapt-types` predates `record/run/v1`. Run 2 used the +repository's own types and signed every phase. Its numbers are below. Run 1's +numbers were the same. The results (counts and record ids only) are in +[`benchmark/ext_tx/results/`](../benchmark/ext_tx/results/). The apps run used +code at `2668a20f`, and the proxy and setup runs used `c88d728c`, which also +compares values at apply. | Surface | Writes | Missed effects | False diffs | Verified undo | Double effects through | |---|---|---|---|---|---| @@ -221,36 +228,46 @@ before-image. Results, counts and record ids only, are in | Mailpit v1.27.10 (email, holdback) | 100 sends | 0 | 0 | 50 cancelled in holdback and never sent; 50 released exactly once. A released email has no undo. | 0 of 20 (20 refused); the control arm doubled 20 of 20 | - **Crash after the send, before the outcome was recorded** (5 per app, REST - and SQL): the regenerated retry was refused, and the identical retry was - read back and held. The run had no second effect in any of the 10 cases. + and SQL): there was no second effect in 10 of 10 cases. - **Identical replays** sent nothing in 60 of 60 cases. - **The independent read-back** (the verifier's `capture_database` and `diff_database`) agreed with the proxy's dry run on every table's counts for - all 120 statements. + 120 of 120 statements. - **Seeded faults, to show the checks can fail:** - - A change the plan didn't predict, injected during apply, was counted as a - missed effect in 10 of 10 cases. - - A change injected before undo was caught in 10 of 10 cases: as collateral - in 9, and in 1 as `changed_since_apply`, because the injected change hit - the planned record. The undo refused to overwrite it. + - A change injected during apply was counted as a missed effect in 10 of 10 + cases. + - A change injected before undo was caught in 10 of 10 cases. In run 1, one + of these hit the planned record, and the undo refused to overwrite it + (`changed_since_apply`). - **A trigger probe** (PostgreSQL, outside the measured set): the dry run - showed the trigger's 5 audit rows, and apply found no missed effect. The undo - fires the trigger again, so it reported `RECONCILIATION_REQUIRED` with 5 - collateral rows, never `ROLLED_BACK`. + showed the trigger's 5 audit rows. The undo fires the trigger again, so it + reported `RECONCILIATION_REQUIRED` with 5 collateral rows. +- **Receipts:** + - In the apps run, 660 of 660 phase receipts were signed and verified. Every + apply, undo and release receipt binds its approval to the plan digest. + - In the proxy run, 446 of 446 were signed and verified. There, a script + pressed `y`, so 139 apply receipts say `person`, although no person + approved them. - **One session over the real MCP client SDK** (`mcp` 1.x, streamable HTTP) - listed the four tools, applied and undid a statement. -- **Setup time.** From an empty virtual environment to the first diff took 8 - to 10 seconds over three runs: install `openadapt-flow`, `openadapt-types` - and `psycopg` with no package cache, then `openadapt-flow proxy --postgres - ... -- ` and its first `sql_preview`. The target was under - 2 minutes. Not included: installing Python and uv, and building the wheels - from source, which stood in for PyPI. The machine was the lab laptop, not - a fresh one. -- **Median dry-run time:** 0.78 s for the 600-user, 1,500-order database. - -The kill criteria were: a verified undo failing on more than 5% of supported -writes, a dry-run diff missing an effect that the read-back found, or a double -effect getting through. None was tripped. + listed the four tools, applied a statement and undid it. +- **A live Claude Code session** went through the proxy (Claude Code 2.1.305, + headless, `--allowedTools` limited to the proxy's tools). The bulk update was + held: 60 rows, 2 of them admins. Claude Code reported the refusal and didn't + work around it. After the approval, a second session applied it and undid + it. See [`results/2026-11-21-live-claude-code.md`](../benchmark/ext_tx/results/2026-11-21-live-claude-code.md). +- **Setup time:** 11.5 to 12.4 s over three runs (run 1: 8.2 to 9.8 s). That is + from an empty virtual environment to the first diff on a local PostgreSQL: + installing `openadapt-flow`, `openadapt-types` and `psycopg` with no package + cache, then `openadapt-flow proxy --postgres ... -- ` and its + first `sql_preview`. The target was under 2 minutes. Not included: + installing Python and uv, and building the wheels from source, which stood + in for PyPI. The machine was the lab laptop, not a fresh one. +- **Median dry-run time:** 0.87 s for 600 users and 1,500 orders. A statement + is staged three times. + +The kill criteria were a verified undo failing on more than 5% of supported +writes, a dry-run diff missing an effect that the read-back found, a double +effect getting through, and setup over 2 minutes. None was tripped. ## References From a23dfedadc615f1ab6484cf7618c8f2affe52b06 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:28:15 -0500 Subject: [PATCH 13/21] docs(plan): drop a link to a page that isn't on this base --- packages/flow/docs/TRANSACTIONS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flow/docs/TRANSACTIONS.md b/packages/flow/docs/TRANSACTIONS.md index 72f906f428..85339c50f1 100644 --- a/packages/flow/docs/TRANSACTIONS.md +++ b/packages/flow/docs/TRANSACTIONS.md @@ -199,7 +199,7 @@ count, never `ROLLED_BACK`. Counters aren't rows and aren't compared. coding agent that also has direct access, declare the same system in `openadapt.systems.yaml` with `approval: block` ([HOOKS.md](HOOKS.md)), so a direct write is refused and batch writes go through a plan. `openadapt wrap` -([WRAP.md](WRAP.md)) is a browser MCP harness, not a broker for these +(#2407) is a browser MCP harness, not a broker for these systems. Like the hooks, this layer is advisory against an agent that holds its own credentials to the system. From fda539c788c408b435f275984bddb81e2aad4a68 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:23:31 -0500 Subject: [PATCH 14/21] fix(plan): SQL apply needs the planned values; undo of an un-undoable write is not rolled back _apply_sql refuses a plan whose statement has no staged_after, so a missing key can't fall back to a shape-only commit. undo_plan reports RECONCILIATION_REQUIRED when any applied write has no undo (DDL, or no undo images). ruff format for openadapt/cli.py. --- openadapt/cli.py | 10 +++++-- .../flow/openadapt_flow/txplan/adapters.py | 8 +++-- packages/flow/openadapt_flow/txplan/engine.py | 5 +++- packages/flow/tests/test_txplan.py | 30 +++++++++++++++++++ 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/openadapt/cli.py b/openadapt/cli.py index 1f255b1d2f..331829e78e 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1919,7 +1919,9 @@ def plan(command_ctx: click.Context) -> None: def proxy(command_ctx: click.Context) -> None: """Hold the database credentials; give the agent tools that preview, apply once and undo.""" _require_supported_python() - proxy_main = _optional_engine_entrypoint(command_ctx, ("openadapt_flow.txplan.proxy_cli",)) + proxy_main = _optional_engine_entrypoint( + command_ctx, ("openadapt_flow.txplan.proxy_cli",) + ) if proxy_main is None: click.echo( "Error: this openadapt-flow installation has no proxy command.", err=True @@ -1929,7 +1931,7 @@ def proxy(command_ctx: click.Context) -> None: # Click drops a bare "--"; restore it from argv so the agent's arguments stay its own. if "--" in sys.argv and "--" not in args: tail = sys.argv[sys.argv.index("--") + 1 :] - if tail and args[-len(tail):] == tail: + if tail and args[-len(tail) :] == tail: args = args[: -len(tail)] + ["--"] + tail sys.exit(int(proxy_main(args) or 0)) @@ -2016,7 +2018,9 @@ def agent(argv: list[str]) -> int: command_ctx, ("openadapt_agent.seal_cli", "openadapt_agent.cli") ) if agent_main is None: - click.echo("Not verified: this openadapt-agent can't check that format.") + click.echo( + "Not verified: this openadapt-agent can't check that format." + ) return 1 return int(agent_main(argv) or 0) diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index 1a1875fe3f..36971e521f 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -789,6 +789,10 @@ def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: want = write.get("staged_diff") if not isinstance(want, Mapping): raise AdapterError("the plan has no staged diff for this statement") + # The planned values, not only the shape: without them a statement + # could commit different values into the planned rows. + if not isinstance(write.get("staged_after"), Mapping): + raise AdapterError("the plan has no staged values for this statement") con = self.connect() try: cur = con.cursor() @@ -803,9 +807,7 @@ def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: got_after = after_image( after_raw(diff, after, after_rows), write.get("volatile") or [] ) - if _shape(diff) != _shape(want) or ( - "staged_after" in write and got_after != write["staged_after"] - ): + if _shape(diff) != _shape(want) or got_after != write["staged_after"]: con.rollback() raise Diverged( "the statement's rows or values are not the planned ones; rolled back" diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 55a6113bec..5b95cf06be 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -1328,7 +1328,10 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: }, } ) - ok = len(verified) == len(counted) and not collateral + # An applied write with no undo (DDL, or no undo images) is still in + # place: the plan is not rolled back, whatever the rows show. + not_undone = [k for k, v in per_write.items() if v == "no_undo"] + ok = len(verified) == len(counted) and not collateral and not not_undone outcome = "ROLLED_BACK" if ok else "RECONCILIATION_REQUIRED" approval = state.approval_record(digest) run = _write_run( diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index bf00f8bc36..3667c807a1 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -783,6 +783,36 @@ def test_proxy_insert_and_delete_round_trip_and_policy_auto_approve( assert _all(db) == before +def test_sql_apply_refuses_a_plan_without_its_planned_values(tmp_path: Path) -> None: + from openadapt_flow.txplan.state import read_json, write_private + + db = _users(tmp_path / "app.sqlite", n=20) + before = _all(db) + proxy = _proxy(db, max_rows=100) + got = proxy.preview("UPDATE users SET role = 'viewer' WHERE id = 4") + state = proxy.ctx.state + private = state.plan_dir(state.find_plan(got["plan"])) / "private.json" + data = read_json(private) + for w in data["writes"]: + w.pop("staged_after", None) + write_private(private, data) + proxy.key("y") + out = proxy.apply(got["plan"]) + assert out["outcome"] != "VERIFIED" and out["tx"]["sent"] == 0, out + assert _all(db) == before + + +def test_undo_of_a_write_it_cannot_undo_is_not_rolled_back(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=5) + proxy = _proxy(db, max_rows=100) + got = proxy.preview("CREATE TABLE extra (id INTEGER PRIMARY KEY)") + proxy.key("y") + assert proxy.apply(got["plan"])["outcome"] == "VERIFIED" + undone = proxy.undo(got["plan"]) + assert undone["outcome"] == "RECONCILIATION_REQUIRED", undone + assert undone["tx"]["no_generated_undo"] == 1 + + def test_proxy_commits_only_the_planned_diff(tmp_path: Path) -> None: db = _users(tmp_path / "app.sqlite", n=20) proxy = _proxy(db, max_rows=100) From 5e8f0c8f4dc969dd5d2ec6d125dcf81717c17447 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:23:48 -0500 Subject: [PATCH 15/21] style: ruff format openadapt/quickstart/__init__.py (launcher CI) --- openadapt/quickstart/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/openadapt/quickstart/__init__.py b/openadapt/quickstart/__init__.py index 06c274a8d3..a287fc77f8 100644 --- a/openadapt/quickstart/__init__.py +++ b/openadapt/quickstart/__init__.py @@ -57,9 +57,7 @@ def build(outcome: Outcome) -> NextSteps: ) return NextSteps( verify=verify, - verify_run=lambda run_dir: hint( - f"verify {quote(display_path(run_dir))}" - ), + verify_run=lambda run_dir: hint(f"verify {quote(display_path(run_dir))}"), record=hint( f"flow record --backend web --url {YOUR_APP_URL} --out my-task" ), From e1949ce9130aa6649a3f8b7eecb94d86d647115b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:48:46 -0500 Subject: [PATCH 16/21] fix(plan): close the round-3 fail-opens in plan, apply, undo and release Instance fixes, named by class until the shared fail-open harness lands: - unstaged commit: transaction-control statements are never writes. - unbound evidence: the approved digest covers private.json. - unobserved scope: SQL writes outside the current schema (PostgreSQL) or database (MySQL) are refused. - unverified success: committed SQL is read again before it is confirmed; a replay is VERIFIED only by a fresh read-back; a refuted undo stays uncertain and keeps its key. - wrong target: undo and release check the tx file like apply. - stale baseline: the undo check and restore share one transaction; a held write is rechecked before release. - double send: a release that began before is never resent. - not rolled back: a released irreversible write blocks ROLLED_BACK. - wrong subject: y/n with several plans waiting approves none. - path injection: REST path values are one quoted segment. - missing evidence: a malformed or repeated list page is an error. - unenforced constraint: SQLite foreign keys on. --- .../flow/openadapt_flow/txplan/adapters.py | 95 +++++++++++- packages/flow/openadapt_flow/txplan/engine.py | 142 +++++++++++++++--- packages/flow/openadapt_flow/txplan/proxy.py | 9 +- packages/flow/tests/test_txplan.py | 54 ++++++- 4 files changed, 270 insertions(+), 30 deletions(-) diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index 36971e521f..73b5a367d5 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -31,6 +31,7 @@ import re import time from typing import Any, Callable, Mapping, Optional, Sequence +from urllib.parse import quote from openadapt_flow.txplan.spec import ( Collection, @@ -48,6 +49,10 @@ class AdapterError(RuntimeError): """A read or a write failed. For a write, delivery is unknown.""" +class ChangedSinceApply(AdapterError): + """Undo found a row no longer as the apply left it.""" + + class Diverged(AdapterError): """The statement did something other than the plan showed. Nothing landed.""" @@ -278,7 +283,12 @@ def one(m: re.Match[str]) -> str: name = m.group(1) if name not in values or values[name] in (None, ""): raise AdapterError(f"the path needs {name}") - return str(values[name]) + # Path-injection class: a value is one path segment, never a + # separator, dot segment or query. + text = str(values[name]) + if text in (".", ".."): + raise AdapterError(f"{name} can't be a dot segment") + return quote(text, safe="") return re.sub(r"\{([a-z_][a-z0-9_]*)\}", one, path) @@ -338,8 +348,13 @@ def frame(self, collection: Optional[str]) -> dict[str, dict[str, str]]: if route.per_page_param: params[route.per_page_param] = route.per_page got = self._call(route.method, route.path, params=params) - items = got if isinstance(got, list) else (got or {}).get("items", []) - if not isinstance(items, list): + # Missing-evidence class: a missing or malformed list is an error, + # never an empty collection. + if isinstance(got, list): + items = got + elif isinstance(got, Mapping) and isinstance(got.get("items"), list): + items = got["items"] + else: raise AdapterError("a list did not return a list") fresh = 0 for item in items: @@ -347,7 +362,11 @@ def frame(self, collection: Optional[str]) -> dict[str, dict[str, str]]: if rid not in out: fresh += 1 out[rid] = column_digests(self.normalize(coll, item)) - if not route.page_param or len(items) < route.per_page or not fresh: + if items and not fresh: + # A page that repeats rows already read means the pager isn't + # advancing: the scan can't prove it saw the whole collection. + raise AdapterError("the list repeated a page") + if not route.page_param or len(items) < route.per_page: return out page += 1 if page > 10_000: @@ -502,6 +521,9 @@ def connect(self, *, read_only: bool = False) -> Any: uri = path.resolve().as_uri() + "?mode=ro" return sqlite3.connect(uri, uri=True, isolation_level=None) con = sqlite3.connect(str(path), isolation_level=None) + # Unenforced-constraint class: a parent delete must not leave + # orphans that the frame read still calls clean. + con.execute("PRAGMA foreign_keys = ON") return con module = importlib.import_module(str(s.driver)) args = dict(s.connect_args) @@ -543,6 +565,33 @@ def _ident(self, name: str) -> str: # reading ---------------------------------------------------------------- + def _refuse_unobserved_writes(self, cur: Any, sql: str) -> None: + """Unobserved-scope class: the frame reads one schema (or database), so + a statement may not change rows anywhere else.""" + d = self.system.dialect + if d == "postgresql": + # This transaction's own row counts, for every table it touched. + cur.execute( + "SELECT count(*) FROM pg_stat_xact_user_tables " + "WHERE schemaname <> current_schema() " + "AND n_tup_ins + n_tup_upd + n_tup_del > 0" + ) + if int(cur.fetchone()[0]): + raise Diverged("the statement changed rows outside the current schema") + elif d == "mysql": + cur.execute("SELECT DATABASE()") + current = str(cur.fetchone()[0] or "") + cur.execute("SHOW DATABASES") + others = {str(r[0]).lower() for r in cur.fetchall()} - {current.lower()} + named = { + m.lower() + for m in re.findall( + r"`?([A-Za-z0-9_$]+)`?\s*\.\s*`?[A-Za-z0-9_$]+", sql + ) + } + if named & others: + raise Diverged("the statement names another database") + def _tables(self, cur: Any) -> list[str]: d = self.system.dialect if d == "sqlite": @@ -681,7 +730,9 @@ def _exec( op = write["op"] if op == "sql": cur.execute(str((write.get("fields") or {})["sql"])) - return {"rows": max(0, int(cur.rowcount or 0))} + rows = max(0, int(cur.rowcount or 0)) + self._refuse_unobserved_writes(cur, str(write["fields"]["sql"])) + return {"rows": rows} fields = {k: untag(v) for k, v in (write.get("fields") or {}).items()} assert key is not None t = self._ident(table) @@ -825,9 +876,30 @@ def _apply_sql(self, write: Mapping[str, Any]) -> dict[str, Any]: con.rollback() raise con.commit() - return {**result, "_images": images} finally: con.close() + # Unverified-success class: what committed is read again, outside the + # transaction, so a deferred trigger that stored other values in the + # planned rows is a refuted write, not a confirmed one. + post_rows: dict[str, Any] = {} + con = self.connect() + try: + cur = con.cursor() + self._begin(cur) + try: + post = self.frame_cur(cur, post_rows) + finally: + con.rollback() + finally: + con.close() + post_diff = diff_frames(before, post) + post_after = after_image( + after_raw(post_diff, post, post_rows), write.get("volatile") or [] + ) + matches = ( + _shape(post_diff) == _shape(want) and post_after == write["staged_after"] + ) + return {**result, "post_commit_matches": matches, "_images": images} def compensate_sql(self, images: Mapping[str, Any]) -> None: """Undo one statement from its images, in one transaction: delete what @@ -844,6 +916,17 @@ def compensate_sql(self, images: Mapping[str, Any]) -> None: cur = con.cursor() self._begin(cur) try: + # Stale-baseline class: the check and the restore share one + # transaction, so an edit landing between them can't be + # overwritten. + now_rows = self.frame_cur(cur) + after = images.get("after", {}) + for rid, want in after.items(): + if now_rows.get(rid) != want: + raise ChangedSinceApply(rid) + for rid in images.get("before", {}): + if rid not in after and now_rows.get(rid) is not None: + raise ChangedSinceApply(rid) left = steps n = 0 while left: diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 5b95cf06be..0f593d0be5 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -26,6 +26,7 @@ from openadapt_flow.txplan.adapters import ( AdapterError, + ChangedSinceApply, Diverged, MailAdapter, SqlAdapter, @@ -64,6 +65,12 @@ _READ = re.compile(r"^\s*(select|with|show|explain|pragma|values)\b", re.I) #: Test hook: exit right after the Nth send, before its outcome is recorded. CRASH_ENV = "OPENADAPT_TX_CRASH_AFTER_SEND" +_TX_CONTROL = re.compile( + r"^\s*(BEGIN|COMMIT|END|ROLLBACK|ABORT|SAVEPOINT|RELEASE|START\s+TRANSACTION|" + r"SET\s+(SESSION\s+)?TRANSACTION|PREPARE\s+TRANSACTION|ATTACH|DETACH|PRAGMA|" + r"VACUUM|LOCK|UNLOCK|XA)\b", + re.IGNORECASE, +) class TxRefused(RuntimeError): @@ -412,6 +419,8 @@ def _undo_sql( state.record(w["key"], "undo_begun", plan=digest, payload=entry.payload) try: adapter.compensate_sql(images) + except ChangedSinceApply: + return "changed_since_apply" except AdapterError as exc: state.record( w["key"], @@ -459,6 +468,12 @@ def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: raise TxRefused( "bad_write", f"write {n}: a read is not a write (use a query)" ) + if _TX_CONTROL.match(sql): + # Unstaged-commit class: a transaction-control statement would end + # the staging transaction and commit earlier writes before approval. + raise TxRefused( + "bad_write", f"write {n}: transaction control is not a write" + ) ddl = bool(_DDL.match(sql)) if ddl and system.dialect == "mysql": raise TxRefused( @@ -804,18 +819,19 @@ def make_plan(ctx: Ctx, task: str, raw: Sequence[Mapping[str, Any]]) -> dict[str "summary": summary, "anomalies": [{k: a[k] for k in ("label", "write")} for a in anomalies], } + private = { + "writes": writes, + "baselines": baselines, + "frames": frames, + "anomalies": anomalies, + } + # Unbound-evidence class: the approved digest covers the private plan + # too, so editing private.json can't change what an approval authorizes. + core["private_sha256"] = sha256(private) digest = sha256(core) pdir = state.plan_dir(digest) write_private(pdir / "plan.json", {**core, "digest": digest}) - write_private( - pdir / "private.json", - { - "writes": writes, - "baselines": baselines, - "frames": frames, - "anomalies": anomalies, - }, - ) + write_private(pdir / "private.json", private) tx = { "phase": "plan", "writes": len(writes), @@ -850,7 +866,15 @@ def load_plan(state: State, digest: str) -> tuple[dict[str, Any], dict[str, Any] pdir = state.plan_dir(digest) if not (pdir / "plan.json").exists(): raise TxRefused("plan_not_found", digest[:12]) - return read_json(pdir / "plan.json"), read_json(pdir / "private.json") + plan, private = read_json(pdir / "plan.json"), read_json(pdir / "private.json") + core = {k: v for k, v in plan.items() if k != "digest"} + if ( + plan.get("digest") != digest + or sha256(core) != digest + or plan.get("private_sha256") != sha256(private) + ): + raise TxRefused("plan_tampered", "the stored plan doesn't match its digest") + return plan, private def approve_plan( @@ -870,7 +894,9 @@ def _readback( if isinstance(adapter, MailAdapter): return None, None if w["op"] == "sql": - return True, None # committed only when its own diff matched the plan + # Committed only when its own diff matched the plan, and confirmed + # only when the committed rows, read again, still match it. + return result.get("post_commit_matches") is True, None rid = str(result.get("id") or w.get("id")) got = adapter.read(w["collection"], rid) if w["op"] == "delete": @@ -968,10 +994,22 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: if entry is not None and entry.status not in FREE: if entry.status in ("applied", "held", "released"): tx["replays"] = tx.get("replays", 0) + 1 + # Unverified-success class: a replay sends nothing, so it + # is VERIFIED only if its effect reads back now. A held + # write is still waiting. + replay_verified: Optional[bool] = None + if entry.status == "held": + tx["held"] = tx.get("held", 0) + 1 + else: + replay_verified, _ = _readback(ctx, w, base, entry.result) + if replay_verified is not True: + tx["unverified_replays"] = ( + tx.get("unverified_replays", 0) + 1 + ) results.append( _line( ok=True, - verified=None, + verified=replay_verified, irreversible=w["irreversible"], payload=payload, code="replay_not_sent", @@ -1146,7 +1184,7 @@ def refuse(code: str, detail: str = "", approval: Any = None) -> TxRefused: ok = not stop and not missed and not false and not tx["refuted"] outcome = ( "VERIFIED" - if ok and not tx.get("held") + if ok and not tx.get("held") and not tx.get("unverified_replays") else ("COMPLETED_UNVERIFIED" if ok else "RECONCILIATION_REQUIRED") ) run = _write_run( @@ -1177,6 +1215,9 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: state, spec = ctx.state, ctx.spec with state.lock(): plan, priv = load_plan(state, digest) + if plan["spec_sha256"] != _spec_sha(spec): + # Wrong-target class: undo goes only to the systems the plan named. + raise TxRefused("spec_changed", "the tx file changed since the plan") applied_path = state.plan_dir(digest) / "applied.json" if not applied_path.exists(): raise TxRefused("not_applied", digest[:12]) @@ -1251,9 +1292,20 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: ok = back is not None and _norm(system, w, back) == _norm( system, w, base ) - state.record( - key, "undone", plan=digest, payload=entry.payload, read_back=ok - ) + if ok: + state.record( + key, "undone", plan=digest, payload=entry.payload, read_back=ok + ) + else: + # Unverified-success class: a compensation the read-back + # refutes is not undone, and keeps its replay key. + state.record( + key, + "uncertain", + plan=digest, + payload=entry.payload, + reason="undo: the read-back does not show the baseline", + ) per_write[key] = "undone" if ok else "undo_refuted" # The whole frame back to the baseline: the records and the collateral. after = ctx.frames(list(priv["frames"])) @@ -1330,7 +1382,9 @@ def undo_plan(ctx: Ctx, digest: str) -> dict[str, Any]: ) # An applied write with no undo (DDL, or no undo images) is still in # place: the plan is not rolled back, whatever the rows show. - not_undone = [k for k, v in per_write.items() if v == "no_undo"] + not_undone = [ + k for k, v in per_write.items() if v in ("no_undo", "irreversible_released") + ] ok = len(verified) == len(counted) and not collateral and not not_undone outcome = "ROLLED_BACK" if ok else "RECONCILIATION_REQUIRED" approval = state.approval_record(digest) @@ -1382,6 +1436,9 @@ def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, A at = now() if at is None else at with state.lock(): plan, priv = load_plan(state, digest) + if plan["spec_sha256"] != _spec_sha(ctx.spec): + # Wrong-target class: a release goes only where the plan said. + raise TxRefused("spec_changed", "the tx file changed since the plan") writes = {w["key"]: (w, b) for w, b in zip(priv["writes"], priv["baselines"])} results = [] tx: dict[str, Any] = { @@ -1400,10 +1457,36 @@ def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, A key = item["key"] w, base = writes[key] adapter = ctx.adapter(w["system"]) + prior = state.entry(key) + # Double-send class: a release that began before may have landed + # even if the target doesn't show it yet. Never send it again. + retried = prior is not None and any( + e.get("event") == "release_begun" for e in prior.events + ) state.record(key, "release_begun", plan=digest, payload=w["payload_sha256"]) verified: Optional[bool] if isinstance(adapter, MailAdapter): before = adapter.count(key) + if before == 0 and retried: + before = adapter.wait_count(key, 1) + if before == 0 and retried: + state.record( + key, + "uncertain", + plan=digest, + payload=w["payload_sha256"], + reason="an earlier release may have sent it", + ) + results.append( + _line( + ok=False, + verified=None, + irreversible=True, + payload=w["payload_sha256"], + code="release_uncertain", + ) + ) + continue if before == 0: try: adapter.send(w, key) @@ -1431,6 +1514,31 @@ def release(ctx: Ctx, digest: str, *, at: Optional[float] = None) -> dict[str, A tx["double"] += int(n > 1) verified = n == 1 else: + # Stale-baseline class: the record must still be what the + # plan read, or the held write would clobber a newer edit. + if w.get("id") is not None and w["op"] in ("update", "delete"): + current = adapter.read(w["collection"], str(w["id"])) + system = ctx.spec.system(w["system"]) + if current is None or _norm(system, w, current) != _norm( + system, w, base + ): + state.record( + key, + "uncertain", + plan=digest, + payload=w["payload_sha256"], + reason="changed during holdback", + ) + results.append( + _line( + ok=False, + verified=None, + irreversible=True, + payload=w["payload_sha256"], + code="changed_during_holdback", + ) + ) + continue adapter.apply(w, base, key) verified, _ = _readback(ctx, w, base, {"id": w.get("id")}) state.unhold(key) diff --git a/packages/flow/openadapt_flow/txplan/proxy.py b/packages/flow/openadapt_flow/txplan/proxy.py index fae93abaef..a11cef97bf 100644 --- a/packages/flow/openadapt_flow/txplan/proxy.py +++ b/packages/flow/openadapt_flow/txplan/proxy.py @@ -288,9 +288,16 @@ def tools(self) -> list[dict[str, Any]]: # the person's keys --------------------------------------------------------- def key(self, ch: str) -> str: - """``y`` approves the oldest waiting plan, ``n`` declines it, ``u`` undoes + """``y`` approves the one waiting plan, ``n`` declines it, ``u`` undoes the last applied one.""" with self.lock: + if ch in ("y", "n") and len(self.pending) > 1: + # Wrong-subject class: with several plans waiting, a key press + # can't say which one the person read, so it decides none. + return ( + f"{len(self.pending)} plans are waiting: approve one by id with " + "`openadapt plan approve `" + ) if ch == "y" and self.pending: digest = self.pending.pop(0) engine.approve_plan( diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 3667c807a1..989bbc79f6 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -622,6 +622,8 @@ def test_email_release_sends_once_even_after_a_crash( assert len(mail.messages) == 1 and out["outcome"] == "VERIFIED" undone = engine.undo_plan(ctx, plan["digest"]) assert undone["tx"]["irreversible_released"] == 1 + # A sent email can't be taken back: the plan is not rolled back. + assert undone["outcome"] == "RECONCILIATION_REQUIRED" # -- receipts ------------------------------------------------------------------ @@ -796,10 +798,46 @@ def test_sql_apply_refuses_a_plan_without_its_planned_values(tmp_path: Path) -> for w in data["writes"]: w.pop("staged_after", None) write_private(private, data) - proxy.key("y") - out = proxy.apply(got["plan"]) - assert out["outcome"] != "VERIFIED" and out["tx"]["sent"] == 0, out - assert _all(db) == before + with pytest.raises(TxRefused) as exc: + proxy.apply(got["plan"]) + assert exc.value.code == "plan_tampered" and _all(db) == before + + +def test_transaction_control_is_never_a_write(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=5) + proxy = _proxy(db, max_rows=100) + for sql in ( + "COMMIT", + "end", + "BEGIN", + "SAVEPOINT a", + "ROLLBACK", + "PRAGMA foreign_keys = OFF", + ): + with pytest.raises(TxRefused) as exc: + proxy.preview(sql) + assert exc.value.code == "bad_write", sql + + +def test_a_key_press_with_several_plans_waiting_approves_none(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=50) + proxy = _proxy(db, max_rows=1) + a = proxy.preview("UPDATE users SET active = 0 WHERE id <= 10") + b = proxy.preview("UPDATE users SET active = 0 WHERE id <= 20") + assert a["approval"].startswith("waiting") and b["approval"].startswith("waiting") + assert "2 plans are waiting" in proxy.key("y") + with pytest.raises(TxRefused): + proxy.apply(a["plan"]) + + +def test_rest_path_values_are_one_segment() -> None: + from openadapt_flow.txplan.adapters import AdapterError, RestAdapter + + fill = RestAdapter._fill + assert fill("/c/{id}", {"id": "a/../b?x=1"}) == "/c/a%2F..%2Fb%3Fx%3D1" + for bad in (".", ".."): + with pytest.raises(AdapterError): + fill("/c/{id}", {"id": bad}) def test_undo_of_a_write_it_cannot_undo_is_not_rolled_back(tmp_path: Path) -> None: @@ -992,9 +1030,13 @@ def test_proxy_commits_only_the_planned_values(tmp_path: Path) -> None: ) priv_path.write_text(json.dumps(priv)) before = _all(db) - with pytest.raises(TxRefused): + # The edited private plan no longer matches the digest a person approves. + with pytest.raises(TxRefused) as exc: + proxy.key("y") + assert exc.value.code == "plan_tampered" + with pytest.raises(TxRefused) as exc: proxy.apply(got["plan"]) - assert _all(db) == before + assert exc.value.code == "plan_tampered" and _all(db) == before def test_proxy_time_defaults_are_volatile_and_random_values_are_flagged( From 1714660cd323a1f1c6af41d30306f80ed0a3553c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:45:22 -0500 Subject: [PATCH 17/21] fix(plan): round-4 fail-opens: admitted statements, resolved targets, undo keys, row identity - unstaged commit: only INSERT, UPDATE, DELETE, MERGE, REPLACE or DDL is a raw-SQL write; anything the stage can't roll back is refused. - wrong target: the approved digest binds the SQLite file a relative path resolved to. - unverified success: a refuted SQL undo is recorded uncertain and keeps its replay key. - missing evidence: every REST list row needs a present identity, unique across the scan. --- .../flow/openadapt_flow/txplan/adapters.py | 13 ++++++- packages/flow/openadapt_flow/txplan/engine.py | 34 +++++++++++++++++-- packages/flow/tests/test_txplan.py | 32 +++++++++++++++++ 3 files changed, 76 insertions(+), 3 deletions(-) diff --git a/packages/flow/openadapt_flow/txplan/adapters.py b/packages/flow/openadapt_flow/txplan/adapters.py index 73b5a367d5..704a89d96f 100644 --- a/packages/flow/openadapt_flow/txplan/adapters.py +++ b/packages/flow/openadapt_flow/txplan/adapters.py @@ -357,8 +357,19 @@ def frame(self, collection: Optional[str]) -> dict[str, dict[str, str]]: else: raise AdapterError("a list did not return a list") fresh = 0 + page_ids: set[str] = set() for item in items: - rid = f"{coll.name}/{item.get(coll.id_field)}" + ident = item.get(coll.id_field) if isinstance(item, Mapping) else None + if ident in (None, ""): + # Missing-evidence class: a row without its identity can't + # be placed in the frame. + raise AdapterError(f"a {coll.name} row has no {coll.id_field}") + rid = f"{coll.name}/{ident}" + if rid in page_ids or rid in out: + # One identity per row across the whole scan: a repeat + # means the pages shifted, so the frame can't be trusted. + raise AdapterError(f"the list repeated {rid}") + page_ids.add(rid) if rid not in out: fresh += 1 out[rid] = column_digests(self.normalize(coll, item)) diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index 0f593d0be5..c978029ddc 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -62,6 +62,7 @@ _DDL = re.compile( r"^\s*(create|alter|drop|truncate|rename|comment|grant|revoke)\b", re.I ) +_DML = re.compile(r"^\s*(insert|update|delete|merge|replace)\b", re.I) _READ = re.compile(r"^\s*(select|with|show|explain|pragma|values)\b", re.I) #: Test hook: exit right after the Nth send, before its outcome is recorded. CRASH_ENV = "OPENADAPT_TX_CRASH_AFTER_SEND" @@ -202,7 +203,18 @@ def frames(self, scopes: Sequence[str]) -> dict[str, dict[str, dict[str, str]]]: def _spec_sha(spec: TxSpec) -> str: - return sha256(spec.model_dump(mode="json")) + # Wrong-target class: a relative SQLite path names a file relative to the + # tx file (or the working folder), so the approved digest binds the file + # it resolved to, not just the spelling. + resolved = {} + for system in spec.systems: + path = getattr(system, "path", None) + if getattr(system, "dialect", None) == "sqlite" and path: + p = Path(str(path)) + resolved[system.name] = str( + (p if p.is_absolute() else spec.root / p).resolve() + ) + return sha256({"spec": spec.model_dump(mode="json"), "sqlite_files": resolved}) # -- receipts ------------------------------------------------------------------ @@ -435,7 +447,19 @@ def _undo_sql( now_.get(r) == _row_digests(adapter, r, item["row"]) for r, item in images.get("before", {}).items() ) - state.record(w["key"], "undone", plan=digest, payload=entry.payload, read_back=ok) + if ok: + state.record( + w["key"], "undone", plan=digest, payload=entry.payload, read_back=ok + ) + else: + # Unverified-success class: a refuted SQL undo keeps its replay key. + state.record( + w["key"], + "uncertain", + plan=digest, + payload=entry.payload, + reason="undo: the read-back does not show the baseline", + ) return "undone" if ok else "undo_refuted" @@ -468,6 +492,12 @@ def _check_write(spec: TxSpec, n: int, w: Mapping[str, Any]) -> dict[str, Any]: raise TxRefused( "bad_write", f"write {n}: a read is not a write (use a query)" ) + if not (_DML.match(sql) or _DDL.match(sql)): + # Unstaged-commit class: only statements the staging transaction + # can roll back are admitted. + raise TxRefused( + "bad_write", f"write {n}: only INSERT, UPDATE, DELETE, MERGE or DDL" + ) if _TX_CONTROL.match(sql): # Unstaged-commit class: a transaction-control statement would end # the staging transaction and commit earlier writes before approval. diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 989bbc79f6..682587a519 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -830,6 +830,38 @@ def test_a_key_press_with_several_plans_waiting_approves_none(tmp_path: Path) -> proxy.apply(a["plan"]) +def test_only_statements_the_stage_can_roll_back_are_writes(tmp_path: Path) -> None: + db = _users(tmp_path / "app.sqlite", n=5) + proxy = _proxy(db, max_rows=100) + for sql in ("REINDEX users", "ANALYZE", "CALL do_things()", "COPY users FROM '/x'"): + with pytest.raises(TxRefused) as exc: + proxy.preview(sql) + assert exc.value.code == "bad_write", sql + + +def test_the_plan_binds_the_sqlite_file_a_relative_path_resolved_to( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from openadapt_flow.txplan.spec import TxSpec + + def spec(root: Path) -> TxSpec: + data = { + "schema_version": "openadapt.tx/v1", + "systems": [ + {"name": "db", "kind": "sql", "dialect": "sqlite", "path": "app.sqlite"} + ], + } + out = TxSpec.model_validate(data) + out.source = root / "systems.tx.yaml" + return out + + (tmp_path / "a").mkdir() + (tmp_path / "b").mkdir() + assert engine._spec_sha(spec(tmp_path / "a")) != engine._spec_sha( + spec(tmp_path / "b") + ) + + def test_rest_path_values_are_one_segment() -> None: from openadapt_flow.txplan.adapters import AdapterError, RestAdapter From ff850f97d110cd0ca21a36d2f934102c3187aa58 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:12:58 -0500 Subject: [PATCH 18/21] fix(cli,release): register plan/proxy cli_tasks mappings and update public-artifacts.json --- openadapt/cli_tasks.py | 2 ++ packages/flow/openadapt_flow/cli_tasks.py | 2 ++ packages/flow/public-artifacts.json | 5 +++++ 3 files changed, 9 insertions(+) diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 5506fde964..8bc0cf2e0d 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -78,8 +78,10 @@ "materialize-approved": "compile --materialize-approved", "narration": "record narration", "no-outbound": "setup no-outbound", + "plan": "run --plan", "process": "run --process", "propose-qualification": "qualify --propose", + "proxy": "services proxy", "pull": "workflow pull", "push": "workflow push", "qualify": "qualify", diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index d05021c0f1..cb075b91ae 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -77,8 +77,10 @@ "materialize-approved": "compile --materialize-approved", "narration": "record narration", "no-outbound": "setup no-outbound", + "plan": "run --plan", "process": "run --process", "propose-qualification": "qualify --propose", + "proxy": "services proxy", "pull": "workflow pull", "push": "workflow push", "qualify": "qualify", diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 67e5aa70b0..5a3f1a301e 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -655,6 +655,11 @@ "benchmark/effectbench/task_pack/manifest.json", "benchmark/environments/environments.json", "benchmark/environments/verification.json", + "benchmark/ext_tx/compose.yml", + "benchmark/ext_tx/results/run1-2026-11-21-apps.json", + "benchmark/ext_tx/results/run1-2026-11-21-proxy.json", + "benchmark/ext_tx/results/run2-2026-11-21-apps.json", + "benchmark/ext_tx/results/run2-2026-11-21-proxy.json", "benchmark/fault_model/results.json", "benchmark/fhir_medplum/app_semantics/medplum-v2.yaml", "benchmark/fhir_medplum/app_semantics/medplum.yaml", From 26ae7591a296cac7d4dfe1efc33d34fee6325cf6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:29:50 -0500 Subject: [PATCH 19/21] fix(txplan,cli): disable parser abbreviations and use open_binary in state.py --- packages/flow/benchmark/ext_tx/proxy_lab.py | 2 +- packages/flow/benchmark/ext_tx/run.py | 2 +- packages/flow/openadapt_flow/txplan/cli.py | 14 ++++++++++---- packages/flow/openadapt_flow/txplan/state.py | 10 ++++++---- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/flow/benchmark/ext_tx/proxy_lab.py b/packages/flow/benchmark/ext_tx/proxy_lab.py index 6b3f70f98c..0d1255689b 100644 --- a/packages/flow/benchmark/ext_tx/proxy_lab.py +++ b/packages/flow/benchmark/ext_tx/proxy_lab.py @@ -147,7 +147,7 @@ def n(v: Any) -> int: def main() -> int: - ap = argparse.ArgumentParser() + ap = argparse.ArgumentParser(allow_abbrev=False) ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=120) ap.add_argument("--seed", type=int, default=20261121) diff --git a/packages/flow/benchmark/ext_tx/run.py b/packages/flow/benchmark/ext_tx/run.py index 92045a7ca6..c70757d02f 100644 --- a/packages/flow/benchmark/ext_tx/run.py +++ b/packages/flow/benchmark/ext_tx/run.py @@ -534,7 +534,7 @@ def apply_and_poke(self, w, base, key, _real=real): # noqa: ANN001 def main() -> int: - ap = argparse.ArgumentParser() + ap = argparse.ArgumentParser(allow_abbrev=False) ap.add_argument("--phase", choices=["pilot", "measured"], required=True) ap.add_argument("--out", required=True) ap.add_argument("--batches", type=int, default=10) diff --git a/packages/flow/openadapt_flow/txplan/cli.py b/packages/flow/openadapt_flow/txplan/cli.py index c6062c04e2..4a1b9d940a 100644 --- a/packages/flow/openadapt_flow/txplan/cli.py +++ b/packages/flow/openadapt_flow/txplan/cli.py @@ -58,7 +58,9 @@ def common(q: argparse.ArgumentParser, tx: bool = True) -> None: q.add_argument("--json", action="store_true", help="print JSON") q = verbs.add_parser( - "create", help="read the baseline and print the predicted diff" + "create", + help="read the baseline and print the predicted diff", + allow_abbrev=False, ) q.add_argument( "--task", @@ -77,11 +79,13 @@ def common(q: argparse.ArgumentParser, tx: bool = True) -> None: ("release", "release held irreversible writes whose holdback passed"), ("cancel", "cancel held writes before release"), ): - q = verbs.add_parser(verb, help=text) + q = verbs.add_parser(verb, help=text, allow_abbrev=False) q.add_argument("plan", help="a plan digest or its prefix") common(q, tx=verb not in ("show", "cancel")) q = verbs.add_parser( - "approve", help="approve one plan digest, once (a person at a terminal)" + "approve", + help="approve one plan digest, once (a person at a terminal)", + allow_abbrev=False, ) q.add_argument("plan") q.add_argument( @@ -93,7 +97,9 @@ def common(q: argparse.ArgumentParser, tx: bool = True) -> None: help="record the approval as automation (lab runs; the receipt then says agent)", ) common(q, tx=False) - q = verbs.add_parser("status", help="list held writes and ledger entries") + q = verbs.add_parser( + "status", help="list held writes and ledger entries", allow_abbrev=False + ) common(q, tx=False) diff --git a/packages/flow/openadapt_flow/txplan/state.py b/packages/flow/openadapt_flow/txplan/state.py index ff0796e433..d3d3ea0fc4 100644 --- a/packages/flow/openadapt_flow/txplan/state.py +++ b/packages/flow/openadapt_flow/txplan/state.py @@ -33,6 +33,8 @@ from pathlib import Path from typing import Any, Iterator, Mapping, Optional +from openadapt_flow.private_file import open_binary + STATE_ENV = "OPENADAPT_TX_STATE" @@ -65,7 +67,7 @@ def write_private(path: Path, payload: Any) -> None: """Write JSON owner-only, atomically.""" _private_dir(path.parent) tmp = path.with_name(path.name + f".{os.getpid()}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + fd = open_binary(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) try: os.write( fd, @@ -126,7 +128,7 @@ def secret(self) -> bytes: if not path.exists(): fd = None with contextlib.suppress(FileExistsError): - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + fd = open_binary(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) os.write(fd, secrets.token_hex(32).encode()) os.fsync(fd) if fd is not None: @@ -159,7 +161,7 @@ def tag(self, text: str) -> str: def lock(self) -> Iterator[None]: """One applier per state folder at a time (an OS lock the kernel drops when the process dies).""" - fd = os.open(self.root / "lock", os.O_RDWR | os.O_CREAT, 0o600) + fd = open_binary(self.root / "lock", os.O_RDWR | os.O_CREAT, 0o600) try: if os.name == "nt": # pragma: no cover - Windows import msvcrt @@ -185,7 +187,7 @@ def record(self, key: str, event: str, **fields: Any) -> None: line = json.dumps( {"event": event, "at": now(), **fields}, sort_keys=True, default=str ) - fd = os.open( + fd = open_binary( self._ledger_path(key), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600 ) try: From d251a12e594d9b4343400d1cb076db57114cf3a4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:41:11 -0500 Subject: [PATCH 20/21] style(flow): sort imports in receipt_record.py (ruff I001) --- packages/flow/openadapt_flow/receipt_record.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index c21392ea28..07144273c9 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -28,9 +28,10 @@ from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence if TYPE_CHECKING: - from openadapt_flow.seal_keys import SealSigner from openadapt_types.receipt import ReceiptVerification, RoleKey + from openadapt_flow.seal_keys import SealSigner + RECEIPT_FILE = "receipt.json" PRIVATE_FILE = "receipt.private.json" CARD_FILE = "receipt.card.json" @@ -153,9 +154,10 @@ def build_statement( salt: Any = None, ) -> tuple[dict[str, Any], dict[str, dict[str, str]]]: """The ``record/run/v1`` statement for a run report, and its private openings.""" - from openadapt_flow.public_seal import _checks, _hour, _int from openadapt_types import receipt as r + from openadapt_flow.public_seal import _checks, _hour, _int + results = report.get("results") results = ( [x for x in results if isinstance(x, Mapping)] @@ -279,9 +281,10 @@ def write_receipt_record( Idempotent: an existing receipt over the same report bytes is kept. A receipt over different bytes is never silently replaced. """ + from openadapt_types import receipt as r + from openadapt_flow.offline_seal import loads_strict, signer_for from openadapt_flow.seal_keys import KeyUnavailable - from openadapt_types import receipt as r run_dir = Path(run_dir) report_path = run_dir / "report.json" @@ -383,9 +386,10 @@ def local_registry( Demo keys are never trusted by default. """ - from openadapt_flow.offline_seal import public_key_entry, seal_home, signer_for from openadapt_types.receipt import RoleKey + from openadapt_flow.offline_seal import public_key_entry, seal_home, signer_for + keys: list[RoleKey] = list(extra) try: home = home or seal_home(env) @@ -436,9 +440,10 @@ def _pinned_cloud_keys(home: Optional[Path]) -> list["RoleKey"]: def load_role_registry(path: Path) -> list["RoleKey"]: - from openadapt_flow.offline_seal import loads_strict from openadapt_types.receipt import parse_registry + from openadapt_flow.offline_seal import loads_strict + return parse_registry(loads_strict(Path(path).read_text(encoding="utf-8"))) @@ -446,9 +451,10 @@ def verify_run_receipt( run_dir: Path, registry: Sequence["RoleKey"] ) -> "ReceiptVerification": """Verify ``run_dir/receipt.json`` and check it covers the run's report bytes.""" - from openadapt_flow.offline_seal import loads_strict from openadapt_types import receipt as r + from openadapt_flow.offline_seal import loads_strict + run_dir = Path(run_dir) try: envelope = loads_strict((run_dir / RECEIPT_FILE).read_text(encoding="utf-8")) From 029a59909e3203914ecbd9a3e022a816a1e1cbea Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:20:58 -0500 Subject: [PATCH 21/21] fix(txplan,hooks,cli): align receipt blocks with #2410 contract and keep __main__.py within ratchet --- packages/flow/openadapt_flow/__main__.py | 48 +++++-------------- packages/flow/openadapt_flow/hooks/engine.py | 29 ++++++++++- packages/flow/openadapt_flow/txplan/engine.py | 26 +++++++++- packages/flow/tests/test_hooks_e2e.py | 6 ++- packages/flow/tests/test_txplan.py | 5 ++ 5 files changed, 73 insertions(+), 41 deletions(-) diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index a415dee552..1522451d3b 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13179,56 +13179,32 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: ), ) + from openadapt_flow.agent_guard.cli import add_parser as _add_guard_parser + from openadapt_flow.cli_cleanup import register as _register_cleanup + from openadapt_flow.cli_fleet import register_fleet_parser + from openadapt_flow.cli_receipt import register as _register_receipt + from openadapt_flow.cli_reconcile import register as _register_reconcile from openadapt_flow.cli_rollback import register as _register_rollback - - _register_rollback(sub) - from openadapt_flow.cli_shadow import register as _register_shadow + from openadapt_flow.compile_agent.cli import add_parser as _add_compile_agent_parser + from openadapt_flow.hooks.cli import add_parser as _add_hooks_parser + from openadapt_flow.jit.cli import add_parser as _add_jit_parser + from openadapt_flow.learn import register as _register_learn + from openadapt_flow.txplan.cli import add_parser as _add_plan_parser + from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser + _register_rollback(sub) _register_shadow(sub) - - from openadapt_flow.cli_receipt import register as _register_receipt - _register_receipt(sub) - - from openadapt_flow.learn import register as _register_learn - _register_learn(sub) - - from openadapt_flow.cli_reconcile import register as _register_reconcile - _register_reconcile(sub) - - from openadapt_flow.cli_cleanup import register as _register_cleanup - _register_cleanup(sub) - - from openadapt_flow.jit.cli import add_parser as _add_jit_parser - _add_jit_parser(sub) - - from openadapt_flow.compile_agent.cli import add_parser as _add_compile_agent_parser - _add_compile_agent_parser(sub) - - from openadapt_flow.agent_guard.cli import add_parser as _add_guard_parser - _add_guard_parser(sub) - - from openadapt_flow.hooks.cli import add_parser as _add_hooks_parser - _add_hooks_parser(sub) - - from openadapt_flow.txplan.cli import add_parser as _add_plan_parser - _add_plan_parser(sub) - - from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser - _add_proxy_parser(sub) - - from openadapt_flow.cli_fleet import register_fleet_parser - register_fleet_parser(sub) parser.add_task_help() diff --git a/packages/flow/openadapt_flow/hooks/engine.py b/packages/flow/openadapt_flow/hooks/engine.py index 8e897596a5..da1d789099 100644 --- a/packages/flow/openadapt_flow/hooks/engine.py +++ b/packages/flow/openadapt_flow/hooks/engine.py @@ -513,6 +513,19 @@ def _run_folder( effect = {"VERIFIED": True, "REFUTED": False}.get(label) sent = label != "BLOCKED" name = ".".join(x for x in (system, write or "undeclared") if x) + contract_hash = f"sha256:{_sha(contract or 'undeclared')}" + evidence: list[dict[str, Any]] = [] + if sent and effect is not None: + evidence.append( + { + "effect_contract_hash": contract_hash, + "substrate": "api", + "initial_verdict": "confirmed" if effect else "refuted", + "final_verdict": "confirmed" if effect else "refuted", + "observed_effect": "present" if effect else "absent", + "verification_tier": 1, + } + ) report: dict[str, Any] = { "schema_version": REPORT_SCHEMA, "workflow_name": name[:48], @@ -528,8 +541,11 @@ def _run_folder( "system": system, "write": write, "hold_sha256": digest, + "change_ledger": [], "results": [ { + "step_id": write_id, + "intent": f"hook {name}", "ok": label == "VERIFIED", "actuation": "api", **( @@ -539,7 +555,8 @@ def _run_folder( # says effect_not_declared. A declared write whose # read-back didn't settle says approved_unverified # (record/run/v1 has no read-back-failed code). - "effect_contract_hashes": [_sha(contract or "undeclared")], + "effect_contract_hashes": [contract_hash], + "effect_evidence": evidence, "effect_approved_unverified": bool(contract) and effect is None, } @@ -547,7 +564,15 @@ def _run_folder( else {} ), **( - {"effect_field_checks": ["delta"]} + { + "effect_field_checks": [ + { + "field": "delta", + "matched": True, + "verification_tier": 1, + } + ] + } if result is not None and (result.checked or {}).get("delta") == "held" else {} diff --git a/packages/flow/openadapt_flow/txplan/engine.py b/packages/flow/openadapt_flow/txplan/engine.py index c978029ddc..62aa8a0b99 100644 --- a/packages/flow/openadapt_flow/txplan/engine.py +++ b/packages/flow/openadapt_flow/txplan/engine.py @@ -229,6 +229,7 @@ def _approval_block( "approvals": [], } if approval: + block["decision"] = "approved" block["approvals"].append( { "decision": "approved", @@ -267,6 +268,7 @@ def _write_run( "execution_outcome": outcome, "success": outcome in ("VERIFIED", "ROLLED_BACK"), "model_calls": 0, + "change_ledger": [], "results": results, "approval": _approval_block(approval, digest), "outcome_envelope": { @@ -313,14 +315,34 @@ def receipt_status(run_dir: Path | str) -> str: def _line( *, ok: bool, verified: Optional[bool], irreversible: bool, payload: str, code: str ) -> dict[str, Any]: + contract_hash = payload if payload.startswith("sha256:") else f"sha256:{payload}" + evidence: list[dict[str, Any]] = [] + if verified is not None: + evidence.append( + { + "effect_contract_hash": contract_hash, + "substrate": "api", + "initial_verdict": "confirmed" if verified else "refuted", + "final_verdict": "confirmed" if verified else "refuted", + "observed_effect": "present" if verified else "absent", + "verification_tier": 1, + } + ) return { + "step_id": f"tx-{code}", + "intent": f"tx {code}", "ok": ok, "effect_verified": verified, "effect_approved_unverified": verified is None, "actuation": "api", "risk": "irreversible" if irreversible else "reversible", - "effect_contract_hashes": [payload], - "effect_field_checks": verified is not None, + "effect_contract_hashes": [contract_hash], + "effect_evidence": evidence, + "effect_field_checks": ( + [{"field": "delta", "matched": verified, "verification_tier": 1}] + if verified is not None + else [] + ), "postconditions_ok": None, "tx_code": code, } diff --git a/packages/flow/tests/test_hooks_e2e.py b/packages/flow/tests/test_hooks_e2e.py index 8100fb23d2..b943533087 100644 --- a/packages/flow/tests/test_hooks_e2e.py +++ b/packages/flow/tests/test_hooks_e2e.py @@ -370,7 +370,11 @@ def test_claude_code_allowed_blocked_and_uncertain(project: Path, api: str) -> N assert verified.ok and verified.outcome == "UNKNOWN" line = verified.statement["predicate"]["lines"][0] assert line["check"] == "not_checked" and line["strength"] == "none" - assert line["not_checked"] == ["approved_unverified", "postconditions"] + assert line["not_checked"] == [ + "approved_unverified", + "field_values", + "postconditions", + ] assert verified.statement["predicate"]["checks"]["effects"] == { "required": 1, "confirmed": 0, diff --git a/packages/flow/tests/test_txplan.py b/packages/flow/tests/test_txplan.py index 682587a519..53bdc2e96f 100644 --- a/packages/flow/tests/test_txplan.py +++ b/packages/flow/tests/test_txplan.py @@ -668,6 +668,11 @@ def test_each_phase_gets_a_signed_receipt_with_the_approval_bound( stmt = verify_run_receipt(Path(applied["run_dir"]), registry).statement assert stmt["predicate"]["approval"]["mode"] == "each_item" assert stmt["predicate"]["approval"]["approver_kind"] == "agent" + assert stmt["predicate"]["approval"]["commitments"] + plan_stmt = verify_run_receipt(Path(plan["run_dir"]), registry).statement + assert plan_stmt["predicate"]["approval"]["mode"] == "each_item" + assert plan_stmt["predicate"]["approval"]["approver_kind"] == "none" + assert plan_stmt["predicate"]["approval"]["commitments"] == {} def test_cli_create_show_approve_apply(