Skip to content

feat(ledger): claim leases and a reaper for dead workers (D145) - #529

Merged
fazpu merged 7 commits into
mainfrom
feat/claim-leases
Nov 6, 2026
Merged

fazpu merged 7 commits into
mainfrom
feat/claim-leases

Conversation

@fazpu

@fazpu fazpu commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Relaunch plan phase 2 item (a): claim leases and a reaper (UMC design/plan/relaunch-shared-runtime.md phase 2a; reasoning in the UMC relaunch analysis §3 item 3).

What changes

  • Lease on claim. claim_one sets processing_state.lease_until = now() + lease_s (REMEMBERSTACK_WORK_LEASE_S, default 60 s). The claimed attempt number identifies the claim.
  • Renewal. Worker.run_one renews the lease from a background thread every lease_s / 3 while the handler runs (_LeaseRenewal). A refused renewal stops renewing and is logged.
  • Attempt-conditional transitions. renew_lease, complete, every complete_* barrier variant and fail now take attempt and match status = 'running' AND attempts = :attempt. A worker whose attempt no longer matches discards its result and returns the new RunResultOutcome.LEASE_LOST (also exported on worker.run).
  • Reaper. WorkLedger.reap_expired_leases(deployment_id, stages) moves expired running rows on those stages to pending (due now, last_error = 'lease expired: …'), or to dead_letter once attempts >= max_attempts (claiming requires attempts < max_attempts). Worker.reap_expired_leases runs it for the worker's registered stages, announces requeued rows through the queue port and runs the terminal-failure finalizer for dead-lettered ones. SelfHostWorkerLoop.drain_due calls it at most once per fallback-poll interval.
  • Migration p9_43_0064. Adds lease_until, a running ⇒ lease_until IS NOT NULL CHECK, and ix_procstate_running_lease. Rows already running get an expired lease, so the first sweep recovers anything a killed worker left behind today.
  • Corpus. New D145 (and a "Refined by D145" note on D67); orchestration design §6 "Claim leases and the reaper"; schema design §2 column, index, claim/reaper queries and decision map; packaging §3 queue-state table row.
  • Docs. Configuration reference (REMEMBERSTACK_WORK_LEASE_S), operating (what happens when a worker dies mid-item), observability (lease_lost).

Cost recording is attempt-conditional too: RecordCall carries the claimed attempt and record_call refuses a call from an attempt that no longer holds the row, so a late call cannot land on (and deduplicate) a newer attempt's calls.

Tests

src/tests/workers/test_claim_leases.py (real Postgres):

  • a claim records its lease;
  • a stale attempt cannot renew, complete or fail after its row was reaped and reclaimed; the new attempt can;
  • the reaper requeues expired rows, dead-letters exhausted ones, leaves live leases and other stages alone;
  • the worker announces requeued rows and finalizes dead-lettered ones;
  • the worker renews while a handler outlives the lease;
  • a worker whose claim was taken back reports lease_lost;
  • kill-mid-task: a subprocess worker is SIGKILLed inside its handler; while alive its lease is renewed (nothing reaped after 2.5 leases); after the kill the reaper requeues the row and another worker completes it as attempt 2.

Local runs (Postgres 19beta3 image from Dockerfile.postgres): the new file, test_work_ledger.py, test_selfhost_queue.py, test_backfill.py, test_operations.py, test_d122_selection.py, test_migrations.py; ruff, ruff format, pyright, lint-imports, test inventory, docs truth check.

Rule 4 (D56)

No ingestion keyed input, chunking, extraction or reuse identity changes. Only claim bookkeeping on processing_state.

🤖 Generated with Claude Code

https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm

fazpu added a commit that referenced this pull request Nov 6, 2026
…tional

Address Codex round 1 on #529: the worker loop now checks the reaper
interval between tasks of a long drain; record_call takes the claimed
attempt and refuses a call from an attempt that no longer holds the row,
so a late call can never land on (and deduplicate) a newer attempt's
calls; the renewal test sweeps after the first lease expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 1 (gpt-6.1-sol, max)

VERDICT: REQUEST_CHANGES

  1. Major — a busy worker can stop reaping indefinitely.
    queue.py:122 checks the reaper throttle only before entering the drain loop. With continuous pending work and tokens replenishing between tasks, that loop never exits, so expired claims remain running. A deterministic reproduction completed ten tasks over 110 simulated seconds with only the initial sweep despite a five-second interval.
    Simplest fix: apply the existing throttled check between tasks inside the drain loop too.

  2. Major — late provider usage corrupts the replacement attempt’s accounting.
    The meter binds only the processing ID at base.py:366; work_ledger.py:1036 attributes usage to the row’s current attempt. After reaping attempt 1 and claiming attempt 2, I reproduced attempt 1’s late charge being stored under attempt 2. Attempt 2’s actual charge with the same call key was then silently deduplicated. This contradicts orchestration §6’s promise that lost-attempt calls retain their own attribution.
    Simplest fix: carry the claimed attempt through the existing meter and record_call path, preserving that attempt for late usage.

  3. Minor — the standalone renewal test does not prove renewal.
    test_claim_leases.py:303 checks eventual success without sweeping or observing lease advancement. Completion intentionally accepts an expired lease before reaping. I disabled renewal in memory and this test still passed.
    Simplest fix: observe the lease advancing while the handler runs, or sweep after its original expiry and assert it remains claimed.

All 33 focused tests passed, including the SIGKILL test. The populated migration downgrade/re-upgrade, expired backfill, and CHECK validation also passed. Completion and failure variants pass the claimed attempt; I found no missing guards there. No reuse identities changed. Files were not modified.

@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Dispositions for Codex round 1 (fixed in f44dab8)

  1. Major, reaping stops during a long drain — fixed. drain_due checks the reaper interval before every claim, not only on entry (_reap_if_due).
  2. Major, late usage lands on the replacement attempt — fixed, with the strict variant: RecordCall now carries the claimed attempt, the meter binds the claim, and record_call refuses a call unless the row is running at that attempt. I did not record late calls under the lost attempt's number: a killed worker's in-flight calls are never recorded either, and the plan item makes the claim's transitions attempt-conditional, so the rule stays uniform. Orchestration §6 and D144 now say this explicitly (the earlier sentence promising lost-attempt attribution is replaced). The stale-attempt test covers both the refusal and attempt 2 recording the same call key.
  3. Minor, renewal test — fixed. The handler sleeps three leases, then sweeps; the test asserts nothing was reaped and the row completes at attempt 1.

@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 2 (gpt-6.1-sol, max)

VERDICT: APPROVE

No new blocker, major, or minor findings. All three round‑1 fixes are verified, and the implementation agrees with D144 and the updated designs/docs.

Validation: 59 focused tests passed, including SIGKILL recovery. Populated migration upgrade/downgrade checks, selected D56/D140 reuse checks, and lint also passed.

No files modified.

@fazpu
fazpu marked this pull request as ready for review November 6, 2026 15:43
fazpu added a commit that referenced this pull request Nov 6, 2026
…tional

Address Codex round 1 on #529: the worker loop now checks the reaper
interval between tasks of a long drain; record_call takes the claimed
attempt and refuses a call from an attempt that no longer holds the row,
so a late call can never land on (and deduplicate) a newer attempt's
calls; the renewal test sweeps after the first lease expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu
fazpu force-pushed the feat/claim-leases branch from a567879 to edf945f Compare November 6, 2026 17:01
@fazpu fazpu changed the title feat(ledger): claim leases and a reaper for dead workers (D144) feat(ledger): claim leases and a reaper for dead workers (D145) Nov 6, 2026
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Rebased onto main 93bf659 (library seams #531, per-database upgrades #532). The only conflict was the end of decisions.md; D144 is now the library-seams decision, so this PR's decision is renumbered D145 (all references, anchors and the catalog-contract key updated). Code merged cleanly: the new named claim (_CLAIM_SELECT_NAMED) shares _CLAIM_START, so run_task claims get a lease too. Codex-approved content is otherwise unchanged. Local: claim-lease, work-ledger, selfhost-queue, telemetry, profiles (incl. two-deployment contexts) and operations tests pass; full workers+spine suite passed before the rebase (1031 passed, 2 xfailed).

fazpu added a commit that referenced this pull request Nov 6, 2026
…tional

Address Codex round 1 on #529: the worker loop now checks the reaper
interval between tasks of a long drain; record_call takes the claimed
attempt and refuses a call from an attempt that no longer holds the row,
so a late call can never land on (and deduplicate) a newer attempt's
calls; the renewal test sweeps after the first lease expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu
fazpu force-pushed the feat/claim-leases branch from edf945f to 4efd3ff Compare November 6, 2026 17:24
@fazpu fazpu changed the title feat(ledger): claim leases and a reaper for dead workers (D145) feat(ledger): claim leases and a reaper for dead workers (D144) Nov 6, 2026
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Rebased onto main 9d6e9e8 (#534 moved the library-seams decision to D147), so this PR's decision is D144 again; references and anchors updated. No code change. Targeted tests pass locally; CI re-running.

fazpu added a commit that referenced this pull request Nov 6, 2026
…tional

Address Codex round 1 on #529: the worker loop now checks the reaper
interval between tasks of a long drain; record_call takes the claimed
attempt and refuses a call from an attempt that no longer holds the row,
so a late call can never land on (and deduplicate) a newer attempt's
calls; the renewal test sweeps after the first lease expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu
fazpu force-pushed the feat/claim-leases branch from 4efd3ff to 68d50ef Compare November 6, 2026 18:18
@fazpu fazpu changed the title feat(ledger): claim leases and a reaper for dead workers (D144) feat(ledger): claim leases and a reaper for dead workers (D145) Nov 6, 2026
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Final decision numbering from the orchestrator: this PR is D145 (library seams D147 on main; D144 stays unused). References updated; no code change.

fazpu and others added 7 commits November 6, 2026 21:45
A claim now records lease_until; the worker renews it every third of the
lease while the handler runs. Renewal, complete and fail are conditional on
the claimed attempt, so a worker whose claim was taken back discards its
result (lease_lost) instead of finishing a newer attempt. Each worker loop
sweeps its stages for expired running rows: rows with attempts left return
to pending and are announced; rows at max_attempts are dead-lettered and
finalized. Includes a kill-mid-task test (SIGKILL inside the handler).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
…tional

Address Codex round 1 on #529: the worker loop now checks the reaper
interval between tasks of a long drain; record_call takes the claimed
attempt and refuses a call from an attempt that no longer holds the row,
so a late call can never land on (and deduplicate) a newer attempt's
calls; the renewal test sweeps after the first lease expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
…eams) merged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu
fazpu force-pushed the feat/claim-leases branch from 05d46a2 to 72b49f7 Compare November 6, 2026 20:47
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Rebased onto main b64a1a2 (#537). #537 added its own p9_42_0063, so the claim-lease migration is now p9_43_0064 chained after it; head assertions (database_reset, test_migrations, CI upgrade gate) updated. Catalog CHECK count 118→119 still holds on top of #537. Local: claim-lease, work-ledger and the migration lifecycle test pass.

@fazpu
fazpu merged commit f835c24 into main Nov 6, 2026
22 checks passed
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