Skip to content

feat(transducer): shared work lease and bounded settle-and-reconcile - #2902

Merged
abrichr merged 3 commits into
mainfrom
feat/transducer-shared-lease-and-async-settle
Dec 2, 2026
Merged

abrichr merged 3 commits into
mainfrom
feat/transducer-shared-lease-and-async-settle

Conversation

@abrichr

@abrichr abrichr commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

What this adds

openadapt/transducer_concurrency.py, two local runtime pieces 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. A claim runs in one BEGIN IMMEDIATE transaction, so exactly one concurrent worker (thread or process) wins.

    • States: PENDING (with a TTL that the holder renews by heartbeat), COMMITTED (terminal; later workers skip the item) and RELEASED (anyone may claim it again).
    • A crashed holder's claim is taken over once its TTL passes. Every takeover bumps a fence number. Heartbeat, commit and release only succeed for the current fence, so a holder that comes back after a takeover cannot commit.
    • A claim marked uncertain (a submit was sent but its outcome is unknown) is never taken over until it is committed or a person resolves it.
  • BoundedSettleAndReconcile: runs one submit and never repeats it after an uncertain outcome, such as a dropped response or a proxy timeout. While settling it holds the lease as uncertain. It then reopens the record (read_back, the check a careful operator would do) with bounded backoff. Results:

    • COMMITTED: the record showed up.
    • RETRY_SAFE: only when the request was never sent, or when the caller sets absent_is_final and every poll saw the record missing.
    • COMPLETED_UNVERIFIED: anything else.

    Unknown read-backs (page error, 403) never count as missing. It works with FormCommitLatch through a new latch_now() method, so the same content on the same control is blocked afterwards.

Wiring

  • SimplexTransducer(..., work_lease=) and openadapt.wrap(agent, work_lease=). An episode claims the task's work_item_key (or item_key) before its first commit is released. While another worker holds the item, the commit is replaced by a wait action (guard WORK_LEASE_HELD). If another worker already committed the item, the episode stops with WORK_ITEM_ALREADY_COMMITTED. The claim is renewed every step and committed when a commit is verified.
  • BoundedSettleAndReconcile is exported and works with the same lease and latch. The code that actually sends the submit (the harness or tool executor) calls it; the transducer does not, because the transducer releases actions and does not send them.
  • wrap(fn, work_lease=...) for a plain function raises TypeError rather than silently ignoring the lease.
  • Without work_lease, behavior is unchanged. All new parameters are optional keyword arguments.

Tests

tests/test_transducer_concurrency.py: 26 tests, all passing in 3 repeat runs (about 3 s each).

  • 8 spawned processes race over 6 items: exactly one winner per item and one saved record per item. A 16-thread race on one item gives the same result.
  • TTL takeover after a real process crash (os._exit while holding a claim), plus fence rejection of a stale holder's heartbeat, commit and release.
  • Dropped response with the record landing on the 3rd backoff poll: COMMITTED, 1 submit. A second attempt during the settle window is BLOCKED and another worker gets HELD_UNCERTAIN.
  • Record never visible within the budget: COMPLETED_UNVERIFIED, with no resubmit from this worker or any other, even after the TTL.
  • A worker whose claim was taken over gets WAIT and never submits. Also: not-sent, absent-is-final (with a fenced release), unknown read-backs, a crash mid-settle after an acknowledged submit, latch blocking, and the transducer/wrap wiring.

Existing suites run locally: 605 passed across test_simplex_transducer.py, test_openadapt_wrap.py, test_wrap_command.py and every test_transducer_*.py. test_wrap_receipt_trust.py fails collection on my machine because of a stale installed openadapt_types (No module named 'openadapt_types.receipt'). That is not related to this change; CI should run it.

ruff check and ruff format --check pass. mypy reports no errors in the new module or test file and none added elsewhere: 41 before and after, all in existing code.

Generality gate

  1. No per-app code in the engine: yes. Nothing names or branches on an app. The app and item key come from the task.
  2. Fix the class, not the instance: the class is "the same item is submitted twice": by two workers, after a lost response, or after a crash and takeover. All three cases use one model (a keyed lease, a fence, and an uncertain hold until read-back), with tests over each entry point.
  3. Held-out evidence: not shown yet. Live Docker runs are preregistered separately and have not run.

Durable item: safe writes and checking effects the way a careful operator would. These pieces keep repeated or concurrent agent saves from creating duplicate records, whichever model drives the agent.

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.
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.
@abrichr

abrichr commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 7b8236d

The lease itself is sound on the paths the tests cover: BEGIN IMMEDIATE claims, fence rejection after takeover, no takeover of an uncertain hold, and post-submit unknown or mixed read-backs never become RETRY_SAFE. tests/test_transducer_concurrency.py: 26 passed, three runs at this exact head (about 2.1–2.3 s each). ruff check is clean on the touched files.

The class this PR names is "the same item is submitted twice": by two workers, after a lost response, or after a crash and takeover. Three holes still let a second submit through.

1. A submit that outlasts the TTL can be taken over and sent again. mark_uncertain runs only after submit() returns. During the send the row stays PENDING and not uncertain, so once the TTL passes another worker is granted TAKEOVER and may submit. The follow-up at this head heartbeats only immediately before submit(). keep_alive exists but run() does not use it. Probe at this head, wall clock jumped by ttl_s + 1 inside A's submit: A returned COMPLETED_UNVERIFIED with submits == 1, and B's overlapping run() also sent (b_sent == [1], outcome COMPLETED_UNVERIFIED). Both workers submitted one item.

