diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0397-count-who-saved-an-update-s-target-on-postgresql.md b/capabilities/04-the-core-a-checked-entry-every-time/0397-count-who-saved-an-update-s-target-on-postgresql.md
new file mode 100644
index 0000000000..adcfb0aa22
--- /dev/null
+++ b/capabilities/04-the-core-a-checked-entry-every-time/0397-count-who-saved-an-update-s-target-on-postgresql.md
@@ -0,0 +1 @@
+| Count who saved an update's target on PostgreSQL, so learned bookkeeping can be excused on updates and found checks too: `frame.row_versions` holds a read-only REPEATABLE READ snapshot from the baseline to the judge; the replaced row version's `xmax` against the current row's `xmin` says whether one transaction or more wrote the target. Two or more refute the frame as a lost update; a judge in another process, a failed read, a target created in the window, an `xmax` that could be a shared lock naming another updater, or a `frame.row_versions` table and key that aren't the ones the target surface reads the target from stop it as not checked. `learn probe --apply` writes the source beside the excuse when the contract's read is one `SELECT` over one table (no join, `UNION`, subquery or second statement). Not yet: MySQL and MariaDB targets (a last-saved marker can't count saves; they need a history read or the change log), rows a window adds and removes on a composite key | (this PR) | Real app replay (InvenTree on PostgreSQL, first-contact retest, frozen vs fix vs this branch on identical writes): correct writes stopped 65, 48 and 27 of 65; the 21 released were all bookkeeping stops on updates and found checks, and none newly stopped; 0 of 31 planted and agent harms passed in any variant, and the row-version check itself refuted the planted lost updates (the pack's 2 plus a no-gap PATCH, a no-gap PUT, a found-check revert and a child-row revert); 9 of 9 excuse attacks stopped. No change on MariaDB apps (no source is derived) | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) |
diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md
index 7fcbb45ad0..d7b3a66b1d 100644
--- a/packages/flow/docs/LEARNED_EXCUSES.md
+++ b/packages/flow/docs/LEARNED_EXCUSES.md
@@ -233,7 +233,32 @@ effect (its `target_surface`; with none set, every other effect must be
on one surface, since an unscoped read tells records apart by id alone). In an update with no
version source, another user's edit that the agent's stale save reverts
leaves nothing changed, and only the bookkeeping move stopped it, so such
-contracts keep stopping. No person approves them: the
+contracts keep stopping unless the probe can give them a version source.
+
+On PostgreSQL it can, for a contract whose write effects all read one
+surface, and whose read is one `SELECT ... FROM
t` (no other
+`FROM`, no join, `UNION`, `WITH`, subquery or second statement) over the
+frame's own connection with the identity field taken from one column. The
+probe then writes `frame.row_versions` (table, key column and target
+surface) beside the excuse. At check time the verifier derives the table
+and key again from the target surface's read and refuses a
+`frame.row_versions` that names another table or key (not checked), so a
+hand-written source can't point at a table nobody edits. At check time the verifier opens a read-only
+REPEATABLE READ transaction before it reads the baseline and keeps it open
+until the judge. That transaction still sees the target row's version from
+the baseline, and that version's `xmax` names the transaction that replaced
+it. If it equals the current row's `xmin`, one transaction saved the
+target. Anything else means two or more did, and the frame is refuted as a
+lost update. A judge in another process, a failed read, or a replaced
+version whose `xmax` could be a shared lock naming another updater makes the
+frame not checked. Only PostgreSQL's "has not been created yet" or "does no
+longer exist" answer means that `xmax` is a plain transaction id; any other
+error reading the lock leaves the frame not checked. A last-saved marker (`xmin` alone, `updated_at`,
+`ON UPDATE CURRENT_TIMESTAMP`) is not used: it reads the same after one
+save as after two. MySQL and MariaDB updates get no automatic source; they
+need `frame.versions` over a history table, or the database's change log.
+
+No person approves them: the
rows were read, the relation is derived from the schema, and the requests
are checked to be read-only. A contract that already has `frame.learned`
is refused, so a person reconciles the two. Receipts name the source.
diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py
index 4ad53d1ada..65dd6e2286 100644
--- a/packages/flow/openadapt_flow/learn_probe.py
+++ b/packages/flow/openadapt_flow/learn_probe.py
@@ -336,12 +336,16 @@ def apply(
names |= _learn._names(n)
except VerifierError as exc:
raise ProbeError(f"{path}: {exc}") from exc
+ row_versions = None
if not _sees_its_own_harm(loaded):
# An update (or a found check) with no version source: another
# user's edit that the agent's stale save reverts leaves nothing
# changed, so before learning only the bookkeeping move stopped
- # it. Such a contract gets no automatic excuse.
- continue
+ # it. Such a contract gets an excuse only with a version source
+ # derived here, written beside it.
+ row_versions = detect_row_versions(data)
+ if row_versions is None:
+ continue
excuses = [
e
for e in block["excuses"]
@@ -354,10 +358,14 @@ def apply(
**frame,
"learned": {**block, "excuses": excuses, "source": "read_only_probe"},
}
+ if row_versions is not None:
+ new["frame"]["row_versions"] = row_versions
try:
- Contract.from_dict(new, name=Path(path).stem)
+ checked = Contract.from_dict(new, name=Path(path).stem)
except VerifierError as exc:
raise ProbeError(f"{path}: {exc}") from exc
+ if row_versions is not None and not _sees_its_own_harm(checked):
+ continue # the derived source doesn't cover every effect
plan.append((Path(path), new, len(excuses)))
_learn._write_all(
[
@@ -374,11 +382,14 @@ def _sees_its_own_harm(contract: Any) -> bool:
Either every declared effect creates new records (``record_written``
with ``count_new_only``; a zero-count guard writes nothing), or the
- contract reads the target's versions (``frame.versions``) and those
- versions cover every other effect: with a ``target_surface``, each
- effect that isn't a create must be read on that surface. Anything else,
- such as a create plus a ``field_equals`` update, gets no excuse."""
-
+ contract reads the target's versions and they cover every other effect:
+ ``frame.versions`` (with a ``target_surface``, each effect that isn't a
+ create must be read on that surface), or ``frame.row_versions`` bound to
+ the target surface's own table (:func:`row_versions.binding_problem`)
+ with every other effect on that surface. Anything else, such as a create
+ plus a ``field_equals`` update, gets no excuse."""
+
+ from openadapt_flow.runtime.effects.row_versions import binding_problem
from openadapt_flow.runtime.effects.surfaces import surface_of
config = getattr(contract, "config", None)
@@ -405,16 +416,94 @@ def guard(effect: Any) -> bool:
others = [e for e in effects if not creates(e) and not guard(e)]
if not others:
return any(creates(e) for e in effects)
- versions = getattr(frame, "versions", None) if frame is not None else None
- if versions is None:
+ if frame is None:
+ return False
+ versions = getattr(frame, "versions", None)
+ if versions is not None:
+ surface = getattr(versions, "target_surface", None)
+ if surface is None:
+ # fail-open class: ambiguous-subject-binding. An unscoped version
+ # read judges targets by their local id alone, so two records
+ # with one id on two surfaces would share one version check.
+ if len({surface_of(e) for e in others}) == 1:
+ return True
+ elif all(surface_of(e) == surface for e in others):
+ return True
+ rows = getattr(frame, "row_versions", None)
+ database = getattr(frame, "database", None)
+ verifier = getattr(config, "verifier", None)
+ if rows is None or database is None or verifier is None:
+ return False
+ if binding_problem(
+ rows,
+ getattr(verifier, "surfaces", None) or {},
+ getattr(database, "read", None) or {},
+ getattr(frame, "identity_field", None),
+ ):
return False
- surface = getattr(versions, "target_surface", None)
- if surface is None:
- # fail-open class: ambiguous-subject-binding. An unscoped version
- # read judges targets by their local id alone, so two records with
- # one id on two surfaces would share one version check.
- return len({surface_of(e) for e in others}) == 1
- return all(surface_of(e) == surface for e in others)
+ return all(surface_of(e) == rows.target_surface for e in others)
+
+
+def detect_row_versions(data: Mapping[str, Any]) -> Optional[dict[str, Any]]:
+ """A version source for an update or found check, from the contract
+ alone: on PostgreSQL, the target's own row versions
+ (``frame.row_versions``). Found only when every write effect reads one
+ surface, that surface's read is a plain ``SELECT ... FROM t``
+ with no other ``FROM`` over the frame's own connection, and it selects the identity field
+ straight from one column. Anything else: None (no excuse).
+
+ A MySQL or MariaDB target has no such source: ``updated_at`` and
+ ``ON UPDATE`` columns read the same after one save as after two, so they
+ can't count saves. Those need a history read (``frame.versions``) or the
+ database's change log."""
+
+ frame = data.get("frame") if isinstance(data, Mapping) else None
+ if not isinstance(frame, Mapping):
+ return None
+ database = frame.get("database")
+ if not isinstance(database, Mapping) or database.get("dialect") != "postgresql":
+ return None
+ names: set[str] = set()
+ for effect in data.get("effects") or []:
+ if not isinstance(effect, Mapping):
+ return None
+ if effect.get("kind") not in ("record_written", "field_equals"):
+ continue
+ if effect.get("kind") == "record_written" and effect.get("expected_count") == 0:
+ continue # a guard reads; it has no target
+ probe = str(effect.get("probe") or "")
+ if not probe.startswith("surface="):
+ return None
+ names.add(probe[len("surface=") :].split("|", 1)[0].strip())
+ if len(names) != 1:
+ return None
+ (surface,) = names
+ verifier = data.get("verifier")
+ surfaces = verifier.get("surfaces") if isinstance(verifier, Mapping) else None
+ source = surfaces.get(surface) if isinstance(surfaces, Mapping) else None
+ if not isinstance(source, Mapping) or source.get("kind") != "sql":
+ return None
+ read = database.get("read") or {}
+ if any(source.get(k) != read.get(k) for k in ("sql_driver", "sql_connect_args")):
+ return None # another database: its rows aren't the frame's
+ from openadapt_flow.runtime.effects.row_versions import single_table_read
+
+ # One SELECT over one table: the declared record is one row, so the
+ # row's versions are the record's. A read that also looks into other
+ # tables (a list of tags, a child row, a UNION) declares rows this
+ # source doesn't count.
+ found = single_table_read(
+ str(source.get("sql_query") or ""), str(frame.get("identity_field") or "id")
+ )
+ if found is None:
+ return None
+ table, key_column = found
+ return {
+ "source": "postgresql_xmin",
+ "table": table,
+ "key_column": key_column,
+ "target_surface": surface,
+ }
def http_sender(
diff --git a/packages/flow/openadapt_flow/runtime/effects/frame.py b/packages/flow/openadapt_flow/runtime/effects/frame.py
index ca6bf0f209..60d0f9f912 100644
--- a/packages/flow/openadapt_flow/runtime/effects/frame.py
+++ b/packages/flow/openadapt_flow/runtime/effects/frame.py
@@ -99,6 +99,7 @@
covers,
set_columns,
)
+from openadapt_flow.runtime.effects.row_versions import FrameRowVersions
from openadapt_flow.runtime.effects.versions import FrameVersions, VersionVerdict
FrameStatus = Literal["held", "refuted", "not_checked"]
@@ -516,6 +517,10 @@ class FrameSpec(BaseModel):
#: (``versions.FrameVersions``): a version in the window that isn't the
#: agent's own is a lost update.
versions: Optional[FrameVersions] = None
+ #: The target's own row versions, held from the baseline
+ #: (``row_versions.FrameRowVersions``, PostgreSQL): two transactions
+ #: writing the target in the window are a lost update.
+ row_versions: Optional[FrameRowVersions] = None
#: Complete type/table change feeds for a provisional then final verdict.
history: Optional[FrameHistory] = None
#: Moves a person approved from ``openadapt-flow learn``
@@ -534,6 +539,8 @@ def _compact(self, handler: Any) -> dict[str, Any]:
data.pop("identities", None)
if data.get("versions") is None:
data.pop("versions", None)
+ if data.get("row_versions") is None:
+ data.pop("row_versions", None)
if data.get("learned") is None:
data.pop("learned", None)
if data.get("target_fields_by_surface") is None:
@@ -543,6 +550,12 @@ def _compact(self, handler: Any) -> dict[str, Any]:
@model_validator(mode="after")
def _database_attribution(self) -> "FrameSpec":
a = self.attribution
+ if self.row_versions is not None:
+ if self.database is None or self.database.dialect != "postgresql":
+ raise ValueError(
+ "frame.row_versions reads through frame.database, PostgreSQL only"
+ )
+ self.row_versions.names()
if (
self.history is not None
and self.database is not None
diff --git a/packages/flow/openadapt_flow/runtime/effects/row_versions.py b/packages/flow/openadapt_flow/runtime/effects/row_versions.py
new file mode 100644
index 0000000000..671160caf8
--- /dev/null
+++ b/packages/flow/openadapt_flow/runtime/effects/row_versions.py
@@ -0,0 +1,491 @@
+"""Row versions held from the baseline: count who saved the target.
+
+Two snapshots can't see a lost update (``versions.py``). A "last saved"
+marker on the row, such as PostgreSQL's ``xmin`` or an ``updated_at``
+column, can't either: after another user's save and the agent's stale save,
+it reads the same as after the agent's save alone. A marker only proves that
+nobody saved.
+
+PostgreSQL keeps more than the marker. A read-only REPEATABLE READ
+transaction opened at the baseline keeps seeing the row version that was
+current then, and that old version's ``xmax`` names the transaction that
+replaced it. The current version's ``xmin`` names the transaction that wrote
+it. So, per target row:
+
+- ``xmin`` unchanged: no transaction wrote the row in the window (0).
+- the old ``xmax`` equals the current ``xmin``: one transaction replaced the
+ version the baseline saw, and nothing replaced it since (1).
+- anything else: two or more transactions wrote the row (2+). A lock taken
+ while the row was being updated also lands here; that is a stop, never a
+ pass.
+
+``frame.row_versions`` names the target's table and key column. The
+verifier opens the held read before it reads the baseline records, keeps it
+in this process until the judge, and closes it there. A judge in another
+process, a read that fails, or a target the held read can't find stops the
+run as not checked. Never a pass.
+
+Every target must have existed at the baseline: a record created in the
+window (a duplicate made instead of the update) has no earlier version, so
+it stops the run as not checked. A target may have been written by at most
+one transaction, and one that changed by exactly one: two writers mean another user's save sits
+inside the window. That is the lost-update rule of ``versions.py`` (one step
+per save) with the row's own transaction ids as the steps.
+
+A lock shared by two transactions sets ``xmax`` to a multixact id, a
+separate counter. If that number equals the later writer's transaction id,
+two writers could read as one; when a multixact with that id exists and
+names another updater, the check is not checked rather than held.
+
+What it doesn't see: a row the window adds and removes again (no snapshot
+holds it; the frame's counter check catches it when the key comes from a
+sequence), and writes to rows other than the target, which the frame judges.
+"""
+
+from __future__ import annotations
+
+import re
+import threading
+import time
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from typing import Any, Callable, Optional
+
+from pydantic import BaseModel, ConfigDict, Field, model_serializer
+
+from openadapt_flow.runtime.effects.versions import VersionVerdict
+
+#: Where the baseline says whether the held read was opened (no values).
+DETAIL = "openadapt:frame_row_versions"
+
+_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_$]*$")
+
+
+class FrameRowVersions(BaseModel):
+ """``frame.row_versions``: the target table whose row versions are held."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ #: Only PostgreSQL keeps the replaced version visible to an old snapshot.
+ source: str = Field(default="postgresql_xmin", pattern="^postgresql_xmin$")
+ #: The target's table, ``table`` or ``schema.table`` (plain identifiers).
+ table: str = Field(min_length=1)
+ #: The table's key column, whose value is the target record's
+ #: ``target_field``.
+ key_column: str = Field(default="id", min_length=1)
+ #: The target record's field holding the key. Unset:
+ #: ``frame.identity_field``, else ``id``.
+ target_field: Optional[str] = None
+ #: Only records matched on this surface are targets. Unset: every record
+ #: a confirmed write effect matched.
+ target_surface: Optional[str] = None
+
+ @model_serializer(mode="wrap")
+ def _compact(self, handler: Any) -> dict[str, Any]:
+ data: dict[str, Any] = handler(self)
+ for key in ("target_field", "target_surface"):
+ if data.get(key) is None:
+ data.pop(key, None)
+ return data
+
+ def names(self) -> tuple[Optional[str], str, str]:
+ """(schema or None, table, key column), each a plain identifier."""
+
+ parts = self.table.split(".")
+ if len(parts) > 2 or not all(_NAME.match(p) for p in parts):
+ raise ValueError(
+ f"frame.row_versions.table {self.table!r} is not a plain "
+ "table or schema.table name"
+ )
+ if not _NAME.match(self.key_column):
+ raise ValueError(
+ f"frame.row_versions.key_column {self.key_column!r} is not a "
+ "plain column name"
+ )
+ schema = parts[0] if len(parts) == 2 else None
+ return schema, parts[-1], self.key_column
+
+
+_IDENT = r'(?:"[A-Za-z_][A-Za-z0-9_$]*"|[A-Za-z_][A-Za-z0-9_$]*)'
+#: The main relation of a generated read: ``... FROM "table" t`` at the end.
+_MAIN_FROM = re.compile(
+ rf"\bFROM\s+({_IDENT}(?:\.{_IDENT})?)\s+(?:AS\s+)?t\s*;?\s*$", re.IGNORECASE
+)
+#: Anything that lets one read return rows that aren't the main table's.
+_NOT_ONE_TABLE = re.compile(
+ r"\b(?:UNION|INTERSECT|EXCEPT|JOIN|LATERAL|WITH)\b|;(?!\s*$)", re.IGNORECASE
+)
+
+
+def _unquote(name: str) -> str:
+ return ".".join(p.strip('"') for p in name.split("."))
+
+
+def single_table_read(query: str, field: str) -> Optional[tuple[str, str]]:
+ """``(table, key column)`` when ``query`` is one ``SELECT`` over one
+ table aliased ``t`` that selects ``field`` straight from one of its
+ columns; None for anything else (a ``UNION``, a join, a subquery, a CTE,
+ a second statement, a second ``FROM``)."""
+
+ text = " ".join(str(query or "").split())
+ if (
+ len(re.findall(r"\bSELECT\b", text, re.IGNORECASE)) != 1
+ or len(re.findall(r"\bFROM\b", text, re.IGNORECASE)) != 1
+ or _NOT_ONE_TABLE.search(text)
+ or not re.match(r"^\s*SELECT\b", text, re.IGNORECASE)
+ ):
+ return None
+ main = _MAIN_FROM.search(text)
+ if main is None:
+ return None
+ # fail-open class: ambiguous-subject-binding. The whole select item must
+ # be the column itself (or its text cast): an expression that merely
+ # ends with the column returns another value than the one the row is
+ # looked up by.
+ column = re.search(
+ rf"(?:\bSELECT\s+|,\s*)(?:CAST\(\s*t\.({_IDENT})\s+AS\s+TEXT\s*\)|t\.({_IDENT}))"
+ rf'\s+AS\s+"?{re.escape(field)}"?\s*(?:,|\bFROM\b)',
+ text,
+ re.IGNORECASE,
+ )
+ if column is None:
+ return None
+ return _unquote(main.group(1)), _unquote(column.group(1) or column.group(2))
+
+
+def binding_problem(
+ spec: FrameRowVersions,
+ surfaces: Mapping[str, Any],
+ database_read: Mapping[str, Any],
+ identity_field: Optional[str],
+) -> Optional[str]:
+ """Why ``spec`` isn't bound to the record the contract reads, or None.
+
+ The held rows count saves only when they are the target's own rows: the
+ table and key column must be the ones the ``target_surface`` read takes
+ the target's ``target_field`` from, over the frame's own connection. A
+ hand-written ``table`` with the same key (a decoy that nobody else
+ edits) would otherwise vouch for a target it never held."""
+
+ if not spec.target_surface:
+ return "frame.row_versions names no target_surface"
+ source = surfaces.get(spec.target_surface)
+ get = (
+ source.get
+ if isinstance(source, Mapping)
+ else (lambda k, d=None: getattr(source, k, d))
+ )
+ if source is None or get("kind") != "sql":
+ return "frame.row_versions.target_surface is not a SQL read"
+ for key in ("sql_driver", "sql_connect_args"):
+ if (get(key) or None) != (database_read.get(key) or None):
+ return "the target surface reads another database than the frame"
+ field = spec.target_field or identity_field or "id"
+ found = single_table_read(str(get("sql_query") or ""), field)
+ if found is None:
+ return (
+ "the target surface's read is not one SELECT over one table that "
+ "selects the target field from one column"
+ )
+ table, key = found
+ if (table, key) != (_unquote(spec.table), spec.key_column):
+ return (
+ "frame.row_versions.table and key_column are not the table and "
+ "column the target surface reads the target from"
+ )
+ return None
+
+
+def _quote(name: str) -> str:
+ return '"' + name.replace('"', '""') + '"'
+
+
+def _query(spec: FrameRowVersions) -> str:
+ schema, table, key = spec.names()
+ relation = (_quote(schema) + "." if schema else "") + _quote(table)
+ return (
+ f"SELECT CAST({_quote(key)} AS TEXT), CAST(xmin AS TEXT), "
+ f"CAST(xmax AS TEXT) FROM {relation} "
+ f"WHERE CAST({_quote(key)} AS TEXT) = ANY(%s)"
+ )
+
+
+def _relkind_query(spec: FrameRowVersions) -> tuple[str, tuple[str, ...]]:
+ schema, table, _key = spec.names()
+ if schema is None:
+ return (
+ "SELECT c.relkind FROM pg_class c WHERE c.oid = to_regclass(%s)",
+ (_quote(table),),
+ )
+ return (
+ "SELECT c.relkind FROM pg_class c WHERE c.oid = to_regclass(%s)",
+ (_quote(schema) + "." + _quote(table),),
+ )
+
+
+class DuplicateKey(ValueError):
+ """A key column value names more than one physical row."""
+
+
+def _unique_rows(fetched: Sequence[tuple]) -> dict[str, tuple]:
+ """``key -> (xmin, xmax)``. fail-open class: ambiguous-subject-binding:
+ when a key maps to several rows, one version would silently replace the
+ other, so the read refuses instead."""
+
+ out: dict[str, tuple] = {}
+ for k, x, m in fetched:
+ if str(k) in out:
+ raise DuplicateKey(str(k))
+ out[str(k)] = (x, m)
+ return out
+
+
+@dataclass
+class HeldRead:
+ """An open read-only REPEATABLE READ transaction from the baseline."""
+
+ conn: Any
+ opened: float
+
+ def rows(self, spec: FrameRowVersions, keys: Sequence[str]) -> dict[str, tuple]:
+ cur = self.conn.cursor()
+ cur.execute(_query(spec), (list(keys),))
+ return _unique_rows(cur.fetchall())
+
+ def close(self) -> None:
+ try:
+ self.conn.cursor().execute("ROLLBACK")
+ except Exception: # noqa: BLE001 - closing changes nothing
+ pass
+ try:
+ self.conn.close()
+ except Exception: # noqa: BLE001
+ pass
+
+
+_LOCK = threading.Lock()
+_HELD: dict[str, HeldRead] = {}
+#: A held read older than this is closed when the next one opens (seconds).
+MAX_HOLD_S = 3600.0
+
+
+def open_held(spec: FrameRowVersions, connect: Callable[[], Any]) -> HeldRead:
+ """Open the held read and take its snapshot now. Raises on any failure
+ (the caller records the baseline as not held)."""
+
+ conn = connect()
+ try:
+ if type(conn).__module__.split(".")[0] not in ("psycopg2", "psycopg"):
+ raise ValueError("frame.row_versions reads PostgreSQL only")
+ # Autocommit off would start its own transaction at the first
+ # statement, at the default isolation; begin one explicitly instead.
+ conn.autocommit = True
+ cur = conn.cursor()
+ # The server ends a hold the judge never closes.
+ cur.execute(
+ "SET idle_in_transaction_session_timeout = %s", (f"{int(MAX_HOLD_S)}s",)
+ )
+ cur.execute("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
+ cur.execute(
+ "SELECT current_setting('transaction_isolation'), "
+ "current_setting('transaction_read_only')"
+ )
+ if tuple(cur.fetchone() or ()) != ("repeatable read", "on"):
+ raise ValueError("the held read is not a read-only snapshot")
+ sql, args = _relkind_query(spec)
+ cur.execute(sql, args)
+ kind = cur.fetchone()
+ # An ordinary or partitioned table keeps row versions; a view doesn't.
+ if kind is None or str(kind[0]) not in ("r", "p"):
+ raise ValueError("frame.row_versions.table is not a table")
+ except Exception:
+ try:
+ conn.close()
+ except Exception: # noqa: BLE001
+ pass
+ raise
+ return HeldRead(conn, time.monotonic())
+
+
+def hold(token: str, held: HeldRead) -> None:
+ now = time.monotonic()
+ with _LOCK:
+ for key in [k for k, h in _HELD.items() if now - h.opened > MAX_HOLD_S]:
+ _HELD.pop(key).close()
+ old = _HELD.pop(token, None)
+ _HELD[token] = held
+ if old is not None:
+ old.close()
+
+
+def take(token: str) -> Optional[HeldRead]:
+ with _LOCK:
+ return _HELD.pop(token, None)
+
+
+#: PostgreSQL's error for a number past every multixact made (multixact.c):
+#: only this means the old ``xmax`` is a plain transaction id. "does no
+#: longer exist" is also raised for an expired multixact, whose members are
+#: gone (fail-open class: absent-evidence-as-success), so it is not checked.
+_NO_SUCH_MULTIXACT = re.compile(r"MultiXactId \d+ has not been created yet")
+#: ``pg_get_multixact_members`` modes that update a row (not just lock it).
+_UPDATE_MODES = frozenset({"nokeyupd", "upd"})
+
+
+def _multixact_updater_other_than(cur: Any, value: str, writer: str) -> bool:
+ """Could ``value``, read as the old version's ``xmax``, be a multixact id
+ (a shared lock) whose updater is a transaction other than ``writer``?
+ Then two writers could read as one. A value past every multixact made
+ (the function's "has not been created yet" error) can't. Any other error,
+ an expired multixact's "does no longer exist" among them, is raised, so
+ the target is not checked."""
+
+ try:
+ cur.execute(
+ "SELECT CAST(xid AS TEXT), mode FROM pg_get_multixact_members(CAST(%s AS xid))",
+ (value,),
+ )
+ members = cur.fetchall()
+ except Exception as exc: # noqa: BLE001 - only "no such multixact" is a plain xid
+ if not _NO_SUCH_MULTIXACT.search(str(exc)):
+ raise # any other failure: the judge leaves the target not checked
+ return False
+ return any(str(m) in _UPDATE_MODES and str(x) != writer for x, m in members)
+
+
+def judge_row_versions(
+ spec: FrameRowVersions,
+ held: Optional[HeldRead],
+ connect: Callable[[], Any],
+ targets: Sequence[tuple[Optional[str], bool, bool]],
+) -> VersionVerdict:
+ """Count the writers of every target that existed. ``targets``: per
+ record a confirmed write effect matched, its key (None when it has
+ none), whether it existed before the write, and whether it changed."""
+
+ if held is None:
+ return VersionVerdict(
+ "not_checked",
+ "unreadable",
+ reason="the row versions held from the baseline are not open in "
+ "this process, so who saved the target can't be told",
+ )
+ try:
+ keys = sorted({t for t, existed, _c in targets if existed and t is not None})
+ old = held.rows(spec, keys) if keys else {}
+ conn = connect()
+ try:
+ conn.autocommit = True
+ cur = conn.cursor()
+ cur.execute(_query(spec), (keys,))
+ now = _unique_rows(cur.fetchall())
+ ambiguous = {
+ k
+ for k, (base_xmin, base_xmax) in old.items()
+ if k in now
+ and now[k][0] != base_xmin
+ and base_xmax == now[k][0]
+ and _multixact_updater_other_than(cur, base_xmax, now[k][0])
+ }
+ finally:
+ conn.close()
+ except DuplicateKey:
+ return VersionVerdict(
+ "not_checked",
+ "unreadable",
+ reason="frame.row_versions.key_column names more than one row "
+ "for a target, so the target's own versions can't be told",
+ )
+ except Exception: # noqa: BLE001 - unreadable -> the check stops the run
+ return VersionVerdict(
+ "not_checked",
+ "unreadable",
+ reason="the target's row versions could not be read",
+ )
+ finally:
+ held.close()
+ out = VersionVerdict("held")
+ worst: Optional[VersionVerdict] = None
+
+ def stop(status: str, problem: str, reason: str) -> None:
+ nonlocal worst
+ if worst is None or (worst.status == "not_checked" and status == "refuted"):
+ worst = VersionVerdict(status, problem, reason=reason) # type: ignore[arg-type]
+
+ seen: set[Optional[str]] = set()
+ for target, existed, changed in targets:
+ if target in seen:
+ continue
+ seen.add(target)
+ if not existed:
+ # An update or a found check names a record that was there. One
+ # created in the window (a duplicate made instead of the update)
+ # has no earlier version, so this source can't vouch for it.
+ stop(
+ "not_checked",
+ "created_target",
+ "the record an update or found check names was created in the "
+ "window, not saved over",
+ )
+ continue
+ if target is None:
+ stop(
+ "not_checked",
+ "no_target_id",
+ "a target record has no key field, so its row can't be found",
+ )
+ continue
+ out.targets += 1
+ base, cur = old.get(target), now.get(target)
+ if base is None or cur is None:
+ stop(
+ "not_checked",
+ "missing",
+ "the target existed but its row isn't in the table "
+ "frame.row_versions names, before or after the write",
+ )
+ continue
+ (base_xmin, base_xmax), (cur_xmin, _cur_xmax) = base, cur
+ if target in ambiguous:
+ stop(
+ "not_checked",
+ "ambiguous_xmax",
+ "the version the baseline saw was replaced under a shared lock, "
+ "so one save can't be told from two",
+ )
+ continue
+ if cur_xmin == base_xmin:
+ writers = 0
+ elif base_xmax not in (None, "0") and base_xmax == cur_xmin:
+ writers = 1
+ else:
+ writers = 2
+ out.new_versions += min(writers, 2)
+ if writers >= 2:
+ stop(
+ "refuted",
+ "extra_steps",
+ "lost update: two or more transactions wrote the target inside "
+ "the window; one save is the agent's, and nothing says whose "
+ "the others are",
+ )
+ elif changed and writers == 0:
+ stop(
+ "not_checked",
+ "no_new_version",
+ "the target changed in the window but its row version didn't, "
+ "so who saved it can't be told",
+ )
+ if worst is not None:
+ worst.targets, worst.new_versions = out.targets, out.new_versions
+ return worst
+ out.reason = f"{out.targets} target(s): at most one save each in the window"
+ return out
+
+
+def baseline_detail(held: Optional[HeldRead], error: Optional[str]) -> dict[str, Any]:
+ return {"held": held is not None, "error": error}
+
+
+def stored_held(detail: Optional[Mapping[str, Any]]) -> bool:
+ return isinstance(detail, Mapping) and detail.get("held") is True
diff --git a/packages/flow/openadapt_flow/runtime/effects/versions.py b/packages/flow/openadapt_flow/runtime/effects/versions.py
index 3f10ca3026..7df84f17fb 100644
--- a/packages/flow/openadapt_flow/runtime/effects/versions.py
+++ b/packages/flow/openadapt_flow/runtime/effects/versions.py
@@ -59,6 +59,9 @@
"no_new_version",
"history_changed",
"unknown_surface",
+ "ambiguous_xmax",
+ "created_target",
+ "unbound_source",
)
_WHOLE = re.compile(r"^(0|[1-9][0-9]*)$")
diff --git a/packages/flow/openadapt_flow/verifier.py b/packages/flow/openadapt_flow/verifier.py
index 16e35ac5c5..d7b368bbbf 100644
--- a/packages/flow/openadapt_flow/verifier.py
+++ b/packages/flow/openadapt_flow/verifier.py
@@ -2418,6 +2418,10 @@ def _scope(
"no_new_version": "the target changed in the window but no new version of it was read",
"history_changed": "a version of the target read before the write is gone after it, "
"so a save in the window could be hidden",
+ "ambiguous_xmax": "the target's row was replaced under a shared lock, so one "
+ "save can't be told from two",
+ "created_target": "the record an update or found check names was created in "
+ "the window, not saved over",
}
diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py
index cabfb87834..5fdf26d527 100644
--- a/packages/flow/openadapt_flow/verify_run.py
+++ b/packages/flow/openadapt_flow/verify_run.py
@@ -660,7 +660,72 @@ def _judge_versions(
spec = cfg.frame.versions if cfg.frame is not None else None
if spec is None:
return frame
- field_name = spec.target_field or cfg.frame.identity_field or "id" # type: ignore[union-attr]
+ targets = _version_targets(
+ cfg, before, effects, verdicts, spec.target_field, spec.target_surface
+ )
+ stored = (before.detail or {}).get(FRAME_VERSIONS_DETAIL)
+ if spec.target_surface is not None and not _surface_has_target(
+ effects, spec.target_surface
+ ):
+ # A surface no write target is read from (a typo in a hand-written
+ # contract, or a surface only a guard reads) would leave no target,
+ # and no target holds.
+ result = VersionVerdict(
+ "not_checked",
+ "unknown_surface",
+ reason="frame.versions.target_surface names a surface no write "
+ "target is read from, so no target's versions can be judged",
+ )
+ else:
+ result = judge_versions(
+ spec,
+ stored if isinstance(stored, Mapping) else {},
+ _read_versions(cfg, params),
+ targets,
+ _mac_key(salt),
+ params,
+ )
+ frame.versions = result
+ return _apply_version_result(frame, result)
+
+
+def _apply_version_result(frame: FrameVerdict, result: Any) -> FrameVerdict:
+ if result.status == "refuted":
+ frame.status = "refuted"
+ frame.reason = result.reason
+ elif result.status == "not_checked" and frame.status == "held":
+ frame.status = "not_checked"
+ frame.reason = result.reason
+ return frame
+
+
+def _writes_a_target(effect: Effect) -> bool:
+ """A write effect whose records can be targets. A guard ("nothing
+ here", ``record_written`` with ``expected_count`` 0) never is."""
+
+ if effect.kind not in (EffectKind.RECORD_WRITTEN, EffectKind.FIELD_EQUALS):
+ return False
+ return not (effect.kind is EffectKind.RECORD_WRITTEN and effect.expected_count == 0)
+
+
+def _surface_has_target(effects: Sequence[Effect], surface: str) -> bool:
+ from openadapt_flow.runtime.effects.surfaces import surface_of
+
+ return any(_writes_a_target(e) and surface_of(e) == surface for e in effects)
+
+
+def _version_targets(
+ cfg: VerifyConfig,
+ before: EffectState,
+ effects: Sequence[Effect],
+ verdicts: Sequence[EffectVerdict],
+ target_field: Optional[str],
+ target_surface: Optional[str],
+) -> list[tuple[Optional[str], bool, bool]]:
+ """Per record a confirmed write effect matched: its ``target_field``
+ value, whether it existed before the write, and whether it changed."""
+
+ field_name = target_field or cfg.frame.identity_field or "id" # type: ignore[union-attr]
# Whether a target existed is told by its identity, which a save doesn't
# change, never by the target field's value after the write: a target
# field the write changed would make an old record look created.
@@ -688,27 +753,14 @@ def before_rows(effect: Effect) -> Optional[dict[str, dict[str, Any]]]:
return index(rows) if isinstance(rows, list) else None
return index(before.records) if before.reachable else None
- def writes_a_target(effect: Effect) -> bool:
- """A write effect whose records can be targets. A guard ("nothing
- here", ``record_written`` with ``expected_count`` 0) never is."""
-
- if effect.kind not in (EffectKind.RECORD_WRITTEN, EffectKind.FIELD_EQUALS):
- return False
- return not (
- effect.kind is EffectKind.RECORD_WRITTEN and effect.expected_count == 0
- )
-
ignored = set(cfg.frame.ignore_fields) # type: ignore[union-attr]
targets: list[tuple[Optional[str], bool, bool]] = []
for effect, verdict in zip(effects, verdicts):
- if not writes_a_target(effect):
+ if not _writes_a_target(effect):
continue
if not verdict.confirmed:
continue
- if (
- spec.target_surface is not None
- and surface_of(effect) != spec.target_surface
- ):
+ if target_surface is not None and surface_of(effect) != target_surface:
continue # a row beside the target, not the target
old = before_rows(effect)
for record in verdict.matched_records:
@@ -726,36 +778,77 @@ def writes_a_target(effect: Effect) -> bool:
or any(record.get(k) != v for k, v in was.items() if k not in ignored)
)
targets.append((text, existed, changed))
- stored = (before.detail or {}).get(FRAME_VERSIONS_DETAIL)
- if spec.target_surface is not None and not any(
- writes_a_target(e) and surface_of(e) == spec.target_surface for e in effects
+ return targets
+
+
+def _hold_row_versions(cfg: VerifyConfig, execution_id: str) -> dict[str, Any]:
+ """Open ``frame.row_versions``' held read before the baseline records."""
+
+ from openadapt_flow.runtime.effects import row_versions as rv
+
+ spec = cfg.frame.row_versions # type: ignore[union-attr]
+ try:
+ read = cfg.frame.database.read # type: ignore[union-attr]
+ held = rv.open_held(spec, _db_connect(read)) # type: ignore[arg-type]
+ except Exception as exc: # noqa: BLE001 - not held -> the judge stops
+ return rv.baseline_detail(None, type(exc).__name__)
+ rv.hold(execution_id, held)
+ return rv.baseline_detail(held, None)
+
+
+def _judge_row_versions(
+ cfg: VerifyConfig,
+ frame: FrameVerdict,
+ before: EffectState,
+ effects: Sequence[Effect],
+ verdicts: Sequence[EffectVerdict],
+ execution_id: str,
+) -> FrameVerdict:
+ """Add ``frame.row_versions``: two writers of a target in the window
+ refute the frame; a read that can't count them leaves it not checked."""
+
+ from openadapt_flow.runtime.effects import row_versions as rv
+ from openadapt_flow.runtime.effects.versions import VersionVerdict
+
+ spec = cfg.frame.row_versions if cfg.frame is not None else None
+ if spec is None:
+ return frame
+ held = rv.take(execution_id)
+ if not rv.stored_held((before.detail or {}).get(rv.DETAIL)):
+ if held is not None:
+ held.close()
+ held = None
+ if spec.target_surface is not None and not _surface_has_target(
+ effects, spec.target_surface
):
- # A surface no write target is read from (a typo in a hand-written
- # contract, or a surface only a guard reads) would leave no target,
- # and no target holds.
+ if held is not None:
+ held.close()
result = VersionVerdict(
"not_checked",
"unknown_surface",
- reason="frame.versions.target_surface names a surface no write "
- "target is read from, so no target's versions can be judged",
+ reason="frame.row_versions.target_surface names a surface no "
+ "write target is read from",
)
- else:
- result = judge_versions(
+ elif (
+ unbound := rv.binding_problem(
spec,
- stored if isinstance(stored, Mapping) else {},
- _read_versions(cfg, params),
- targets,
- _mac_key(salt),
- params,
+ cfg.verifier.surfaces,
+ cfg.frame.database.read, # type: ignore[union-attr]
+ cfg.frame.identity_field, # type: ignore[union-attr]
)
- frame.versions = result
- if result.status == "refuted":
- frame.status = "refuted"
- frame.reason = result.reason
- elif result.status == "not_checked" and frame.status == "held":
- frame.status = "not_checked"
- frame.reason = result.reason
- return frame
+ ) is not None:
+ if held is not None:
+ held.close()
+ result = VersionVerdict("not_checked", "unbound_source", reason=unbound)
+ else:
+ targets = _version_targets(
+ cfg, before, effects, verdicts, spec.target_field, spec.target_surface
+ )
+ read = cfg.frame.database.read # type: ignore[union-attr]
+ result = rv.judge_row_versions(spec, held, _db_connect(read), targets)
+ if frame.versions is None or result.status != "held":
+ frame.versions = result
+ return _apply_version_result(frame, result)
def _db_connect(read: Mapping[str, Any]) -> Any:
@@ -2483,6 +2576,11 @@ def capture_baseline(
history_before, _history_rows = _read_history(cfg, params, _now(), salt)
except Exception as exc:
history_error = type(exc).__name__
+ row_versions_detail = (
+ _hold_row_versions(cfg, execution_id)
+ if cfg.frame is not None and cfg.frame.row_versions is not None
+ else None
+ )
# The versions first: a save between this read and the record read is
# then in the record baseline too, never hidden in the versions one.
versions_rows = (
@@ -2538,6 +2636,10 @@ def capture_baseline(
"reachable": entries is not None,
"ids": _audit_ids(entries or [], salt),
}
+ if row_versions_detail is not None:
+ from openadapt_flow.runtime.effects.row_versions import DETAIL as RV_DETAIL
+
+ detail[RV_DETAIL] = row_versions_detail
if cfg.frame is not None and cfg.frame.versions is not None:
from openadapt_flow.runtime.effects.versions import seal_versions
@@ -3276,6 +3378,9 @@ def verify_run(
frame = _judge_versions(
cfg, frame, before, bound_effects, verdicts, params, salt
)
+ frame = _judge_row_versions(
+ cfg, frame, before, bound_effects, verdicts, execution_id
+ )
else:
frame = FrameVerdict(
status="not_checked",
diff --git a/packages/flow/tests/test_row_versions.py b/packages/flow/tests/test_row_versions.py
new file mode 100644
index 0000000000..353b63e74b
--- /dev/null
+++ b/packages/flow/tests/test_row_versions.py
@@ -0,0 +1,637 @@
+"""Row versions held from the baseline (``frame.row_versions``).
+
+On PostgreSQL the verifier holds a read-only snapshot from the baseline and
+counts the transactions that wrote each target row in the window. These
+tests check that one save passes and that every lost update stops: another
+user's save then the agent's stale save (with and without a gap), two
+same-value rewrites, an edit and a revert against a found check, and a
+target whose held read is gone. They also check that the probe writes the
+version source beside an excuse only where it can derive one, and that a
+learned bookkeeping excuse no longer hides a lost update.
+
+The judge's arithmetic runs everywhere on recorded transaction ids; the
+round trips need ``OPENADAPT_SNAPSHOT_POSTGRES``. Records are made up.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Optional
+
+import pytest
+
+from openadapt_flow import learn_probe
+from openadapt_flow.runtime.effects import row_versions as rv
+from openadapt_flow.runtime.effects.frame import FrameSpec
+from openadapt_flow.verifier import Contract
+from tests import test_learned_excuses as _le
+from tests.test_learned_excuses import (
+ LOGIN,
+ SEEN,
+ Engine,
+ check,
+ learned_block,
+)
+
+_homes = _le._homes
+
+
+@pytest.fixture(autouse=True)
+def _no_leaked_holds() -> Any:
+ yield
+ assert not rv._HELD, "a held read was left open"
+
+
+@pytest.fixture
+def pg(request: pytest.FixtureRequest, tmp_path: Path) -> Any:
+ if not _le._PG:
+ pytest.skip("set OPENADAPT_SNAPSHOT_POSTGRES")
+ e = _le._postgres()
+ try:
+ for statement in e.ddl():
+ e.run(statement)
+ for table in ("app_user", "api_token", "note", "asset"):
+ e.run(
+ f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), "
+ f"(SELECT MAX(id) FROM {table}))"
+ )
+ yield e
+ finally:
+ for fn in e.cleanup:
+ fn()
+
+
+SPEC = {"table": "asset", "key_column": "id"}
+BOUND_READ = (
+ 'SELECT CAST(t."id" AS TEXT) AS "id", t."tag" AS "tag", t."name" AS "name", '
+ 't."assigned_to" AS "assigned_to", t."modified_at" AS "modified_at" '
+ 'FROM "asset" t'
+)
+_n = [0]
+
+
+def request_bookkeeping(e: Engine, user: str = _le.ACTOR) -> None:
+ """What the app changes on every request by ``user``: the moves a
+ read-only probe learns (no added row)."""
+
+ _n[0] += 1
+ e.run("UPDATE app_user SET last_login = %s WHERE id = %s", f"r{_n[0]}", int(user))
+ e.run(
+ "UPDATE api_token SET last_seen = %s WHERE user_id = %s", f"r{_n[0]}", int(user)
+ )
+
+
+def rename_contract(e: Engine, *, versions: bool = True, found: bool = False) -> dict:
+ """Rename asset LT-100 (an update), or check it is already named (a
+ found check), with the bookkeeping on the agent's own rows excused."""
+
+ doc = _le.asset_contract(e, learned_block(LOGIN, SEEN))
+ if versions:
+ # The held rows must be the ones the target surface reads the
+ # record from (rv.binding_problem): one SELECT over "asset" t.
+ doc["verifier"] = {
+ "kind": "surfaces",
+ "surfaces": {"record": _le._verifier(e, BOUND_READ)},
+ }
+ for effect in doc["effects"]:
+ effect["probe"] = "surface=record"
+ doc["frame"]["row_versions"] = {**SPEC, "target_surface": "record"}
+ if found:
+ doc["frame"]["target_fields"] = []
+ return doc
+
+
+def rename(e: Engine, name: str, user: str = _le.ACTOR) -> None:
+ request_bookkeeping(e, user)
+ e.run("UPDATE asset SET name = %s WHERE tag = 'LT-100'", name)
+
+
+def _outcome(result: Any) -> str:
+ return result.outcome.value
+
+
+# -- the judge's arithmetic, on recorded transaction ids ---------------------------
+
+
+class _Held:
+ def __init__(self, rows: dict[str, tuple]) -> None:
+ self._rows, self.closed = rows, False
+
+ def rows(self, spec: Any, keys: Any) -> dict[str, tuple]:
+ return {k: v for k, v in self._rows.items() if k in keys}
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _Cur:
+ def __init__(self, rows: list[tuple], members: Optional[list[tuple]]) -> None:
+ self._rows, self._members, self._sql = rows, members, ""
+
+ def execute(self, sql: str, *a: Any) -> None:
+ self._sql = sql
+ if "multixact" in sql and self._members is None:
+ raise RuntimeError(
+ "MultiXactId 105 has not been created yet -- apparent wraparound"
+ )
+
+ def fetchall(self) -> list[tuple]:
+ return list(self._members or []) if "multixact" in self._sql else self._rows
+
+
+class _Conn:
+ def __init__(
+ self, rows: list[tuple], members: Optional[list[tuple]] = None
+ ) -> None:
+ self._rows, self._members, self.autocommit = rows, members, False
+
+ def cursor(self) -> _Cur:
+ return _Cur(self._rows, self._members)
+
+ def rollback(self) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
+
+
+def _judge(
+ old: tuple,
+ now: tuple,
+ *,
+ changed: bool,
+ held: bool = True,
+ members: Optional[list[tuple]] = None,
+) -> rv.VersionVerdict:
+ spec = rv.FrameRowVersions(**SPEC)
+ h: Optional[_Held] = _Held({"1": old}) if held else None
+ result = rv.judge_row_versions(
+ spec, h, lambda: _Conn([("1", *now)], members), [("1", True, changed)]
+ )
+ if h is not None:
+ assert h.closed
+ return result
+
+
+def test_judge_counts_writers() -> None:
+ # Nobody wrote it: xmin unchanged.
+ assert _judge(("100", "0"), ("100", "0"), changed=False).status == "held"
+ # One transaction replaced the version the baseline saw.
+ assert _judge(("100", "105"), ("105", "0"), changed=True).status == "held"
+ # Two: the old version was replaced by 105, the current one is 107's.
+ two = _judge(("100", "105"), ("107", "0"), changed=True)
+ assert (two.status, two.problem) == ("refuted", "extra_steps")
+ # An edit and a revert leave the content unchanged, still two writers.
+ assert _judge(("100", "105"), ("107", "0"), changed=False).status == "refuted"
+ # Changed, yet the row version didn't move: can't say who saved it.
+ odd = _judge(("100", "0"), ("100", "0"), changed=True)
+ assert (odd.status, odd.problem) == ("not_checked", "no_new_version")
+ # A lock left on the old version (xmax) but no save: still nobody.
+ assert _judge(("100", "103"), ("100", "103"), changed=False).status == "held"
+
+
+def test_judge_never_reads_a_shared_lock_as_one_writer() -> None:
+ """The old version's xmax may be a multixact id equal to the current
+ xmin by chance; if that multixact names another updater, not checked."""
+
+ v = _judge(
+ ("100", "105"),
+ ("105", "0"),
+ changed=True,
+ members=[("103", "upd"), ("104", "keysh")],
+ )
+ assert (v.status, v.problem) == ("not_checked", "ambiguous_xmax")
+ # Lockers only, or the writer itself as the updater: still one writer.
+ assert (
+ _judge(
+ ("100", "105"), ("105", "0"), changed=True, members=[("104", "keysh")]
+ ).status
+ == "held"
+ )
+ assert (
+ _judge(
+ ("100", "105"), ("105", "0"), changed=True, members=[("105", "nokeyupd")]
+ ).status
+ == "held"
+ )
+
+
+def test_judge_stops_without_the_held_read() -> None:
+ v = _judge(("100", "0"), ("105", "0"), changed=True, held=False)
+ assert (v.status, v.problem) == ("not_checked", "unreadable")
+
+
+def test_judge_stops_on_a_missing_row() -> None:
+ spec = rv.FrameRowVersions(**SPEC)
+ v = rv.judge_row_versions(
+ spec, _Held({}), lambda: _Conn([("1", "5", "0")]), [("1", True, True)]
+ )
+ assert (v.status, v.problem) == ("not_checked", "missing")
+ # A record created in the window (a duplicate made instead of the
+ # update) has no earlier version: never held.
+ v = rv.judge_row_versions(spec, _Held({}), lambda: _Conn([]), [("9", False, False)])
+ assert (v.status, v.problem) == ("not_checked", "created_target")
+
+
+def test_spec_is_postgresql_only_and_plain_names() -> None:
+ db = {"dialect": "postgresql", "read": {"sql_driver": "psycopg2"}}
+ FrameSpec.model_validate({"database": db, "row_versions": SPEC})
+ with pytest.raises(ValueError, match="PostgreSQL only"):
+ FrameSpec.model_validate(
+ {
+ "database": {"dialect": "mysql", "read": {"sql_driver": "pymysql"}},
+ "row_versions": SPEC,
+ }
+ )
+ with pytest.raises(ValueError, match="PostgreSQL only"):
+ FrameSpec.model_validate({"row_versions": SPEC})
+ with pytest.raises(ValueError, match="plain"):
+ FrameSpec.model_validate(
+ {"database": db, "row_versions": {"table": 'asset"; DROP TABLE x; --'}}
+ )
+ # Unset, it is left out, so existing contracts keep their digests.
+ assert "row_versions" not in FrameSpec.model_validate({"database": db}).model_dump()
+
+
+# -- the probe writes the version source beside the excuse ------------------------
+
+
+def _generated(dialect: str, query: str, *, read_same: bool = True) -> dict:
+ read = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "db"}}
+ other = {"sql_driver": "psycopg2", "sql_connect_args": {"host": "elsewhere"}}
+ return {
+ "verifier": {
+ "kind": "surfaces",
+ "surfaces": {
+ "record": {
+ "kind": "sql",
+ **(read if read_same else other),
+ "sql_query": query,
+ }
+ },
+ },
+ "effects": [
+ {"kind": "record_written", "probe": "surface=record|x", "expected_count": 1}
+ ],
+ "frame": {"database": {"dialect": dialect, "read": read}},
+ }
+
+
+GENERATED = (
+ 'SELECT CAST(t."id" AS TEXT) AS "id", CAST(t."name" AS TEXT) AS "name", '
+ 'CASE WHEN CAST(t."minimum_stock" AS numeric) = CAST(%(v0)s AS numeric) '
+ "THEN '1' ELSE '0' END AS \"p__minimum_stock\" FROM \"part_part\" t"
+)
+
+
+def test_detects_the_row_versions_of_a_generated_read() -> None:
+ got = learn_probe.detect_row_versions(_generated("postgresql", GENERATED))
+ assert got == {
+ "source": "postgresql_xmin",
+ "table": "part_part",
+ "key_column": "id",
+ "target_surface": "record",
+ }
+
+
+@pytest.mark.parametrize(
+ "doc",
+ [
+ # MySQL and MariaDB: a marker can't count saves.
+ _generated("mysql", GENERATED),
+ # A read over another connection.
+ _generated("postgresql", GENERATED, read_same=False),
+ # A join or any shape the detector can't read: no source.
+ _generated(
+ "postgresql",
+ 'SELECT CAST(t."id" AS TEXT) AS "id" FROM "part_part" t JOIN x ON x.id = t.id',
+ ),
+ _generated("postgresql", 'SELECT CAST(t."pk" + 1 AS TEXT) AS "id" FROM "p" t'),
+ # A read that also counts child rows: those rows have versions of
+ # their own, which this source doesn't count.
+ _generated(
+ "postgresql",
+ 'SELECT CAST(t."id" AS TEXT) AS "id", CASE WHEN (SELECT COUNT(*) '
+ "FROM \"part_tag\" g WHERE g.part_id = t.id) = 1 THEN '1' ELSE "
+ '\'0\' END AS "p__tags" FROM "part_part" t',
+ ),
+ ],
+)
+def test_no_row_versions_where_none_can_be_derived(doc: dict) -> None:
+ assert learn_probe.detect_row_versions(doc) is None
+
+
+def test_probe_excuse_goes_in_only_with_a_version_source(tmp_path: Path) -> None:
+ proposal = {
+ "kinds": {"read_only_probe": {"excuses": [dict(LOGIN)]}},
+ "proposal_sha256": "sha256:" + "0" * 64,
+ }
+ pg_doc = _generated("postgresql", GENERATED)
+ my_doc = _generated("mysql", GENERATED)
+ import yaml
+
+ paths = []
+ for name, doc in (("pg", pg_doc), ("my", my_doc)):
+ doc["schema_version"] = "openadapt.verify/v1"
+ doc["effects"][0]["match"] = {"name": {"param": "name"}}
+ doc["verifier"]["surfaces"]["record"]["sql_password_env"] = "X"
+ doc["frame"]["database"]["read"]["sql_password_env"] = "X"
+ p = tmp_path / f"{name}.yaml"
+ p.write_text(yaml.safe_dump(doc))
+ paths.append(p)
+ written = learn_probe.apply(proposal, paths)
+ names = {p.stem for p, _n in written}
+ assert names == {"pg"}
+ pg_new = yaml.safe_load(paths[0].read_text())
+ assert pg_new["frame"]["row_versions"]["table"] == "part_part"
+ assert "learned" not in (yaml.safe_load(paths[1].read_text())["frame"] or {})
+ Contract.from_dict(pg_new, name="pg")
+
+
+# -- round trips on PostgreSQL ---------------------------------------------------
+
+
+def test_one_save_passes(pg: Engine, tmp_path: Path) -> None:
+ r = check(
+ pg,
+ rename_contract(pg),
+ {"tag": "LT-100", "name": "Laptop B"},
+ lambda: rename(pg, "Laptop B"),
+ tmp_path,
+ )
+ assert _outcome(r) == "CONFIRMED", r.reasons
+
+
+def test_bookkeeping_excuse_alone_hides_a_lost_update(
+ pg: Engine, tmp_path: Path
+) -> None:
+ """Why #2413 holds these contracts back: excused bookkeeping, no
+ version source, and a colleague's edit the stale save reverts."""
+
+ def act() -> None:
+ pg.run("UPDATE asset SET assigned_to = 3 WHERE tag = 'LT-100'")
+ rename(pg, "Laptop B")
+ pg.run("UPDATE asset SET assigned_to = NULL WHERE tag = 'LT-100'")
+
+ r = check(
+ pg,
+ rename_contract(pg, versions=False),
+ {"tag": "LT-100", "name": "Laptop B"},
+ act,
+ tmp_path,
+ )
+ assert _outcome(r) == "CONFIRMED", r.reasons
+
+
+@pytest.mark.parametrize("gap", [False, True])
+def test_lost_update_stops(pg: Engine, tmp_path: Path, gap: bool) -> None:
+ """A colleague's save, then the agent's stale full save over it."""
+
+ def act() -> None:
+ pg.run("UPDATE asset SET assigned_to = 3 WHERE tag = 'LT-100'")
+ if gap:
+ import time
+
+ time.sleep(1.0)
+ request_bookkeeping(pg)
+ pg.run(
+ "UPDATE asset SET name = 'Laptop B', assigned_to = NULL WHERE tag = 'LT-100'"
+ )
+
+ r = check(
+ pg,
+ rename_contract(pg),
+ {"tag": "LT-100", "name": "Laptop B"},
+ act,
+ tmp_path,
+ )
+ assert _outcome(r) == "REFUTED", r.reasons
+ assert r.evidence["frame"]["versions"]["problem"] == "extra_steps"
+
+
+def test_duplicate_instead_of_update_stops(pg: Engine, tmp_path: Path) -> None:
+ """The agent adds a second record with the asked values instead of
+ saving the existing one; the effect matches the new record."""
+
+ def act() -> None:
+ request_bookkeeping(pg)
+ pg.run("INSERT INTO asset (tag, name) VALUES ('LT-100', 'Laptop B')")
+
+ doc = rename_contract(pg)
+ doc["frame"]["target_fields"] = ["name", "tag"]
+ r = check(pg, doc, {"tag": "LT-100", "name": "Laptop B"}, act, tmp_path)
+ assert _outcome(r) != "CONFIRMED", r.reasons
+
+
+def test_same_value_rewrite_twice_stops(pg: Engine, tmp_path: Path) -> None:
+ def act() -> None:
+ rename(pg, "Laptop B")
+ pg.run("UPDATE asset SET name = 'Laptop B' WHERE tag = 'LT-100'")
+
+ r = check(
+ pg,
+ rename_contract(pg),
+ {"tag": "LT-100", "name": "Laptop B"},
+ act,
+ tmp_path,
+ )
+ assert _outcome(r) == "REFUTED", r.reasons
+
+
+def test_found_check(pg: Engine, tmp_path: Path) -> None:
+ params = {"tag": "LT-100", "name": "Laptop A"}
+ ok = check(
+ pg,
+ rename_contract(pg, found=True),
+ params,
+ lambda: request_bookkeeping(pg),
+ tmp_path,
+ )
+ assert _outcome(ok) == "CONFIRMED", ok.reasons
+
+ def edit_and_revert() -> None:
+ # A colleague edits the record; the agent's stale save puts it back.
+ pg.run("UPDATE asset SET assigned_to = 3 WHERE tag = 'LT-100'")
+ request_bookkeeping(pg)
+ pg.run("UPDATE asset SET assigned_to = NULL WHERE tag = 'LT-100'")
+
+ bad = check(pg, rename_contract(pg, found=True), params, edit_and_revert, tmp_path)
+ assert _outcome(bad) == "REFUTED", bad.reasons
+
+
+def test_judge_without_the_held_read_stops(
+ pg: Engine, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A judge in another process finds no held read: never a pass."""
+
+ real_take = rv.take
+
+ def gone(token: str) -> None:
+ held = real_take(token) # the other process never had it
+ if held is not None:
+ held.close()
+ return None
+
+ monkeypatch.setattr(rv, "take", gone)
+ r = check(
+ pg,
+ rename_contract(pg),
+ {"tag": "LT-100", "name": "Laptop B"},
+ lambda: rename(pg, "Laptop B"),
+ tmp_path,
+ )
+ assert _outcome(r) != "CONFIRMED"
+ assert r.evidence["frame"]["versions"]["problem"] == "unreadable"
+
+
+def test_held_read_is_a_read_only_snapshot(pg: Engine) -> None:
+ from openadapt_flow.verify_run import _db_connect
+
+ held = rv.open_held(rv.FrameRowVersions(**SPEC), _db_connect(pg.read))
+ try:
+ cur = held.conn.cursor()
+ with pytest.raises(Exception, match="read-only"):
+ cur.execute("UPDATE asset SET name = 'x'")
+ finally:
+ held.close()
+ with pytest.raises(Exception):
+ rv.open_held(rv.FrameRowVersions(table="no_such_table"), _db_connect(pg.read))
+
+
+# -- review blockers: binding, multixact errors, one-table reads --------------
+
+
+class _FailingCur(_Cur):
+ def execute(self, sql: str, *a: Any) -> None:
+ self._sql = sql
+ if "multixact" in sql:
+ raise RuntimeError(
+ "permission denied for function pg_get_multixact_members"
+ )
+
+
+def test_any_other_multixact_error_is_not_checked() -> None:
+ """Only "no such multixact" means a plain xid; any other failure (a
+ permission error, a dropped connection) can't rule out two writers."""
+
+ class Conn(_Conn):
+ def cursor(self) -> _Cur:
+ return _FailingCur(self._rows, self._members)
+
+ spec = rv.FrameRowVersions(**SPEC)
+ v = rv.judge_row_versions(
+ spec,
+ _Held({"1": ("100", "105")}),
+ lambda: Conn([("1", "105", "0")]),
+ [("1", True, True)],
+ )
+ assert v.status == "not_checked"
+
+
+@pytest.mark.parametrize(
+ "query",
+ [
+ 'SELECT 1 AS "x" UNION SELECT CAST(t."id" AS TEXT) AS "id", t."n" AS "n" '
+ 'FROM "part_part" t',
+ 'WITH d AS (SELECT 1) SELECT CAST(t."id" AS TEXT) AS "id", t."n" AS "n" '
+ 'FROM "part_part" t',
+ 'SELECT CAST(t."id" AS TEXT) AS "id", t."n" AS "n" FROM "part_part" t; '
+ 'SELECT 1 FROM "part_part" t',
+ 'SELECT CAST(t."id" AS TEXT) AS "id", (SELECT 1) AS "n" FROM "part_part" t',
+ ],
+)
+def test_a_read_that_is_not_one_select_over_one_table_has_no_source(
+ query: str,
+) -> None:
+ assert rv.single_table_read(query, "id") is None
+ assert learn_probe.detect_row_versions(_generated("postgresql", query)) is None
+
+
+def _bound(spec: dict, query: str = GENERATED) -> Optional[str]:
+ doc = _generated("postgresql", query)
+ return rv.binding_problem(
+ rv.FrameRowVersions(**spec),
+ doc["verifier"]["surfaces"],
+ doc["frame"]["database"]["read"],
+ "id",
+ )
+
+
+def test_row_versions_must_be_the_target_surfaces_own_table() -> None:
+ """A decoy table with the same key (one nobody edits) would vouch for a
+ target it never held: an edit and a revert would pass."""
+
+ good = {"table": "part_part", "key_column": "id", "target_surface": "record"}
+ assert _bound(good) is None
+ assert _bound({**good, "table": "decoy"}) is not None
+ assert _bound({**good, "key_column": "other_id"}) is not None
+ assert _bound({**good, "target_surface": "elsewhere"}) is not None
+ assert _bound({"table": "part_part", "key_column": "id"}) is not None
+ joined = GENERATED.replace('FROM "part_part" t', 'FROM "part_part" t JOIN x ON 1=1')
+ assert _bound(good, query=joined) is not None
+
+
+@pytest.mark.parametrize(
+ "item",
+ [
+ 'CAST(t."id" + 0 AS TEXT) AS "id"',
+ 'COALESCE(NULL, t."id") AS "id"',
+ 'lower(t."code") || t."id" AS "id"',
+ ],
+)
+def test_a_computed_identity_is_not_the_key_column(item: str) -> None:
+ """The returned identity must be the column itself (or its text cast),
+ not an expression that ends with it."""
+
+ query = f'SELECT {item}, t."n" AS "n" FROM "part_part" t'
+ assert rv.single_table_read(query, "id") is None
+
+
+def test_a_direct_or_cast_identity_is_the_key_column() -> None:
+ for item in ('CAST(t."id" AS TEXT) AS "id"', 't."id" AS "id"'):
+ query = f'SELECT t."n" AS "n", {item} FROM "part_part" t'
+ assert rv.single_table_read(query, "id") == ("part_part", "id")
+
+
+def test_a_key_naming_two_rows_is_not_checked() -> None:
+ spec = rv.FrameRowVersions(**SPEC)
+ two_now = rv.judge_row_versions(
+ spec,
+ _Held({"1": ("100", "105")}),
+ lambda: _Conn([("1", "105", "0"), ("1", "107", "0")]),
+ [("1", True, True)],
+ )
+ assert two_now.status == "not_checked"
+ assert "more than one row" in two_now.reason
+
+ class TwoHeld(_Held):
+ def rows(self, spec: Any, keys: Any) -> dict[str, tuple]:
+ return rv._unique_rows([("1", "100", "105"), ("1", "101", "0")])
+
+ two_before = rv.judge_row_versions(
+ spec, TwoHeld({}), lambda: _Conn([("1", "105", "0")]), [("1", True, True)]
+ )
+ assert two_before.status == "not_checked"
+
+
+def test_an_expired_multixact_is_not_checked() -> None:
+ """PostgreSQL says "does no longer exist" for a multixact older than its
+ retained range too; its members are gone, so one writer can't be told."""
+
+ class ExpiredCur(_Cur):
+ def execute(self, sql: str, *a: Any) -> None:
+ self._sql = sql
+ if "multixact" in sql:
+ raise RuntimeError("MultiXactId 105 does no longer exist -- wraparound")
+
+ class Conn(_Conn):
+ def cursor(self) -> _Cur:
+ return ExpiredCur(self._rows, self._members)
+
+ v = rv.judge_row_versions(
+ rv.FrameRowVersions(**SPEC),
+ _Held({"1": ("100", "105")}),
+ lambda: Conn([("1", "105", "0")]),
+ [("1", True, True)],
+ )
+ assert v.status == "not_checked"