From 48f4973bb617f97566f388d63001ae27e5e22fb5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 21:59:48 -0500 Subject: [PATCH 1/3] feat(transducer): shared work lease and bounded settle-and-reconcile Add openadapt/transducer_concurrency.py with two local runtime primitives for workers that share one queue of items: - SharedWorkLease: a claim lease keyed by (app, canonical item key) in a SQLite file in WAL mode. Claims run in one BEGIN IMMEDIATE transaction, so exactly one concurrent worker wins. PENDING claims carry a TTL renewed by heartbeat; COMMITTED is terminal (later workers skip); RELEASED can be claimed again. Each takeover bumps a fence number, and heartbeat, commit and release only succeed for the current fence, so a holder that resumes after its TTL passed cannot commit over the new holder. A claim marked uncertain is never taken over until it is resolved. - BoundedSettleAndReconcile: runs one submit, never repeats it on an uncertain outcome (dropped response, proxy timeout), marks the lease uncertain, then polls a read-back with bounded backoff. Returns COMMITTED when the record shows up, RETRY_SAFE only when nothing could have been saved, and COMPLETED_UNVERIFIED otherwise. Cooperates with FormCommitLatch through a new latch_now() method. Wiring: SimplexTransducer and openadapt.wrap accept work_lease=. An episode claims the task's work_item_key before its first commit is released, waits (guard WORK_LEASE_HELD) while another worker holds it, stops with WORK_ITEM_ALREADY_COMMITTED when it is done elsewhere, heartbeats each step and commits the lease when a commit is verified. Without work_lease, behavior is unchanged. Tests: tests/test_transducer_concurrency.py (26 tests), including an 8-process and a 16-thread race (one winner per item, zero duplicate saves), TTL takeover after a real process crash, fence rejection of a stale holder, and dropped-ack / async-save settle cases. --- openadapt/__init__.py | 18 + openadapt/simplex_transducer.py | 19 +- openadapt/transducer_concurrency.py | 952 +++++++++++++++++++++++++++ openadapt/transducer_fact_ledger.py | 20 + openadapt/wrap_sdk.py | 12 + tests/test_transducer_concurrency.py | 699 ++++++++++++++++++++ 6 files changed, 1718 insertions(+), 2 deletions(-) create mode 100644 openadapt/transducer_concurrency.py create mode 100644 tests/test_transducer_concurrency.py diff --git a/openadapt/__init__.py b/openadapt/__init__.py index c0d2142056..e9535a5aa9 100644 --- a/openadapt/__init__.py +++ b/openadapt/__init__.py @@ -192,6 +192,20 @@ def __getattr__(name: str): return locals()[name] + # Concurrent-worker lease and settle primitives (stdlib-only at import time) + if name in ( + "BoundedSettleAndReconcile", + "SettleOutcome", + "SharedWorkLease", + ): + from openadapt.transducer_concurrency import ( # noqa: F401 + BoundedSettleAndReconcile, + SettleOutcome, + SharedWorkLease, + ) + + return locals()[name] + # Demo library lives in openadapt-evals if name == "DemoLibrary": try: @@ -238,6 +252,10 @@ def __getattr__(name: str): "TransducerReceipt", "TrustLevel", "WriteAheadSagaLog", + # Concurrent-worker lease and settle primitives + "BoundedSettleAndReconcile", + "SettleOutcome", + "SharedWorkLease", # From kernel (canonical runtime) "CommitInterceptor", "ObligationLedger", diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index ebce351cfe..943798bcc7 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -27,6 +27,7 @@ from pathlib import Path from typing import Any, Literal, TypeVar +from openadapt.transducer_concurrency import SharedWorkLease, WorkLeaseHooks from openadapt.transducer_fact_ledger import ( FactLedgerHooks, FormCommitLatch, @@ -1766,6 +1767,7 @@ def __init__( sop_contract: Any = None, dual_egress: Any = None, compounding_handoff: Any = None, + work_lease: SharedWorkLease | None = None, ) -> None: if not callable(getattr(agent, "act", None)): raise TypeError( @@ -1817,6 +1819,8 @@ def __init__( self.finalize_episode = self._v3.finalize_episode self._facts = FactLedgerHooks(self) self.finalize_on_step_cap = self._facts.finalize_on_step_cap + self.work_lease = work_lease + self._lease = WorkLeaseHooks(self, work_lease) @property def last_receipt(self) -> TransducerReceipt | None: @@ -1860,6 +1864,7 @@ def reset( **kwargs: Any, ) -> None: """Reset episode state and respect ``isolation_mode`` on cartridge store.""" + self._lease.forget(run_id, task_id) with self._states_lock: if run_id is not None and task_id is not None: self._states.pop((run_id, task_id), None) @@ -3321,6 +3326,7 @@ def _mark_verified( state.next_commit_index = self.wal.resume_point( state.run_id, state.task_id ) + self._lease.on_verified(state) def _check_stream_disconnect( self, state: EpisodeState, observation: Any @@ -3354,9 +3360,14 @@ def _check_stream_disconnect( return None def _build_wait_action( - self, state: EpisodeState, observation: Any, reason: str + self, + state: EpisodeState, + observation: Any, + reason: str, + *, + guard: str = "STREAM_DISCONNECTED", ) -> Any: - meta = {"guard": "STREAM_DISCONNECTED", "reason": reason} + meta = {"guard": guard, "reason": reason} with state._lock: action_cls = state.action_cls if action_cls is not None: @@ -3643,6 +3654,7 @@ def _act_supervised( self._v3.on_context(state, observation, task) self._v3.observe_saved(state, observation, task) self._facts.on_observation(state, observation) + self._lease.on_step(state) # Native BenchmarkObservation surface guard: stream/VDI disconnect. # Hold commits and return a wait action directly without burning an LLM call. @@ -3875,6 +3887,9 @@ def _route_action_inner( fast_forward_obs=observation, ) return self._reenter(state, observation, task, history) + leased = self._lease.gate(state, action, observation, task) + if leased is not action: + return leased self._v3.note_commit(state, action) fp = _commit_fingerprint(action, observation=observation) safe_summary = { diff --git a/openadapt/transducer_concurrency.py b/openadapt/transducer_concurrency.py new file mode 100644 index 0000000000..827d5e0397 --- /dev/null +++ b/openadapt/transducer_concurrency.py @@ -0,0 +1,952 @@ +"""Shared work lease and bounded settle-and-reconcile for concurrent workers. + +* ``SharedWorkLease`` lets several local workers (threads or processes) share + one queue of work items without doing an item twice. A worker claims an item + by ``(app, item_key)`` in a SQLite file opened in WAL mode. The claim runs in + one ``BEGIN IMMEDIATE`` transaction, so exactly one worker wins. A claim is + ``PENDING`` with a time-to-live that the holder renews by heartbeat. It ends + ``COMMITTED`` (terminal: later workers skip the item) or ``RELEASED`` (anyone + may claim it again). A holder that crashes stops renewing, and once its TTL + passes another worker takes the item over. Every takeover bumps a fence + number, and heartbeat, commit and release only succeed for the current + fence, so a holder that wakes up after a takeover cannot commit. +* ``BoundedSettleAndReconcile`` runs one submit when its response may be lost + (a dropped HTTP response, a proxy timeout) or the app saves in a background + job. It never re-submits on an uncertain outcome. It marks the lease as + uncertain, waits with bounded backoff and reopens the record the way a person + would (``read_back``) until the record shows up or the budget runs out. The + result is ``COMMITTED``, ``RETRY_SAFE`` (only when nothing could have been + saved) or ``COMPLETED_UNVERIFIED``. +* ``WorkLeaseHooks`` connects a lease to one ``SimplexTransducer``: an episode + claims its work item before its first commit is released, renews the claim + every step and marks it committed once a commit is verified. + +Nothing here names an application. Apps and item keys are whatever the caller +or the task carries. +""" + +from __future__ import annotations + +import enum +import os +import sqlite3 +import threading +import time +import unicodedata +import uuid +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # pragma: no cover + from openadapt.simplex_transducer import EpisodeState, SimplexTransducer + from openadapt.transducer_fact_ledger import FormCommitLatch + +__all__ = [ + "BoundedSettleAndReconcile", + "ClaimDecision", + "LeaseClaim", + "LeaseRecord", + "LeaseState", + "ReadBack", + "SettleOutcome", + "SettleResult", + "SharedWorkLease", + "SubmitStatus", + "WorkLeaseHooks", + "canonical_item_key", + "work_item_for", +] + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS work_lease ( + app TEXT NOT NULL, + item_key TEXT NOT NULL, + holder TEXT NOT NULL, + fence INTEGER NOT NULL, + state TEXT NOT NULL, + uncertain INTEGER NOT NULL DEFAULT 0, + claimed_at REAL NOT NULL, + expires_at REAL NOT NULL, + committed_at REAL, + note TEXT NOT NULL DEFAULT '', + PRIMARY KEY (app, item_key) +) +""" +_COLUMNS = ( + "app, item_key, holder, fence, state, uncertain, claimed_at, expires_at, " + "committed_at, note" +) + + +def canonical_item_key(*parts: Any) -> str: + """One stable key for a work item, whatever spacing or case the source used. + + Each part is NFKC-normalized, case-folded and has its runs of whitespace + collapsed; empty parts are dropped. Parts are joined with ``|``. + """ + out: list[str] = [] + for part in parts: + if part is None: + continue + text = unicodedata.normalize("NFKC", str(part)).casefold() + text = " ".join(text.split()) + if text: + out.append(text) + return "|".join(out) + + +class LeaseState(str, enum.Enum): + """State of one work item in the lease file.""" + + PENDING = "PENDING" + COMMITTED = "COMMITTED" + RELEASED = "RELEASED" + + +class ClaimDecision(str, enum.Enum): + """What ``SharedWorkLease.claim`` decided.""" + + GRANTED = "GRANTED" + """No live claim existed; the caller now holds the item.""" + TAKEOVER = "TAKEOVER" + """The previous holder's TTL passed; the caller now holds the item.""" + WAIT = "WAIT" + """Another live claim holds the item; try again later.""" + SKIP_COMMITTED = "SKIP_COMMITTED" + """The item was already committed; do not do it again.""" + HELD_UNCERTAIN = "HELD_UNCERTAIN" + """A submit for the item has an unknown outcome. Nobody may take it over + until it is reconciled, because a second submit could duplicate it.""" + + +@dataclass(frozen=True) +class LeaseRecord: + """One row of the lease file.""" + + app: str + item_key: str + holder: str + fence: int + state: LeaseState + uncertain: bool + claimed_at: float + expires_at: float + committed_at: float | None + note: str + + @classmethod + def from_row(cls, row: tuple[Any, ...]) -> LeaseRecord: + return cls( + app=str(row[0]), + item_key=str(row[1]), + holder=str(row[2]), + fence=int(row[3]), + state=LeaseState(row[4]), + uncertain=bool(row[5]), + claimed_at=float(row[6]), + expires_at=float(row[7]), + committed_at=None if row[8] is None else float(row[8]), + note=str(row[9] or ""), + ) + + +@dataclass(frozen=True) +class LeaseClaim: + """The answer to one claim attempt. + + ``holder`` and ``fence`` identify the claim when ``granted``. Otherwise + ``record`` is the row that blocked it. + """ + + app: str + item_key: str + holder: str + decision: ClaimDecision + fence: int = 0 + expires_at: float = 0.0 + previous_holder: str = "" + record: LeaseRecord | None = None + + @property + def granted(self) -> bool: + return self.decision in (ClaimDecision.GRANTED, ClaimDecision.TAKEOVER) + + +class SharedWorkLease: + """Keyed claim lease over a local SQLite file in WAL mode. + + One instance is one worker (``worker_id``). Each call opens its own + connection, so an instance may be used from several threads, and several + processes may open the same file. ``clock`` must be a wall clock shared by + all workers (``time.time`` by default), since expiry times are compared + across processes. + """ + + def __init__( + self, + path: str | Path, + *, + worker_id: str | None = None, + ttl_s: float = 60.0, + clock: Callable[[], float] = time.time, + busy_timeout_s: float = 30.0, + ) -> None: + if ttl_s <= 0: + raise ValueError("ttl_s must be positive") + self.path = Path(path).expanduser() + self.worker_id = worker_id or f"{os.getpid()}-{uuid.uuid4().hex[:12]}" + self.ttl_s = float(ttl_s) + self.clock = clock + self.busy_timeout_s = float(busy_timeout_s) + self.path.parent.mkdir(parents=True, exist_ok=True) + con = self._connect() + try: + con.execute("PRAGMA journal_mode=WAL") + con.execute(_SCHEMA) + finally: + con.close() + + def _connect(self) -> sqlite3.Connection: + con = sqlite3.connect( + str(self.path), timeout=self.busy_timeout_s, isolation_level=None + ) + con.execute(f"PRAGMA busy_timeout={int(self.busy_timeout_s * 1000)}") + con.execute("PRAGMA synchronous=FULL") + return con + + @contextmanager + def _write(self) -> Iterator[sqlite3.Connection]: + """One write transaction that holds the database write lock throughout.""" + con = self._connect() + try: + con.execute("BEGIN IMMEDIATE") + try: + yield con + except BaseException: + con.execute("ROLLBACK") + raise + con.execute("COMMIT") + finally: + con.close() + + @staticmethod + def _select(con: sqlite3.Connection, app: str, item_key: str) -> LeaseRecord | None: + row = con.execute( + f"SELECT {_COLUMNS} FROM work_lease WHERE app=? AND item_key=?", + (app, item_key), + ).fetchone() + return None if row is None else LeaseRecord.from_row(row) + + # -- claims ----------------------------------------------------------- + def claim( + self, app: str, item_key: str, *, ttl_s: float | None = None + ) -> LeaseClaim: + """Try to take the item. Exactly one concurrent caller is granted it.""" + ttl = self.ttl_s if ttl_s is None else float(ttl_s) + with self._write() as con: + now = self.clock() + rec = self._select(con, app, item_key) + if rec is not None and rec.state is LeaseState.COMMITTED: + return LeaseClaim( + app, + item_key, + self.worker_id, + ClaimDecision.SKIP_COMMITTED, + record=rec, + ) + if rec is not None and rec.state is LeaseState.PENDING: + if rec.uncertain: + return LeaseClaim( + app, + item_key, + self.worker_id, + ClaimDecision.HELD_UNCERTAIN, + record=rec, + ) + if rec.expires_at > now: + return LeaseClaim( + app, + item_key, + self.worker_id, + ClaimDecision.WAIT, + record=rec, + ) + expires = now + ttl + if rec is None: + con.execute( + f"INSERT INTO work_lease ({_COLUMNS}) " + "VALUES (?, ?, ?, 1, ?, 0, ?, ?, NULL, '')", + ( + app, + item_key, + self.worker_id, + LeaseState.PENDING.value, + now, + expires, + ), + ) + return LeaseClaim( + app, + item_key, + self.worker_id, + ClaimDecision.GRANTED, + fence=1, + expires_at=expires, + ) + fence = rec.fence + 1 + con.execute( + "UPDATE work_lease SET holder=?, fence=?, state=?, uncertain=0, " + "claimed_at=?, expires_at=?, committed_at=NULL, note='' " + "WHERE app=? AND item_key=?", + ( + self.worker_id, + fence, + LeaseState.PENDING.value, + now, + expires, + app, + item_key, + ), + ) + decision = ( + ClaimDecision.TAKEOVER + if rec.state is LeaseState.PENDING + else ClaimDecision.GRANTED + ) + return LeaseClaim( + app, + item_key, + self.worker_id, + decision, + fence=fence, + expires_at=expires, + previous_holder=rec.holder, + ) + + def _update_held( + self, + claim: LeaseClaim, + assignments: str, + params: tuple[Any, ...], + *, + extra_where: str = "", + ) -> bool: + if not claim.granted: + return False + with self._write() as con: + cur = con.execute( + f"UPDATE work_lease SET {assignments} " + "WHERE app=? AND item_key=? AND holder=? AND fence=? AND state=?" + f"{extra_where}", + ( + *params, + claim.app, + claim.item_key, + claim.holder, + claim.fence, + LeaseState.PENDING.value, + ), + ) + return cur.rowcount == 1 + + def heartbeat(self, claim: LeaseClaim, *, ttl_s: float | None = None) -> bool: + """Renew the claim. False when it was taken over or already ended.""" + ttl = self.ttl_s if ttl_s is None else float(ttl_s) + return self._update_held(claim, "expires_at=?", (self.clock() + ttl,)) + + def commit(self, claim: LeaseClaim, *, note: str = "") -> bool: + """Mark the item done. False when this claim no longer holds it.""" + return self._update_held( + claim, + "state=?, uncertain=0, committed_at=?, note=?", + (LeaseState.COMMITTED.value, self.clock(), note), + ) + + def release( + self, claim: LeaseClaim, *, note: str = "", even_if_uncertain: bool = False + ) -> bool: + """Give the item back unsaved. + + Refused while a submit is uncertain, unless the holder has since shown + that nothing was saved (``even_if_uncertain``). + """ + return self._update_held( + claim, + "state=?, uncertain=0, note=?", + (LeaseState.RELEASED.value, note), + extra_where="" if even_if_uncertain else " AND uncertain=0", + ) + + def mark_uncertain(self, claim: LeaseClaim, *, note: str = "") -> bool: + """Record that a submit was sent with an unknown outcome. + + Until ``commit`` or ``resolve``, nobody may take the item over, even + after the TTL passes. + """ + return self._update_held(claim, "uncertain=1, note=?", (note,)) + + def resolve( + self, app: str, item_key: str, *, committed: bool, note: str = "" + ) -> bool: + """Settle an item after a person checked it, whoever holds it. + + This is the operator override and is not fenced. Holders use + ``commit`` and ``release``, which are. + """ + state = LeaseState.COMMITTED if committed else LeaseState.RELEASED + with self._write() as con: + cur = con.execute( + "UPDATE work_lease SET state=?, uncertain=0, committed_at=?, note=? " + "WHERE app=? AND item_key=? AND state=?", + ( + state.value, + self.clock() if committed else None, + note, + app, + item_key, + LeaseState.PENDING.value, + ), + ) + return cur.rowcount == 1 + + # -- reads ------------------------------------------------------------ + def status(self, app: str, item_key: str) -> LeaseRecord | None: + con = self._connect() + try: + return self._select(con, app, item_key) + finally: + con.close() + + def records(self) -> list[LeaseRecord]: + con = self._connect() + try: + rows = con.execute( + f"SELECT {_COLUMNS} FROM work_lease ORDER BY app, item_key" + ).fetchall() + finally: + con.close() + return [LeaseRecord.from_row(r) for r in rows] + + def wait( + self, + app: str, + item_key: str, + *, + timeout_s: float, + poll_s: float = 0.5, + sleep: Callable[[float], None] = time.sleep, + ) -> LeaseRecord | None: + """Wait until the item is no longer held by a live claim, or time runs out. + + Returns the last row seen. A caller that gets ``COMMITTED`` skips the + item; one that gets ``RELEASED`` or an expired ``PENDING`` may claim it. + """ + deadline = self.clock() + max(0.0, timeout_s) + while True: + rec = self.status(app, item_key) + if ( + rec is None + or rec.state is not LeaseState.PENDING + or (not rec.uncertain and rec.expires_at <= self.clock()) + ): + return rec + if self.clock() >= deadline: + return rec + sleep(poll_s) + + @contextmanager + def keep_alive( + self, claim: LeaseClaim, *, interval_s: float | None = None + ) -> Iterator[threading.Event]: + """Renew *claim* from a background thread while the block runs. + + The yielded event is set if a heartbeat fails (the claim was lost). + """ + lost = threading.Event() + stop = threading.Event() + interval = self.ttl_s / 3 if interval_s is None else interval_s + + def _beat() -> None: + while not stop.wait(interval): + if not self.heartbeat(claim): + lost.set() + return + + thread = threading.Thread(target=_beat, name="work-lease-heartbeat") + thread.daemon = True + thread.start() + try: + yield lost + finally: + stop.set() + thread.join(timeout=max(1.0, interval * 2)) + + +# --------------------------------------------------------------------------- +# Bounded settle and reconcile +# --------------------------------------------------------------------------- + + +class ReadBack(str, enum.Enum): + """What reopening the record showed.""" + + PRESENT = "PRESENT" + """The saved record is visible.""" + ABSENT = "ABSENT" + """The place the record would be is visible and the record is not there.""" + UNKNOWN = "UNKNOWN" + """The check could not tell (page did not load, search errored).""" + + +class SubmitStatus(str, enum.Enum): + """What the submit call itself reported.""" + + ACKED = "ACKED" + UNCERTAIN = "UNCERTAIN" + NOT_SENT = "NOT_SENT" + + +class SettleOutcome(str, enum.Enum): + COMMITTED = "COMMITTED" + """The record was seen after this submit.""" + ALREADY_COMMITTED = "ALREADY_COMMITTED" + """The item was done before this call; nothing was submitted.""" + RETRY_SAFE = "RETRY_SAFE" + """Nothing could have been saved; the lease was released.""" + COMPLETED_UNVERIFIED = "COMPLETED_UNVERIFIED" + """A submit ran but the record never showed up within the budget. The item + stays held as uncertain so nobody submits it again without a check.""" + BLOCKED = "BLOCKED" + """A submit for this item is settling or unverified; no second submit.""" + WAIT = "WAIT" + """Another worker holds the item.""" + + +@dataclass(frozen=True) +class SettleResult: + outcome: SettleOutcome + reason: str + submits: int = 0 + submit_status: SubmitStatus | None = None + read_backs: tuple[ReadBack, ...] = () + delays: tuple[float, ...] = () + claim: LeaseClaim | None = None + lease_committed: bool = False + value: Any = None + + +_UNCERTAIN_ERRORS: tuple[type[BaseException], ...] = ( + TimeoutError, + ConnectionResetError, + ConnectionAbortedError, + BrokenPipeError, +) +_NOT_SENT_ERRORS: tuple[type[BaseException], ...] = (ConnectionRefusedError,) + + +@dataclass +class BoundedSettleAndReconcile: + """Submit once, then wait and reopen the record before deciding. + + ``read_back`` reopens the record the way a careful person would (search + the list, open the item) and returns a ``ReadBack`` or a bool (True means + present, False means absent). An exception counts as ``UNKNOWN``. + + ``submit`` may return a ``SubmitStatus``; any other value counts as + ``ACKED``. An exception in ``not_sent_errors`` means the request never left + (``NOT_SENT``). Any other exception counts as ``UNCERTAIN``: the request + may have reached the server. An uncertain submit is never repeated here. + + After a submit, ``read_back`` runs up to ``max_polls`` times. The waits + before each poll start at ``initial_delay_s`` and grow by ``backoff`` up + to ``max_delay_s``; polling stops early once ``budget_s`` would be passed. + + ``RETRY_SAFE`` after a submit needs both ``absent_is_final=True`` and every + poll returning ``ABSENT``. Set it only when the app's documented save delay + is shorter than the budget, or the submit carries an idempotency key the + app honors. Otherwise a slow background save would turn a retry into a + duplicate, so the result is ``COMPLETED_UNVERIFIED``. + """ + + read_back: Callable[[], ReadBack | bool | None] + max_polls: int = 4 + initial_delay_s: float = 1.0 + backoff: float = 2.0 + max_delay_s: float = 8.0 + budget_s: float = 30.0 + check_before_submit: bool = True + absent_is_final: bool = False + uncertain_errors: tuple[type[BaseException], ...] = _UNCERTAIN_ERRORS + not_sent_errors: tuple[type[BaseException], ...] = _NOT_SENT_ERRORS + sleep: Callable[[float], None] = time.sleep + clock: Callable[[], float] = time.monotonic + _lock: threading.RLock = field(default_factory=threading.RLock, repr=False) + _in_flight: set[tuple[str, str]] = field(default_factory=set, repr=False) + _unverified: dict[tuple[str, str], str] = field(default_factory=dict, repr=False) + + def __post_init__(self) -> None: + if self.max_polls < 1: + raise ValueError("max_polls must be at least 1") + if self.backoff < 1.0: + raise ValueError("backoff must be at least 1.0") + + def delays(self) -> list[float]: + """The planned wait before each poll, before the budget cuts it short.""" + out: list[float] = [] + delay = max(0.0, self.initial_delay_s) + for _ in range(self.max_polls): + out.append(min(delay, self.max_delay_s)) + delay *= self.backoff + return out + + def _read(self) -> ReadBack: + try: + value = self.read_back() + except Exception: + return ReadBack.UNKNOWN + if isinstance(value, ReadBack): + return value + if value is True: + return ReadBack.PRESENT + if value is False: + return ReadBack.ABSENT + return ReadBack.UNKNOWN + + def _classify(self, exc: BaseException) -> SubmitStatus: + if isinstance(exc, self.not_sent_errors): + return SubmitStatus.NOT_SENT + return SubmitStatus.UNCERTAIN + + def unverified(self) -> dict[tuple[str, str], str]: + """Items this instance left ``COMPLETED_UNVERIFIED``, with the reason.""" + with self._lock: + return dict(self._unverified) + + def clear(self, app: str, item_key: str) -> bool: + """Forget an unverified item once a person has checked it.""" + with self._lock: + return self._unverified.pop((app, item_key), None) is not None + + def run( + self, + submit: Callable[[], Any], + *, + app: str, + item_key: str, + lease: SharedWorkLease | None = None, + claim: LeaseClaim | None = None, + latch: FormCommitLatch | None = None, + control_key: str = "", + text: str = "", + step_index: int = 0, + commit_index: int = 0, + ) -> SettleResult: + """Submit the item at most once and decide what happened.""" + key = (app, item_key) + with self._lock: + if key in self._in_flight: + return SettleResult( + SettleOutcome.BLOCKED, "a submit for this item is still settling" + ) + if key in self._unverified: + return SettleResult( + SettleOutcome.BLOCKED, + "an earlier submit for this item is unverified: " + + self._unverified[key], + ) + self._in_flight.add(key) + try: + return self._run( + submit, + app=app, + item_key=item_key, + lease=lease, + claim=claim, + latch=latch, + control_key=control_key, + text=text, + step_index=step_index, + commit_index=commit_index, + ) + finally: + with self._lock: + self._in_flight.discard(key) + + def _run( + self, + submit: Callable[[], Any], + *, + app: str, + item_key: str, + lease: SharedWorkLease | None, + claim: LeaseClaim | None, + latch: FormCommitLatch | None, + control_key: str, + text: str, + step_index: int, + commit_index: int, + ) -> SettleResult: + if latch is not None and control_key: + hit = latch.match(control_key, text) + if hit is not None: + return SettleResult( + SettleOutcome.BLOCKED, + f"the same content was already submitted on this control " + f"(commit #{hit.commit_index})", + ) + if lease is not None and claim is None: + claim = lease.claim(app, item_key) + if claim is not None and not claim.granted: + if claim.decision is ClaimDecision.SKIP_COMMITTED: + return SettleResult( + SettleOutcome.ALREADY_COMMITTED, + "another worker already committed this item", + claim=claim, + ) + holder = claim.record.holder if claim.record is not None else "?" + return SettleResult( + SettleOutcome.WAIT, + f"item is held by {holder} ({claim.decision.value})", + claim=claim, + ) + + def _commit_lease() -> bool: + if lease is None or claim is None: + return False + return lease.commit(claim) + + def _latch() -> None: + if latch is not None and control_key: + latch.latch_now( + control_key, text, step_index=step_index, commit_index=commit_index + ) + + if self.check_before_submit: + before = self._read() + if before is ReadBack.PRESENT: + committed = _commit_lease() + _latch() + return SettleResult( + SettleOutcome.ALREADY_COMMITTED, + "the record was already there before submitting", + read_backs=(before,), + claim=claim, + lease_committed=committed, + ) + + value: Any = None + try: + value = submit() + except BaseException as exc: + if not isinstance(exc, Exception): + raise + status = self._classify(exc) + detail = f"{type(exc).__name__}: {exc}" + else: + status = value if isinstance(value, SubmitStatus) else SubmitStatus.ACKED + detail = status.value + + if status is SubmitStatus.NOT_SENT: + if lease is not None and claim is not None: + lease.release(claim, note=f"not sent: {detail}") + return SettleResult( + SettleOutcome.RETRY_SAFE, + f"the submit was not sent ({detail})", + submits=1, + submit_status=status, + claim=claim, + ) + + # Any sent submit may land, even an acknowledged one whose record is not + # visible yet. Hold the item as uncertain while settling so that, if this + # worker dies now, no other worker takes it over and submits again. + if lease is not None and claim is not None: + lease.mark_uncertain(claim, note=f"settling after {detail} submit") + + reads: list[ReadBack] = [] + waited: list[float] = [] + started = self.clock() + for delay in self.delays(): + if (self.clock() - started) + delay > self.budget_s: + break + if delay > 0: + self.sleep(delay) + waited.append(delay) + if lease is not None and claim is not None: + lease.heartbeat(claim) + seen = self._read() + reads.append(seen) + if seen is ReadBack.PRESENT: + committed = _commit_lease() + _latch() + return SettleResult( + SettleOutcome.COMMITTED, + f"record seen on poll {len(reads)} after a {status.value} submit", + submits=1, + submit_status=status, + read_backs=tuple(reads), + delays=tuple(waited), + claim=claim, + lease_committed=committed, + value=value, + ) + + if self.absent_is_final and reads and all(r is ReadBack.ABSENT for r in reads): + if lease is not None and claim is not None: + lease.release( + claim, note="absent after settle window", even_if_uncertain=True + ) + return SettleResult( + SettleOutcome.RETRY_SAFE, + f"record absent on all {len(reads)} polls and absence is final", + submits=1, + submit_status=status, + read_backs=tuple(reads), + delays=tuple(waited), + claim=claim, + value=value, + ) + + reason = ( + f"{status.value} submit; record not seen in {len(reads)} polls " + f"over {sum(waited):.1f}s" + ) + if lease is not None and claim is not None: + lease.mark_uncertain(claim, note=reason) + _latch() + with self._lock: + self._unverified[(app, item_key)] = reason + return SettleResult( + SettleOutcome.COMPLETED_UNVERIFIED, + reason, + submits=1, + submit_status=status, + read_backs=tuple(reads), + delays=tuple(waited), + claim=claim, + value=value, + ) + + +# --------------------------------------------------------------------------- +# SimplexTransducer hooks +# --------------------------------------------------------------------------- + +_ITEM_KEY_NAMES: tuple[str, ...] = ("work_item_key", "item_key") +_APP_NAMES: tuple[str, ...] = ("work_app", "app", "app_id", "domain") + + +def _get(obj: Any, name: str) -> Any: + if obj is None: + return None + if isinstance(obj, Mapping): + return obj.get(name) + return getattr(obj, name, None) + + +def _first(sources: tuple[Any, ...], names: tuple[str, ...]) -> str: + for source in sources: + for name in names: + value = _get(source, name) + if value not in (None, ""): + return str(value) + return "" + + +def work_item_for(task: Any, observation: Any = None) -> tuple[str, str] | None: + """``(app, canonical item key)`` the task names, or None when it names none. + + Looks for ``work_item_key`` or ``item_key`` on the task, its + ``raw_config`` and the observation's ``raw_observation``; the app comes + from ``work_app``, ``app``, ``app_id`` or ``domain`` in the same places. + """ + sources = ( + task, + _get(task, "raw_config"), + observation, + _get(observation, "raw_observation"), + ) + raw_key = _first(sources, _ITEM_KEY_NAMES) + if not raw_key: + return None + app = canonical_item_key(_first(sources, _APP_NAMES)) + return app, canonical_item_key(raw_key) + + +class WorkLeaseHooks: + """Connect a ``SharedWorkLease`` to one ``SimplexTransducer``. + + Each ``(run_id, task_id)`` episode claims its work item before its first + commit is released. If another worker holds the item the commit is + replaced by a wait; if the item is already committed the episode stops + with ``WORK_ITEM_ALREADY_COMMITTED``. The claim is renewed every step and + committed once a commit is verified. A claim whose commit was never + verified is not released when the episode ends: the save may have landed, + so the TTL (or a settle step) decides. + """ + + def __init__(self, owner: SimplexTransducer, lease: SharedWorkLease | None): + self.owner = owner + self.lease = lease + self._lock = threading.RLock() + self._claims: dict[tuple[str, str], LeaseClaim] = {} + + def claim_for(self, state: EpisodeState) -> LeaseClaim | None: + with self._lock: + return self._claims.get((state.run_id, state.task_id)) + + def on_step(self, state: EpisodeState) -> None: + claim = self.claim_for(state) + if self.lease is not None and claim is not None: + self.lease.heartbeat(claim) + + def gate( + self, state: EpisodeState, action: Any, observation: Any, task: Any + ) -> Any: + """Return *action* if this episode may commit it, else a wait or a stop.""" + if self.lease is None or self.claim_for(state) is not None: + return action + item = work_item_for(task, observation) + if item is None: + return action + app, item_key = item + claim = self.lease.claim(app, item_key) + if claim.granted: + with self._lock: + self._claims[(state.run_id, state.task_id)] = claim + return action + if claim.decision is ClaimDecision.SKIP_COMMITTED: + return self.owner._abstain_action( + state, + trap_code="WORK_ITEM_ALREADY_COMMITTED", + reason=( + f"Work item {item_key!r} was already saved by another worker; " + "skipping it so it is not saved twice." + ), + commit_index=state.next_commit_index, + ) + holder = claim.record.holder if claim.record is not None else "another worker" + return self.owner._build_wait_action( + state, + observation, + f"Work item {item_key!r} is held by {holder} ({claim.decision.value}).", + guard="WORK_LEASE_HELD", + ) + + def on_verified(self, state: EpisodeState) -> None: + claim = self.claim_for(state) + if self.lease is not None and claim is not None: + self.lease.commit(claim, note=f"verified in run {state.run_id}") + + def forget(self, run_id: str | None = None, task_id: str | None = None) -> None: + with self._lock: + if run_id is not None and task_id is not None: + self._claims.pop((run_id, task_id), None) + elif run_id is not None: + for key in [k for k in self._claims if k[0] == run_id]: + self._claims.pop(key, None) + else: + self._claims.clear() diff --git a/openadapt/transducer_fact_ledger.py b/openadapt/transducer_fact_ledger.py index 4743459de9..0e58a1dff2 100644 --- a/openadapt/transducer_fact_ledger.py +++ b/openadapt/transducer_fact_ledger.py @@ -493,6 +493,26 @@ def confirm(self, frame_digest: str) -> list[LatchedSubmit]: self._pending = still_pending return latched + def latch_now( + self, control_key: str, text: str, *, step_index: int, commit_index: int + ) -> LatchedSubmit: + """Latch a submit whose outcome was settled outside the screen loop. + + Used when a read-back already showed the save, or when a submit with an + unknown outcome must not be repeated, so no later frame is needed. + """ + tokens = _semantic_tokens(text) + entry = LatchedSubmit( + control_key=control_key, + semantic_hash=_token_hash(tokens), + tokens=tokens, + step_index=int(step_index), + commit_index=int(commit_index), + ) + with self._lock: + self._latched.setdefault(control_key, []).append(entry) + return entry + def match(self, control_key: str, text: str) -> LatchedSubmit | None: tokens = _semantic_tokens(text) digest = _token_hash(tokens) diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index 3cf30ab99b..df109d4eaf 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -2503,6 +2503,7 @@ def wrap( sop_contract: Any = None, dual_egress: Any = None, compounding_handoff: Any = None, + work_lease: Any = None, ) -> Any: """Wrap a Python function, coroutine, tool, or agent with commit-boundary checks. @@ -2521,6 +2522,11 @@ def wrap( ``checked_how`` declares how ``check`` reads the result. Without it a ``check`` is recorded as ``caller_check``; a value the check returns in a mapping is ignored, so a check can't claim ``system_of_record`` for itself. + + ``work_lease`` (a ``SharedWorkLease``) lets several workers share one queue + of items. It applies to ``.act`` agents only: an episode claims the task's + ``work_item_key`` before its first commit, waits while another worker holds + it, and stops instead of saving an item another worker already committed. """ if check is not None and expect is not None: raise ValueError("pass either check= or expect=, not both") @@ -2618,6 +2624,12 @@ def _apply(obj: Any) -> Any: sop_contract=sop_contract, dual_egress=dual_egress, compounding_handoff=compounding_handoff, + work_lease=work_lease, + ) + if work_lease is not None: + raise TypeError( + "work_lease applies to agents exposing .act; use " + "BoundedSettleAndReconcile(...).run(submit, lease=...) for a function" ) if callable(obj) and not inspect.isclass(obj): action_name = ( diff --git a/tests/test_transducer_concurrency.py b/tests/test_transducer_concurrency.py new file mode 100644 index 0000000000..e9463c465f --- /dev/null +++ b/tests/test_transducer_concurrency.py @@ -0,0 +1,699 @@ +"""Tests for ``openadapt.transducer_concurrency``: shared work lease and settle.""" + +from __future__ import annotations + +import multiprocessing +import os +import random +import sqlite3 +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import pytest + +import openadapt +from openadapt.simplex_transducer import SimplexTransducer, TransducerAction +from openadapt.transducer_concurrency import ( + BoundedSettleAndReconcile, + ClaimDecision, + LeaseState, + ReadBack, + SettleOutcome, + SharedWorkLease, + SubmitStatus, + canonical_item_key, + work_item_for, +) +from openadapt.transducer_fact_ledger import FormCommitLatch + +# --------------------------------------------------------------------------- +# helpers +# --------------------------------------------------------------------------- + + +class _Clock: + def __init__(self, start: float = 1000.0) -> None: + self.now = start + + def __call__(self) -> float: + return self.now + + def sleep(self, seconds: float) -> None: + self.now += seconds + + +def _app_db(path: Path) -> None: + con = sqlite3.connect(str(path)) + con.execute("CREATE TABLE IF NOT EXISTS saved (item_key TEXT, worker TEXT)") + con.commit() + con.close() + + +def _app_save(path: Path, item_key: str, worker: str) -> None: + con = sqlite3.connect(str(path), timeout=30) + con.execute("INSERT INTO saved VALUES (?, ?)", (item_key, worker)) + con.commit() + con.close() + + +def _app_counts(path: Path) -> dict[str, int]: + con = sqlite3.connect(str(path)) + rows = con.execute( + "SELECT item_key, COUNT(*) FROM saved GROUP BY item_key" + ).fetchall() + con.close() + return {str(k): int(n) for k, n in rows} + + +def _race_worker( + lease_path: str, + app_path: str, + worker: str, + items: list[str], + barrier: Any, + results: Any, +) -> None: + """Claim every item; save and commit only the ones this worker won.""" + lease = SharedWorkLease(lease_path, worker_id=worker, ttl_s=60) + order = list(items) + random.Random(worker).shuffle(order) + barrier.wait() + for item in order: + claim = lease.claim("app", item) + if claim.granted: + _app_save(Path(app_path), item, worker) + if not lease.commit(claim): + results.put((worker, item, "commit_lost")) + continue + results.put((worker, item, "won")) + else: + results.put((worker, item, claim.decision.value)) + + +def _crash_worker(lease_path: str, ready: Any) -> None: + """Claim the item, then die without committing or releasing.""" + lease = SharedWorkLease(lease_path, worker_id="crasher", ttl_s=0.5) + claim = lease.claim("app", "item-1") + ready.put(claim.granted) + # Flush the queue's feeder thread; os._exit skips all cleanup. + ready.close() + ready.join_thread() + os._exit(1) + + +@dataclass +class _SlowApp: + """A form endpoint whose save lands after a number of read-backs. + + ``drop_ack`` makes ``submit`` raise ``TimeoutError`` after the server has + accepted the request, the way a proxy timeout or dropped response does. + ``lands_after_reads`` is how many post-submit read-backs pass before the + record is visible (an async background save). None means it never lands. + """ + + drop_ack: bool = True + lands_after_reads: int | None = 3 + records: list[str] = field(default_factory=list) + submits: int = 0 + reads_after_submit: int = 0 + _queued: list[str] = field(default_factory=list) + + def submit(self, item_key: str) -> Any: + self.submits += 1 + self._queued.append(item_key) + if self.lands_after_reads == 0: + self.records.extend(self._queued) + self._queued.clear() + if self.drop_ack: + raise TimeoutError("proxy timed out waiting for the response") + return {"status": 200} + + def read_back(self, item_key: str) -> ReadBack: + if self.submits: + self.reads_after_submit += 1 + if ( + self.lands_after_reads is not None + and self.reads_after_submit >= self.lands_after_reads + and self._queued + ): + self.records.extend(self._queued) + self._queued.clear() + return ReadBack.PRESENT if item_key in self.records else ReadBack.ABSENT + + +# --------------------------------------------------------------------------- +# canonical keys +# --------------------------------------------------------------------------- + + +def test_canonical_item_key_normalizes_spacing_case_and_width() -> None: + assert canonical_item_key(" Claim ", "ABC 123") == "claim|abc 123" + assert canonical_item_key("Claim", None, "", "x") == "claim|x" + + +def test_work_item_for_reads_task_raw_config_and_observation() -> None: + assert work_item_for({"work_item_key": " A-1 ", "app": "Portal"}) == ( + "portal", + "a-1", + ) + + @dataclass + class _Task: + task_id: str + domain: str + raw_config: dict[str, Any] + + task = _Task("t", "Billing", {"item_key": "INV 9"}) + assert work_item_for(task) == ("billing", "inv 9") + assert work_item_for({}, {"raw_observation": {"item_key": "z"}}) == ("", "z") + assert work_item_for({"task_id": "t"}) is None + + +# --------------------------------------------------------------------------- +# SharedWorkLease +# --------------------------------------------------------------------------- + + +def test_lease_uses_sqlite_wal_mode(tmp_path: Path) -> None: + lease = SharedWorkLease(tmp_path / "lease.db") + con = sqlite3.connect(str(lease.path)) + assert con.execute("PRAGMA journal_mode").fetchone()[0].lower() == "wal" + con.close() + + +def test_lease_lifecycle_claim_wait_commit_skip(tmp_path: Path) -> None: + clock = _Clock() + a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + + ca = a.claim("app", "k") + assert ca.decision is ClaimDecision.GRANTED and ca.fence == 1 + cb = b.claim("app", "k") + assert cb.decision is ClaimDecision.WAIT + assert cb.record is not None and cb.record.holder == "a" + # The same worker does not get a second claim on a live item either. + assert a.claim("app", "k").decision is ClaimDecision.WAIT + + assert a.commit(ca) is True + assert a.commit(ca) is False # already terminal + assert b.claim("app", "k").decision is ClaimDecision.SKIP_COMMITTED + clock.now += 10_000 # COMMITTED never expires + assert b.claim("app", "k").decision is ClaimDecision.SKIP_COMMITTED + rec = b.status("app", "k") + assert rec is not None and rec.state is LeaseState.COMMITTED + + +def test_lease_release_lets_another_worker_claim(tmp_path: Path) -> None: + a = SharedWorkLease(tmp_path / "l.db", worker_id="a") + b = SharedWorkLease(tmp_path / "l.db", worker_id="b") + ca = a.claim("app", "k") + assert a.release(ca) is True + cb = b.claim("app", "k") + assert cb.decision is ClaimDecision.GRANTED and cb.fence == 2 + assert a.heartbeat(ca) is False + + +def test_ttl_expiry_takeover_after_crashed_holder_and_fence_rejects_zombie( + tmp_path: Path, +) -> None: + clock = _Clock() + a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + ca = a.claim("app", "k") + clock.now += 5 + assert a.heartbeat(ca) is True # renewed to t+15 + clock.now += 9 + assert b.claim("app", "k").decision is ClaimDecision.WAIT + # "a" crashes: no more heartbeats. Its TTL passes. + clock.now += 2 + cb = b.claim("app", "k") + assert cb.decision is ClaimDecision.TAKEOVER + assert cb.previous_holder == "a" and cb.fence == ca.fence + 1 + # "a" wakes up: every write on its stale claim is refused. + assert a.heartbeat(ca) is False + assert a.commit(ca) is False + assert a.release(ca) is False + assert b.commit(cb) is True + rec = a.status("app", "k") + assert rec is not None and rec.holder == "b" and rec.state is LeaseState.COMMITTED + + +def test_ttl_takeover_after_real_process_crash(tmp_path: Path) -> None: + path = str(tmp_path / "l.db") + SharedWorkLease(path) + ctx = multiprocessing.get_context("spawn") + ready = ctx.Queue() + proc = ctx.Process(target=_crash_worker, args=(path, ready)) + proc.start() + assert ready.get(timeout=60) is True + proc.join(timeout=60) + assert proc.exitcode == 1 + + survivor = SharedWorkLease(path, worker_id="survivor", ttl_s=5) + assert survivor.claim("app", "item-1").decision is ClaimDecision.WAIT + rec = survivor.wait("app", "item-1", timeout_s=10, poll_s=0.05) + assert rec is not None and rec.expires_at <= time.time() + claim = survivor.claim("app", "item-1") + assert claim.decision is ClaimDecision.TAKEOVER + assert claim.previous_holder == "crasher" + assert survivor.commit(claim) is True + + +def test_race_processes_exactly_one_winner_per_item_zero_duplicates( + tmp_path: Path, +) -> None: + lease_path = tmp_path / "lease.db" + app_path = tmp_path / "app.db" + SharedWorkLease(lease_path) + _app_db(app_path) + items = [f"item-{i}" for i in range(6)] + n_workers = 8 + ctx = multiprocessing.get_context("spawn") + barrier = ctx.Barrier(n_workers) + results = ctx.Queue() + procs = [ + ctx.Process( + target=_race_worker, + args=(str(lease_path), str(app_path), f"p{i}", items, barrier, results), + ) + for i in range(n_workers) + ] + for p in procs: + p.start() + got = [results.get(timeout=120) for _ in range(n_workers * len(items))] + for p in procs: + p.join(timeout=60) + assert p.exitcode == 0 + + for item in items: + outcomes = [o for _, i, o in got if i == item] + assert outcomes.count("won") == 1, (item, outcomes) + assert "commit_lost" not in outcomes + assert set(outcomes) <= {"won", "WAIT", "SKIP_COMMITTED"} + assert _app_counts(app_path) == {item: 1 for item in items} + lease = SharedWorkLease(lease_path) + assert [r.state for r in lease.records()] == [LeaseState.COMMITTED] * len(items) + + +def test_race_threads_exactly_one_winner(tmp_path: Path) -> None: + lease_path = tmp_path / "lease.db" + app_path = tmp_path / "app.db" + SharedWorkLease(lease_path) + _app_db(app_path) + n_workers = 16 + barrier = threading.Barrier(n_workers) + out: list[tuple[str, str, str]] = [] + out_lock = threading.Lock() + + class _Q: + def put(self, row: tuple[str, str, str]) -> None: + with out_lock: + out.append(row) + + threads = [ + threading.Thread( + target=_race_worker, + args=(str(lease_path), str(app_path), f"t{i}", ["same"], barrier, _Q()), + ) + for i in range(n_workers) + ] + for t in threads: + t.start() + for t in threads: + t.join(timeout=60) + assert [o for _, _, o in out].count("won") == 1 + assert _app_counts(app_path) == {"same": 1} + + +def test_keep_alive_renews_and_reports_loss(tmp_path: Path) -> None: + a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=0.3) + b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=0.3) + claim = a.claim("app", "k") + with a.keep_alive(claim, interval_s=0.05) as lost: + time.sleep(0.6) + assert b.claim("app", "k").decision is ClaimDecision.WAIT + assert not lost.is_set() + a.resolve("app", "k", committed=False) + time.sleep(0.2) + assert lost.is_set() + + +# --------------------------------------------------------------------------- +# BoundedSettleAndReconcile +# --------------------------------------------------------------------------- + + +def _settler(app: _SlowApp, clock: _Clock, **kw: Any) -> BoundedSettleAndReconcile: + return BoundedSettleAndReconcile( + read_back=lambda: app.read_back("k"), + sleep=clock.sleep, + clock=clock, + **kw, + ) + + +def test_dropped_ack_reconciles_after_backoff_polls_with_zero_duplicates( + tmp_path: Path, +) -> None: + clock = _Clock() + app = _SlowApp(drop_ack=True, lands_after_reads=3) + lease = SharedWorkLease(tmp_path / "l.db", worker_id="a", clock=clock) + other = SharedWorkLease(tmp_path / "l.db", worker_id="b", clock=clock) + settle = _settler(app, clock) + during: list[Any] = [] + + def _sleep(seconds: float) -> None: + # While settling: a second attempt here, and another worker, must not + # get to submit again. + during.append(settle.run(lambda: app.submit("k"), app="app", item_key="k")) + during.append(other.claim("app", "k").decision) + clock.sleep(seconds) + + settle.sleep = _sleep + result = settle.run(lambda: app.submit("k"), app="app", item_key="k", lease=lease) + + assert result.outcome is SettleOutcome.COMMITTED + assert result.submit_status is SubmitStatus.UNCERTAIN + assert result.submits == 1 and app.submits == 1 + assert result.read_backs == (ReadBack.ABSENT, ReadBack.ABSENT, ReadBack.PRESENT) + assert result.delays == (1.0, 2.0, 4.0) + assert result.lease_committed is True + assert app.records == ["k"] + assert all( + r.outcome is SettleOutcome.BLOCKED for r in during if hasattr(r, "outcome") + ) + assert ClaimDecision.HELD_UNCERTAIN in during + rec = lease.status("app", "k") + assert rec is not None and rec.state is LeaseState.COMMITTED and not rec.uncertain + + # A later attempt by either worker skips without submitting. + again = settle.run(lambda: app.submit("k"), app="app", item_key="k", lease=other) + assert again.outcome is SettleOutcome.ALREADY_COMMITTED and again.submits == 0 + assert app.submits == 1 and app.records == ["k"] + + +def test_async_background_save_after_two_polls_with_ack() -> None: + clock = _Clock() + app = _SlowApp(drop_ack=False, lands_after_reads=2) + result = _settler(app, clock).run(lambda: app.submit("k"), app="app", item_key="k") + assert result.outcome is SettleOutcome.COMMITTED + assert result.submit_status is SubmitStatus.ACKED + assert result.read_backs == (ReadBack.ABSENT, ReadBack.PRESENT) + assert app.records == ["k"] and app.submits == 1 + + +def test_no_record_within_budget_returns_completed_unverified_and_blocks_resubmit( + tmp_path: Path, +) -> None: + clock = _Clock() + # The save lands, but only after the settle budget: a retry would duplicate. + app = _SlowApp(drop_ack=True, lands_after_reads=None) + lease = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + other = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + settle = _settler(app, clock, max_polls=4, budget_s=10.0) + + result = settle.run(lambda: app.submit("k"), app="app", item_key="k", lease=lease) + assert result.outcome is SettleOutcome.COMPLETED_UNVERIFIED + assert result.submits == 1 + # 1 + 2 + 4 = 7 s fits a 10 s budget; the next 8 s wait would not. + assert result.delays == (1.0, 2.0, 4.0) + assert result.read_backs == (ReadBack.ABSENT,) * 3 + assert ("app", "k") in settle.unverified() + + # Same process: blocked. Other worker: held, even long after the TTL. + blocked = settle.run(lambda: app.submit("k"), app="app", item_key="k") + assert blocked.outcome is SettleOutcome.BLOCKED + clock.now += 3600 + assert other.claim("app", "k").decision is ClaimDecision.HELD_UNCERTAIN + fresh = _settler(app, clock) + held = fresh.run(lambda: app.submit("k"), app="app", item_key="k", lease=other) + assert held.outcome is SettleOutcome.WAIT + assert lease.release(result.claim) is False # type: ignore[arg-type] + + # The slow save finally lands; a person resolves the item. + app.records.append("k") + assert lease.resolve("app", "k", committed=True, note="seen by operator") + assert other.claim("app", "k").decision is ClaimDecision.SKIP_COMMITTED + assert app.submits == 1 and app.records.count("k") == 1 + + +def test_not_sent_is_retry_safe_and_releases_lease(tmp_path: Path) -> None: + clock = _Clock() + lease = SharedWorkLease(tmp_path / "l.db", worker_id="a", clock=clock) + other = SharedWorkLease(tmp_path / "l.db", worker_id="b", clock=clock) + calls: list[int] = [] + + def _refused() -> None: + calls.append(1) + raise ConnectionRefusedError("connection refused") + + settle = BoundedSettleAndReconcile( + read_back=lambda: ReadBack.ABSENT, sleep=clock.sleep, clock=clock + ) + result = settle.run(_refused, app="app", item_key="k", lease=lease) + assert result.outcome is SettleOutcome.RETRY_SAFE + assert result.read_backs == () and calls == [1] + assert other.claim("app", "k").decision is ClaimDecision.GRANTED + + +def test_absent_is_final_retry_safe_only_when_every_poll_is_absent() -> None: + clock = _Clock() + seq = iter([ReadBack.ABSENT, ReadBack.ABSENT, ReadBack.ABSENT, ReadBack.ABSENT]) + settle = BoundedSettleAndReconcile( + read_back=lambda: next(seq), + max_polls=3, + absent_is_final=True, + sleep=clock.sleep, + clock=clock, + ) + r = settle.run(lambda: SubmitStatus.UNCERTAIN, app="a", item_key="k") + assert r.outcome is SettleOutcome.RETRY_SAFE + + unknown = iter([ReadBack.ABSENT, ReadBack.ABSENT, ReadBack.UNKNOWN, None]) + settle2 = BoundedSettleAndReconcile( + read_back=lambda: next(unknown), + max_polls=3, + absent_is_final=True, + sleep=clock.sleep, + clock=clock, + ) + r2 = settle2.run(lambda: SubmitStatus.UNCERTAIN, app="a", item_key="k") + assert r2.outcome is SettleOutcome.COMPLETED_UNVERIFIED + + +def test_absent_is_final_release_is_fenced_against_stale_holder( + tmp_path: Path, +) -> None: + clock = _Clock() + a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + + # Normal case: the holder's own claim is released and can be claimed again. + settle = BoundedSettleAndReconcile( + read_back=lambda: ReadBack.ABSENT, + max_polls=2, + absent_is_final=True, + check_before_submit=False, + sleep=clock.sleep, + clock=clock, + ) + ok = settle.run(lambda: SubmitStatus.UNCERTAIN, app="app", item_key="k1", lease=a) + assert ok.outcome is SettleOutcome.RETRY_SAFE + assert b.claim("app", "k1").decision is ClaimDecision.GRANTED + + # Stale holder: "a" settles on a claim that "b" took over meanwhile. + stale = a.claim("app", "k2") + clock.now += 11 + fresh = b.claim("app", "k2") + assert fresh.decision is ClaimDecision.TAKEOVER + result = settle.run( + lambda: SubmitStatus.UNCERTAIN, app="app", item_key="k2", lease=a, claim=stale + ) + assert result.outcome is SettleOutcome.RETRY_SAFE + assert a.release(stale, even_if_uncertain=True) is False + rec = b.status("app", "k2") + assert rec is not None and rec.holder == "b" and rec.state is LeaseState.PENDING + assert b.commit(fresh) is True + + +def test_acked_submit_is_held_while_settling_so_a_crash_cannot_be_taken_over( + tmp_path: Path, +) -> None: + clock = _Clock() + a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + seen: list[ClaimDecision] = [] + + def _crash_during_settle(seconds: float) -> None: + clock.now += 3600 # the holder stalls far past its TTL + seen.append(b.claim("app", "k").decision) + raise KeyboardInterrupt # and dies + + settle = BoundedSettleAndReconcile( + read_back=lambda: ReadBack.ABSENT, + check_before_submit=False, + sleep=_crash_during_settle, + clock=clock, + ) + with pytest.raises(KeyboardInterrupt): + settle.run(lambda: {"status": 200}, app="app", item_key="k", lease=a) + assert seen == [ClaimDecision.HELD_UNCERTAIN] + assert b.claim("app", "k").decision is ClaimDecision.HELD_UNCERTAIN + + +def test_unknown_read_backs_never_mean_retry() -> None: + clock = _Clock() + + def _broken() -> ReadBack: + raise RuntimeError("page did not load") + + settle = BoundedSettleAndReconcile( + read_back=_broken, absent_is_final=True, sleep=clock.sleep, clock=clock + ) + r = settle.run(lambda: SubmitStatus.UNCERTAIN, app="a", item_key="k") + assert r.outcome is SettleOutcome.COMPLETED_UNVERIFIED + assert set(r.read_backs) == {ReadBack.UNKNOWN} + + +def test_record_already_present_skips_submit(tmp_path: Path) -> None: + lease = SharedWorkLease(tmp_path / "l.db", worker_id="a") + calls: list[int] = [] + settle = BoundedSettleAndReconcile(read_back=lambda: True) + r = settle.run(lambda: calls.append(1), app="a", item_key="k", lease=lease) + assert r.outcome is SettleOutcome.ALREADY_COMMITTED and calls == [] + assert r.lease_committed is True + + +def test_settle_latches_form_commit_latch_and_blocks_same_content() -> None: + clock = _Clock() + app = _SlowApp(drop_ack=True, lands_after_reads=1) + latch = FormCommitLatch() + r = _settler(app, clock).run( + lambda: app.submit("k"), + app="app", + item_key="k", + latch=latch, + control_key="notes", + text="Called patient, left voicemail", + commit_index=1, + ) + assert r.outcome is SettleOutcome.COMMITTED + assert latch.latched_count() == 1 + # A fresh settler (no in-process memory) is still stopped by the latch. + r2 = _settler(app, clock).run( + lambda: app.submit("k2"), + app="app", + item_key="k2", + latch=latch, + control_key="notes", + text="left voicemail, called patient", + ) + assert r2.outcome is SettleOutcome.BLOCKED + assert app.submits == 1 + + +def test_settle_rejects_bad_config() -> None: + with pytest.raises(ValueError): + BoundedSettleAndReconcile(read_back=lambda: True, max_polls=0) + with pytest.raises(ValueError): + BoundedSettleAndReconcile(read_back=lambda: True, backoff=0.5) + + +# --------------------------------------------------------------------------- +# SimplexTransducer / openadapt.wrap wiring +# --------------------------------------------------------------------------- + + +@dataclass +class _Act: + type: str + raw_action: dict[str, Any] = field(default_factory=dict) + is_commit: bool = False + + +class _Agent: + def __init__(self, script: list[Any]) -> None: + self.script = list(script) + + def act(self, observation: Any, task: Any, history: Any = None) -> Any: + return self.script.pop(0) if self.script else _Act(type="done") + + +def _save() -> _Act: + return _Act(type="click", is_commit=True, raw_action={"op": "save"}) + + +def test_transducer_second_worker_waits_then_skips_committed_item( + tmp_path: Path, +) -> None: + lease_a = SharedWorkLease(tmp_path / "l.db", worker_id="worker-a") + lease_b = SharedWorkLease(tmp_path / "l.db", worker_id="worker-b") + verified = {"a": False} + worker_a = openadapt.wrap( + _Agent([_save(), _Act(type="click", raw_action={"nav": 1})]), + work_lease=lease_a, + rung3_verifier=lambda o, t, s: {"verified": verified["a"]}, + ) + worker_b = SimplexTransducer(_Agent([_save(), _save()]), work_lease=lease_b) + assert isinstance(worker_a, SimplexTransducer) + task_a = {"run_id": "ra", "task_id": "t", "work_item_key": "INV-7", "app": "erp"} + task_b = {"run_id": "rb", "task_id": "t", "work_item_key": " inv-7 ", "app": "ERP"} + + a1 = worker_a.act({}, task_a) + assert a1.is_commit is True + + b1 = worker_b.act({}, task_b) + assert b1.type == "wait" + assert b1.raw_action["guard"] == "WORK_LEASE_HELD" + assert worker_b.wal.get("rb", "t", 1) is None # nothing recorded as sent + + verified["a"] = True + worker_a.act({}, task_a) + rec = lease_a.status("erp", "inv-7") + assert rec is not None and rec.state is LeaseState.COMMITTED + + b2 = worker_b.act({}, task_b) + assert isinstance(b2, TransducerAction) and b2.is_abstained + assert b2.raw_action["trap_code"] == "WORK_ITEM_ALREADY_COMMITTED" + + +def test_transducer_without_item_key_or_lease_is_unchanged(tmp_path: Path) -> None: + lease = SharedWorkLease(tmp_path / "l.db") + t = SimplexTransducer(_Agent([_save()]), work_lease=lease) + assert t.act({}, {"run_id": "r", "task_id": "t"}).is_commit is True + assert lease.records() == [] + plain = SimplexTransducer(_Agent([_save()])) + assert plain.work_lease is None + assert plain.act({}, {"run_id": "r", "task_id": "t"}).is_commit is True + + +def test_transducer_heartbeats_held_claim_each_step(tmp_path: Path) -> None: + clock = _Clock() + lease = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + t = SimplexTransducer( + _Agent([_save()] + [_Act(type="click")] * 3), work_lease=lease + ) + task = {"run_id": "r", "task_id": "t", "item_key": "k"} + t.act({}, task) + first = lease.status("", "k") + assert first is not None + clock.now += 5 + t.act({}, task) + later = lease.status("", "k") + assert later is not None and later.expires_at == first.expires_at + 5 + t.reset(run_id="r", task_id="t") + assert t._lease.claim_for(t.get_state("r", "t")) is None + + +def test_wrap_rejects_work_lease_for_plain_function(tmp_path: Path) -> None: + with pytest.raises(TypeError): + openadapt.wrap(lambda: 1, work_lease=SharedWorkLease(tmp_path / "l.db")) + + +def test_lazy_exports() -> None: + assert openadapt.SharedWorkLease is SharedWorkLease + assert openadapt.BoundedSettleAndReconcile is BoundedSettleAndReconcile + assert openadapt.SettleOutcome is SettleOutcome From 7b8236de07ce9e20dd91a91a7806b3e060315737 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 22:07:36 -0500 Subject: [PATCH 2/3] fix(transducer): settle refuses to submit on a lost claim A worker that stalled past its TTL could still run submit() on an item another worker had taken over. Heartbeat the claim right before submit and return WAIT if it was lost. The stale-holder test now asserts no submit. --- openadapt/transducer_concurrency.py | 7 +++++++ tests/test_transducer_concurrency.py | 15 ++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/openadapt/transducer_concurrency.py b/openadapt/transducer_concurrency.py index 827d5e0397..7fec30096d 100644 --- a/openadapt/transducer_concurrency.py +++ b/openadapt/transducer_concurrency.py @@ -737,6 +737,13 @@ def _latch() -> None: lease_committed=committed, ) + # Confirm the claim is still ours right before sending. A worker that + # stalled past its TTL must not submit an item someone else now holds. + if lease is not None and claim is not None and not lease.heartbeat(claim): + return SettleResult( + SettleOutcome.WAIT, "the claim was lost before submitting", claim=claim + ) + value: Any = None try: value = submit() diff --git a/tests/test_transducer_concurrency.py b/tests/test_transducer_concurrency.py index e9463c465f..090c009872 100644 --- a/tests/test_transducer_concurrency.py +++ b/tests/test_transducer_concurrency.py @@ -504,15 +504,20 @@ def test_absent_is_final_release_is_fenced_against_stale_holder( assert ok.outcome is SettleOutcome.RETRY_SAFE assert b.claim("app", "k1").decision is ClaimDecision.GRANTED - # Stale holder: "a" settles on a claim that "b" took over meanwhile. + # Stale holder: "a" tries to settle on a claim that "b" took over meanwhile. stale = a.claim("app", "k2") clock.now += 11 fresh = b.claim("app", "k2") assert fresh.decision is ClaimDecision.TAKEOVER - result = settle.run( - lambda: SubmitStatus.UNCERTAIN, app="app", item_key="k2", lease=a, claim=stale - ) - assert result.outcome is SettleOutcome.RETRY_SAFE + sent: list[int] = [] + + def _submit() -> SubmitStatus: + sent.append(1) + return SubmitStatus.UNCERTAIN + + result = settle.run(_submit, app="app", item_key="k2", lease=a, claim=stale) + assert result.outcome is SettleOutcome.WAIT + assert sent == [] # no second submit assert a.release(stale, even_if_uncertain=True) is False rec = b.status("app", "k2") assert rec is not None and rec.holder == "b" and rec.state is LeaseState.PENDING From 04f86f7aa7d35ec14fa4385ba9559695d85fea53 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 23:14:18 -0500 Subject: [PATCH 3/3] fix(transducer): hold the lease through the send and send only on confirmed absence Smoke failed on a new swallow_wide verdict fold: the submit handler caught BaseException and fell through with a status from an opaque call. The handler now catches not_sent_errors narrowly and sets SubmitStatus.UNKNOWN for any other exception (renamed from UNCERTAIN to match ReadBack.UNKNOWN). Also addresses the Grok review at 7b8236de: - Mark the claim uncertain before submit(), so a send that outlasts the TTL cannot be taken over and sent again by another worker. - Send only when the pre-submit read-back shows the record is ABSENT. An UNKNOWN, unparseable or raising read-back ends with the new UNCHECKED outcome, sends nothing and releases the lease. - WorkLeaseHooks.gate heartbeats a cached claim before each later commit and stops the episode with WORK_LEASE_LOST once the claim was taken over. --- openadapt/transducer_concurrency.py | 98 ++++++++++++++++++++-------- tests/test_transducer_concurrency.py | 89 +++++++++++++++++++++++-- 2 files changed, 152 insertions(+), 35 deletions(-) diff --git a/openadapt/transducer_concurrency.py b/openadapt/transducer_concurrency.py index 7fec30096d..460a114775 100644 --- a/openadapt/transducer_concurrency.py +++ b/openadapt/transducer_concurrency.py @@ -12,14 +12,18 @@ fence, so a holder that wakes up after a takeover cannot commit. * ``BoundedSettleAndReconcile`` runs one submit when its response may be lost (a dropped HTTP response, a proxy timeout) or the app saves in a background - job. It never re-submits on an uncertain outcome. It marks the lease as - uncertain, waits with bounded backoff and reopens the record the way a person - would (``read_back``) until the record shows up or the budget runs out. The - result is ``COMMITTED``, ``RETRY_SAFE`` (only when nothing could have been - saved) or ``COMPLETED_UNVERIFIED``. + job. It sends only after reopening the record shows it is absent, and it + marks the lease as uncertain before sending, so nobody takes the item over + while the send is in flight. It never re-submits on an uncertain outcome. It + waits with bounded backoff and reopens the record the way a person would + (``read_back``) until the record shows up or the budget runs out. The result + is ``COMMITTED``, ``RETRY_SAFE`` (only when nothing could have been saved), + ``COMPLETED_UNVERIFIED`` or ``UNCHECKED`` (absence could not be confirmed, + so nothing was sent). * ``WorkLeaseHooks`` connects a lease to one ``SimplexTransducer``: an episode claims its work item before its first commit is released, renews the claim - every step and marks it committed once a commit is verified. + every step, stops releasing commits once the claim is lost, and marks it + committed once a commit is verified. Nothing here names an application. Apps and item keys are whatever the caller or the task carries. @@ -505,7 +509,8 @@ class SubmitStatus(str, enum.Enum): """What the submit call itself reported.""" ACKED = "ACKED" - UNCERTAIN = "UNCERTAIN" + UNKNOWN = "UNKNOWN" + """The submit raised after it may have reached the server.""" NOT_SENT = "NOT_SENT" @@ -523,6 +528,9 @@ class SettleOutcome(str, enum.Enum): """A submit for this item is settling or unverified; no second submit.""" WAIT = "WAIT" """Another worker holds the item.""" + UNCHECKED = "UNCHECKED" + """Reopening the record before submitting could not show it was absent, so + nothing was sent and the lease was released.""" @dataclass(frozen=True) @@ -555,10 +563,15 @@ class BoundedSettleAndReconcile: the list, open the item) and returns a ``ReadBack`` or a bool (True means present, False means absent). An exception counts as ``UNKNOWN``. + With ``check_before_submit`` (the default) the record is reopened first. + ``PRESENT`` ends with ``ALREADY_COMMITTED``; anything but ``ABSENT`` ends + with ``UNCHECKED`` and nothing is sent. Before sending, the lease is marked + uncertain, so a send that outlasts the TTL cannot be taken over. + ``submit`` may return a ``SubmitStatus``; any other value counts as ``ACKED``. An exception in ``not_sent_errors`` means the request never left - (``NOT_SENT``). Any other exception counts as ``UNCERTAIN``: the request - may have reached the server. An uncertain submit is never repeated here. + (``NOT_SENT``). Any other exception counts as ``UNKNOWN``: the request may + have reached the server. An uncertain submit is never repeated here. After a submit, ``read_back`` runs up to ``max_polls`` times. The waits before each poll start at ``initial_delay_s`` and grow by ``backoff`` up @@ -615,11 +628,6 @@ def _read(self) -> ReadBack: return ReadBack.ABSENT return ReadBack.UNKNOWN - def _classify(self, exc: BaseException) -> SubmitStatus: - if isinstance(exc, self.not_sent_errors): - return SubmitStatus.NOT_SENT - return SubmitStatus.UNCERTAIN - def unverified(self) -> dict[tuple[str, str], str]: """Items this instance left ``COMPLETED_UNVERIFIED``, with the reason.""" with self._lock: @@ -736,21 +744,40 @@ def _latch() -> None: claim=claim, lease_committed=committed, ) + if before is not ReadBack.ABSENT: + if lease is not None and claim is not None: + lease.release(claim, note=f"read-back {before.value} before submit") + return SettleResult( + SettleOutcome.UNCHECKED, + f"the record could not be shown absent before submitting " + f"({before.value}); nothing was sent", + read_backs=(before,), + claim=claim, + ) - # Confirm the claim is still ours right before sending. A worker that - # stalled past its TTL must not submit an item someone else now holds. - if lease is not None and claim is not None and not lease.heartbeat(claim): - return SettleResult( - SettleOutcome.WAIT, "the claim was lost before submitting", claim=claim - ) + # Confirm the claim is still ours and hold it as uncertain before + # sending. A worker that stalled past its TTL must not submit an item + # someone else now holds, and a send that outlasts the TTL must not let + # another worker take the item over and send it again. + if lease is not None and claim is not None: + if not ( + lease.heartbeat(claim) + and lease.mark_uncertain(claim, note="submit in flight") + ): + return SettleResult( + SettleOutcome.WAIT, + "the claim was lost before submitting", + claim=claim, + ) value: Any = None try: value = submit() - except BaseException as exc: - if not isinstance(exc, Exception): - raise - status = self._classify(exc) + except self.not_sent_errors as exc: + status = SubmitStatus.NOT_SENT + detail = f"{type(exc).__name__}: {exc}" + except Exception as exc: + status = SubmitStatus.UNKNOWN detail = f"{type(exc).__name__}: {exc}" else: status = value if isinstance(value, SubmitStatus) else SubmitStatus.ACKED @@ -758,7 +785,7 @@ def _latch() -> None: if status is SubmitStatus.NOT_SENT: if lease is not None and claim is not None: - lease.release(claim, note=f"not sent: {detail}") + lease.release(claim, note=f"not sent: {detail}", even_if_uncertain=True) return SettleResult( SettleOutcome.RETRY_SAFE, f"the submit was not sent ({detail})", @@ -768,7 +795,7 @@ def _latch() -> None: ) # Any sent submit may land, even an acknowledged one whose record is not - # visible yet. Hold the item as uncertain while settling so that, if this + # visible yet. The item stays uncertain while settling so that, if this # worker dies now, no other worker takes it over and submits again. if lease is not None and claim is not None: lease.mark_uncertain(claim, note=f"settling after {detail} submit") @@ -890,7 +917,9 @@ class WorkLeaseHooks: commit is released. If another worker holds the item the commit is replaced by a wait; if the item is already committed the episode stops with ``WORK_ITEM_ALREADY_COMMITTED``. The claim is renewed every step and - committed once a commit is verified. A claim whose commit was never + before every later commit; once it is lost (taken over after its TTL) the + episode stops with ``WORK_LEASE_LOST`` instead of releasing the commit. It + is committed once a commit is verified. A claim whose commit was never verified is not released when the episode ends: the save may have landed, so the TTL (or a settle step) decides. """ @@ -914,8 +943,21 @@ def gate( self, state: EpisodeState, action: Any, observation: Any, task: Any ) -> Any: """Return *action* if this episode may commit it, else a wait or a stop.""" - if self.lease is None or self.claim_for(state) is not None: + if self.lease is None: return action + held = self.claim_for(state) + if held is not None: + if self.lease.heartbeat(held): + return action + return self.owner._abstain_action( + state, + trap_code="WORK_LEASE_LOST", + reason=( + f"Work item {held.item_key!r} was taken over by another " + "worker; not releasing another commit for it." + ), + commit_index=state.next_commit_index, + ) item = work_item_for(task, observation) if item is None: return action diff --git a/tests/test_transducer_concurrency.py b/tests/test_transducer_concurrency.py index 090c009872..f99689dd07 100644 --- a/tests/test_transducer_concurrency.py +++ b/tests/test_transducer_concurrency.py @@ -22,6 +22,7 @@ LeaseState, ReadBack, SettleOutcome, + SettleResult, SharedWorkLease, SubmitStatus, canonical_item_key, @@ -376,7 +377,7 @@ def _sleep(seconds: float) -> None: result = settle.run(lambda: app.submit("k"), app="app", item_key="k", lease=lease) assert result.outcome is SettleOutcome.COMMITTED - assert result.submit_status is SubmitStatus.UNCERTAIN + assert result.submit_status is SubmitStatus.UNKNOWN assert result.submits == 1 and app.submits == 1 assert result.read_backs == (ReadBack.ABSENT, ReadBack.ABSENT, ReadBack.PRESENT) assert result.delays == (1.0, 2.0, 4.0) @@ -469,7 +470,7 @@ def test_absent_is_final_retry_safe_only_when_every_poll_is_absent() -> None: sleep=clock.sleep, clock=clock, ) - r = settle.run(lambda: SubmitStatus.UNCERTAIN, app="a", item_key="k") + r = settle.run(lambda: SubmitStatus.UNKNOWN, app="a", item_key="k") assert r.outcome is SettleOutcome.RETRY_SAFE unknown = iter([ReadBack.ABSENT, ReadBack.ABSENT, ReadBack.UNKNOWN, None]) @@ -480,7 +481,7 @@ def test_absent_is_final_retry_safe_only_when_every_poll_is_absent() -> None: sleep=clock.sleep, clock=clock, ) - r2 = settle2.run(lambda: SubmitStatus.UNCERTAIN, app="a", item_key="k") + r2 = settle2.run(lambda: SubmitStatus.UNKNOWN, app="a", item_key="k") assert r2.outcome is SettleOutcome.COMPLETED_UNVERIFIED @@ -500,7 +501,7 @@ def test_absent_is_final_release_is_fenced_against_stale_holder( sleep=clock.sleep, clock=clock, ) - ok = settle.run(lambda: SubmitStatus.UNCERTAIN, app="app", item_key="k1", lease=a) + ok = settle.run(lambda: SubmitStatus.UNKNOWN, app="app", item_key="k1", lease=a) assert ok.outcome is SettleOutcome.RETRY_SAFE assert b.claim("app", "k1").decision is ClaimDecision.GRANTED @@ -513,7 +514,7 @@ def test_absent_is_final_release_is_fenced_against_stale_holder( def _submit() -> SubmitStatus: sent.append(1) - return SubmitStatus.UNCERTAIN + return SubmitStatus.UNKNOWN result = settle.run(_submit, app="app", item_key="k2", lease=a, claim=stale) assert result.outcome is SettleOutcome.WAIT @@ -556,13 +557,69 @@ def _broken() -> ReadBack: raise RuntimeError("page did not load") settle = BoundedSettleAndReconcile( - read_back=_broken, absent_is_final=True, sleep=clock.sleep, clock=clock + read_back=_broken, + absent_is_final=True, + check_before_submit=False, + sleep=clock.sleep, + clock=clock, ) - r = settle.run(lambda: SubmitStatus.UNCERTAIN, app="a", item_key="k") + r = settle.run(lambda: SubmitStatus.UNKNOWN, app="a", item_key="k") assert r.outcome is SettleOutcome.COMPLETED_UNVERIFIED assert set(r.read_backs) == {ReadBack.UNKNOWN} +@pytest.mark.parametrize("outcome", ["unknown", "none", "raises"]) +def test_unconfirmed_absence_before_submit_sends_nothing( + tmp_path: Path, outcome: str +) -> None: + clock = _Clock() + lease = SharedWorkLease(tmp_path / "l.db", worker_id="a", clock=clock) + other = SharedWorkLease(tmp_path / "l.db", worker_id="b", clock=clock) + calls: list[int] = [] + + def _read() -> ReadBack | None: + if outcome == "raises": + raise RuntimeError("403 forbidden") + return ReadBack.UNKNOWN if outcome == "unknown" else None + + settle = BoundedSettleAndReconcile(read_back=_read, sleep=clock.sleep, clock=clock) + r = settle.run(lambda: calls.append(1), app="app", item_key="k", lease=lease) + assert r.outcome is SettleOutcome.UNCHECKED + assert r.submits == 0 and calls == [] + assert r.read_backs == (ReadBack.UNKNOWN,) + # Nothing was sent, so the item is free for a later, checkable attempt. + assert other.claim("app", "k").decision is ClaimDecision.GRANTED + + +def test_submit_outlasting_ttl_cannot_be_taken_over(tmp_path: Path) -> None: + clock = _Clock() + lease_a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + lease_b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + b_sent: list[int] = [] + b_results: list[SettleResult] = [] + settle_b = BoundedSettleAndReconcile( + read_back=lambda: ReadBack.ABSENT, sleep=clock.sleep, clock=clock + ) + + def _slow_submit() -> None: + clock.now += 11 # the send outlasts A's TTL + b_results.append( + settle_b.run( + lambda: b_sent.append(1), app="app", item_key="k", lease=lease_b + ) + ) + + settle_a = BoundedSettleAndReconcile( + read_back=lambda: ReadBack.ABSENT, sleep=clock.sleep, clock=clock + ) + r = settle_a.run(_slow_submit, app="app", item_key="k", lease=lease_a) + assert r.submits == 1 + assert b_sent == [] + assert b_results[0].outcome is SettleOutcome.WAIT + assert b_results[0].claim is not None + assert b_results[0].claim.decision is ClaimDecision.HELD_UNCERTAIN + + def test_record_already_present_skips_submit(tmp_path: Path) -> None: lease = SharedWorkLease(tmp_path / "l.db", worker_id="a") calls: list[int] = [] @@ -693,6 +750,24 @@ def test_transducer_heartbeats_held_claim_each_step(tmp_path: Path) -> None: assert t._lease.claim_for(t.get_state("r", "t")) is None +def test_transducer_stops_releasing_commits_after_claim_is_lost( + tmp_path: Path, +) -> None: + clock = _Clock() + lease_a = SharedWorkLease(tmp_path / "l.db", worker_id="a", ttl_s=10, clock=clock) + lease_b = SharedWorkLease(tmp_path / "l.db", worker_id="b", ttl_s=10, clock=clock) + t = SimplexTransducer(_Agent([_save(), _save()]), work_lease=lease_a) + task = {"run_id": "r", "task_id": "t", "item_key": "k"} + assert t.act({}, task).is_commit is True + + clock.now += 11 + assert lease_b.claim("", "k").decision is ClaimDecision.TAKEOVER + + second = t.act({}, task) + assert isinstance(second, TransducerAction) and second.is_abstained + assert second.raw_action["trap_code"] == "WORK_LEASE_LOST" + + def test_wrap_rejects_work_lease_for_plain_function(tmp_path: Path) -> None: with pytest.raises(TypeError): openadapt.wrap(lambda: 1, work_lease=SharedWorkLease(tmp_path / "l.db"))