2. An unknown pre-submit read-back still sends. check_before_submit skips only on PRESENT. ABSENT and UNKNOWN both fall through to submit(). _read also maps any Exception (including a programming error in read_back) to UNKNOWN. The post-submit rule in the PR, "unknown read-backs never count as missing," is not applied before the send. Probe at this head: read_back returning UNKNOWN, and read_back raising RuntimeError("403 forbidden"), each produced COMPLETED_UNVERIFIED with submits == 1. Fail-closed would refuse to send when absence is not confirmed.

That same except Exception: return ReadBack.UNKNOWN in _read is a new swallow_wide fold. Smoke failed at this head: swallow_wide: 420 (baseline 419); rose in openadapt/transducer_concurrency.py 1 (baseline 0). run-ci, ci, and the required packages-gate check are red because of that smoke failure. This should be fixed as a verdict, not by raising the baseline: if the check cannot confirm the record is absent, do not submit.

3. After a takeover, SimplexTransducer still releases later commits. WorkLeaseHooks.gate claims only on the first commit (a cached claim returns the action unchanged). on_step heartbeats and ignores failure. Probe at this head: worker A released a first save and was granted the lease; after the TTL, B took the item over; A's next act() still returned is_commit is True for a second save, and heartbeat on A's cached claim was False. The episode should wait or abstain once the claim is lost, the same way settle now returns WAIT before a stale send.

Generality gate. Point 1 passes: no application names or branches; keys come from the task. Point 2 fails for the class above. Point 3 (held-out live runs) is not shown, as the PR says.

CI at this head. launcher / run-ci (ubuntu-latest, 3.12) and in-workflow packages / packages-gate are green (packages jobs were correctly skipped; this change is in the root package). Smoke is red on the new fold; the required packages-gate / ci / run-ci checks are red because of smoke. review-verdict was red because there was no review yet. The PR is MERGEABLE; git merge-tree against main (7c30a436) is clean.

I didn't push to this branch, and I won't merge it.

…firmed 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 7b8236d:

- 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.
@abrichr

abrichr commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Grok
Reviewed-Head: 04f86f7

Re-review of the push since my REQUEST CHANGES at 7b8236de07ce. All three blockers, and the smoke verdict-fold failure, are fixed at this head.

1. Fixed. run() now heartbeats and mark_uncertain(..., note="submit in flight") before calling submit(). A send that outlasts the TTL stays PENDING and uncertain, so another worker gets HELD_UNCERTAIN and does not send. Official test test_submit_outlasting_ttl_cannot_be_taken_over covers the default pre-check path. My earlier mid-submit probe, with check_before_submit=False and the wall clock jumped by ttl_s + 1 inside A's submit, now returns COMPLETED_UNVERIFIED with a.submits == 1, b_sent == [], and B's overlapping run() as WAIT / HELD_UNCERTAIN. Same result with the default pre-check on.

2. Fixed. With check_before_submit (the default), a pre-submit read-back sends only on confirmed ABSENT. UNKNOWN, None, and a raising read_back (mapped to UNKNOWN) return UNCHECKED, submits == 0, and release the lease so a later checkable attempt can claim it. Official test test_unconfirmed_absence_before_submit_sends_nothing covers those three cases. Probe at this head: read_back returning UNKNOWN, and read_back raising RuntimeError("403 forbidden"), each produced UNCHECKED with submits_fn == [].

3. Fixed. WorkLeaseHooks.gate renews a held claim before each later commit and, if the heartbeat fails, returns _abstain_action with WORK_LEASE_LOST instead of releasing the commit. Official test test_transducer_stops_releasing_commits_after_claim_is_lost and the earlier probe both show the second act() as abstained with that trap after B takes the item over.

Smoke verdict-fold. SubmitStatus.UNCERTAIN is now SubmitStatus.UNKNOWN. CI smoke at this head reports "Verdict folds OK (2615 baseline folds left)". I get the same locally from packages/flow/scripts/check_verdict_folds.py. The except Exception in _read still returns ReadBack.UNKNOWN (fail-closed, and now it also refuses the send). The submit handler's except Exception assigns SubmitStatus.UNKNOWN and never retries the send.

Tests at this exact head (Linux, Python 3.12, /tmp/rv2787-venv): tests/test_transducer_concurrency.py 31 passed, three runs (2.53 s, 2.21 s, 2.33 s). ruff check is clean on the two touched files.

Generality gate. Point 1 passes: no application names or branches; keys come from the task. Point 2 now passes for the class this PR names (the same item submitted twice: by two workers, after a lost response, or after a crash and takeover) on the settle path and on later transducer commits. Point 3 (held-out live runs) is not shown, as the PR says.

Limitation, not a blocker. The transducer still releases the first commit while the lease is PENDING and not uncertain. It does not send; a harness that actually submits should go through BoundedSettleAndReconcile. Without that, a first save whose send outlasts the TTL can still be taken over.

CI at this head. smoke, launcher / run-ci (ubuntu-latest, 3.12), and in-workflow packages / packages-gate are green. The required ci / run-ci / packages-gate checks are skipped by design because those three jobs succeeded (GitHub treats that skip as passing). review-verdict is still red from my previous review at 7b8236de. The PR is MERGEABLE; git merge-tree against main (7c30a436) is clean.

I didn't push to this branch, and I won't merge it.

@abrichr
abrichr added this pull request to the merge queue Dec 2, 2026
Merged via the queue into main with commit e5b8403 Dec 2, 2026
42 of 43 checks passed
@abrichr
abrichr deleted the feat/transducer-shared-lease-and-async-settle branch December 2, 2026 05:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant