xai / grok-4.7-efficient / low / low effort preferred over cursor / composer-2.5 / Composer 2.5 default / unknown effort · close win.
Primary judge: Sol 6.1, requested Low. Effective provider effort and internal attempts were not verified. A close win is still a scored preference; it does not establish a material defect.
Reviewed public evidence
Task goal
Review the worker-queue claim and completion lifecycle for stuck work, duplicate execution, or incorrect capacity accounting after retries and worker interruption. Trace an exact plausible failure state through the provided code, identify whether the queue recovers, and recommend the smallest safe change plus focused failure-injection checks.
xai / grok-4.7-efficient / low / low effort answer
The queue does not self-heal a `/complete` that waits for a slot while holding the job row lock. Under a completion storm the worker’s heartbeats cannot refresh the lease, the wait ends in 503, the retry is 410, and the row stays `running` until an external reaper.
**Failure state.** Job 42 is `running`, `attempt_count=1`, `leased_until` still in the future, worker heartbeats every 60s. Other `/complete` calls already hold every `WORKER_COMPLETE_MAX_CONCURRENT` slot (`worker_complete_slots.py` 65–83).
1. `complete_job` locks job 42 with `FOR UPDATE` and `_validate_claim` succeeds (`worker_queue.py` 7823–7936).
2. PDF-full, convert-only, mdb, and review-pack then call `_complete_with_tenant_slots` without releasing that lock (7987–8096). Only the Apple Vision branch rollbacks first (8016).
3. `acquire_complete_slots` waits up to `WORKER_COMPLETE_SLOT_WAIT_TIMEOUT_S` (65–93). Heartbeat for job 42 also takes `FOR UPDATE` (3761–3776) and blocks behind that wait, so `leased_until` is not extended (3779).
4. While the slot pool stays saturated, each Mac 5xx retry repeats steps 1–3 and keeps pinning the row for the whole wait. Heartbeats never land. The lease expires.
5. The in-flight wait then raises 503 (`worker_queue.py` 5980–6004). The retry calls `_validate_claim`, sees `leased_until <= now`, and gets 410 (2385–2397). The worker is specified to stop on 410.
6. Claim will not take the row: status is still `running`, and the same-worker check requires `leased_until > now` (3028–3043, 3119–3120). `/fail` and `/release` also 410 before any requeue (8544–8564, 8686).
Recovery is not in these three files. Comments point at `scheduler.py`’s lease reaper, which is outside this packet. Until that reaper runs, the job is stuck and the API key still counts the expired lease only after `leased_until` passes (3009–3015), so the stuck row itself does not hold the concurrency cap — it simply never returns to `pending`.
**Smallest safe change.** After the initial claim check in `complete_job`, snapshot the fields the branches need and `await db.rollback()` before `_complete_with_tenant_slots`, matching the Apple Vision path at 8016. Inside the slotted helper, re-lock the job and call `_validate_claim` before any mutation (AV persist already does this at 6419–6432). Do not clear the token on the 503 path.
Also make slot acquire cancellation-safe. The increment is inside `_wait_and_enter` (79–86), but the decrement runs only after `wait_for` returns and the context is yielded (92–109). A client disconnect or `wait_for` timeout that cancels the waiter after the increment never enters that `finally`, so `_global_in_flight` / `_muni_in_flight` stay high until process restart and later completes 503 forever. Roll the increment back on `CancelledError` before re-raising.
**Discarded.** Idempotent claim replay and `SKIP LOCKED` prevent a second lease of the same job when `Idempotency-Key` is present (3028–3056, 3162–3168). Graceful release’s `attempt_count - graceful_release_count` discount (8689–8703) does not apply to `/fail` (8164), so interruptions still burn the real-failure budget — real, but it terminal-fails rather than sticking a live lease. A 429-before-replay at `MAX_ACTIVE_LEASES_PER_API_KEY` (3009–3026 vs 3042–3056) can block stale-lease self-heal, but only at the cap.
**Missing.** `get_db` transaction lifetime, `WORKER_COMPLETE_SLOT_WAIT_TIMEOUT_S`, and the reaper are outside the packet. If the dependency did not hold the transaction open across the slot wait, heartbeats would not stall; the slot-leak bug would remain.
**Checks.** Saturate complete slots, start `/complete`, and assert a concurrent heartbeat commits without waiting out the slot timeout. Cancel a waiter after the counter increments and assert `in_flight_counts()` returns to baseline. After a 503, assert the job is still `running` with the same `claim_token_hash` and a future `leased_until`, and that the next `/complete` is not 410.
cursor / composer-2.5 / Composer 2.5 default / unknown effort answer
## Conclusion
The claim/complete lifecycle is largely self-healing for HTTP retries, terminal idempotency, and lease-based concurrency, but one **in-packet** path can produce **duplicate work** and skew **attempt/capacity accounting**: same-`worker_id` **stale-lease self-heal** after 150s without `heartbeat_at`/`claimed_at` activity, while the original worker may still be running. Multi-process deployments also **under-enforce** per-municipality claim throughput and `/complete` concurrency because those counters are **process-local**.
**Confidence:** High for the stale-heal duplicate-work trace (logic is explicit in `worker_queue.py`). Medium for multi-replica capacity drift (`worker_claim_rate.py`, `worker_complete_slots.py`). Low for lease-reaper behavior (referenced but not in packet).
---
## Exact plausible failure trace (stuck → duplicate → accounting)
**Setup:** Worker `W` claims job `J` (`status=running`, `leased_until` ≈ now+25–60m, `heartbeat_at=claimed_at=now`, `attempt_count` incremented). `W` keeps processing locally (long download, paused debugger, heartbeat bug, or API unreachable) and sends **no** `/heartbeat` for **>150s**.
**Step 1 — Stale heal on next `/claim` from same `worker_id`:**
`existing_job` is selected `FOR UPDATE` with live lease. `last_activity = heartbeat_at or claimed_at`. Because wall clock advanced >150s with no new heartbeat, `is_stale` is true. The handler sets `J` back to `pending`, clears `worker_id`, `claim_token_hash`, `leased_until`, etc., audits `WORKER_CLAIM_STALE_LEASE_RECLAIMED`, and **does not** decrement `attempt_count` (release/fail semantics don’t apply here).
**Step 2 — Same transaction claims again:**
`J` (or another job) is claimed fresh: `attempt_count` **+1 again**, new `claim_token`, possibly new `output_path` (`…/attempt-{n}` when `n` increased).
**Step 3 — Duplicate execution:**
`W` still believes it owns `J` with the **old** token and old `review_pack_key`. A second claimant (often the same `W` on its next poll) runs the same media job in parallel. First `/complete` may succeed; the other gets **410** (`lease_expired_or_invalid`) or writes to a **different attempt prefix** if it completes before conflict detection.
**Capacity accounting after retries/interruption:**
| Mechanism | Effect |
|-----------|--------|
| Per-API-key cap (`claiming_api_key_id`, `status=running`, `leased_until>now`) | Healed job drops out immediately → slot freed **before** duplicate claim; cap can **under-count** real in-flight work (ghost worker + new lease). |
| Per-muni claim rate (`record_claim_for_municipality` after commit, not on idempotent replay) | **Second successful claim counts again** → throughput budget burned twice for one logical run. |
| `attempt_count` | **+1 per claim**, including re-claim after stale heal → retries/interrupts inflate attempts without a matching `/fail`. |
| `/complete` slots | Unaffected by stale heal; duplicate completes compete for slots separately. |
**Does the queue recover?** **Partially.** `worker_id` is unblocked; `J` returns to the pool; terminal `/complete`/`/fail`/`/release` guards prevent resurrecting `completed`/`failed`/`cancelled` rows. **Recovery does not guarantee single execution** or correct attempt/rate accounting when a live worker outlives stale heal.
**What works (contrasting evidence):** Idempotent `/claim` with `Idempotency-Key` (advisory lock + token rotation, 600s TTL); bound `/complete` sets `status=completed` and clears lease (avoids reaper re-queue duplicate); terminal short-circuit on `/fail`/`/release`/`/heartbeat`; `SKIP LOCKED` prevents two workers claiming the same row in one instant; per-key concurrency excludes expired leases (`leased_until <= now`).
---
## Smallest safe change (recommendation)
**Tighten stale same-worker heal so it cannot return a **still-leased** job to `pending` while `leased_until > now`**, unless the heal is explicitly the “orphaned claim” case (client never had a live session).
Practical minimal variant aligned with existing comments (Mys-MacBook incident): **only stale-heal when `heartbeat_at` is still the claim-time stamp *and* there has never been a successful client `/heartbeat`** (e.g. compare `heartbeat_at == claimed_at` and optional monotonic `heartbeat_count` if added later), **or** require `leased_until <= now` for heal when any post-claim heartbeat occurred.
Today, server sets `heartbeat_at` at claim, so “no client heartbeat” is indistinguishable from “client heartbeating” without a separate flag—**smallest incremental fix:** add `config_json._claim_client_heartbeat_seen: true` on first successful `/heartbeat`, and stale-heal only when that flag is absent **and** `(now - claimed_at) > STALE_SAME_WORKER_LEASE_SECONDS`. Orphaned-response workers never heartbeat → still heal at 150s. Live workers that heartbeat at 60s → never heal while lease valid.
If a one-line behavior change is unacceptable, **smallest operational mitigation without schema:** raise `STALE_SAME_WORKER_LEASE_SECONDS` above worst-case first-heartbeat delay (weak; does not fix heartbeat outages).
---
## Focused failure-injection checks
1. **Stale heal vs live worker:** Claim job; block `/heartbeat` for 151s while a background task simulates work; call `/claim` same `worker_id`; assert whether job returned to `pending` and `attempt_count` increased; assert first worker `/complete` → 410 and whether second run created a second `output_path` attempt directory.
2. **Orphan claim (intended heal):** `/claim` commit; drop HTTP response before client reads `claim_token`; no heartbeats; after 151s same `worker_id` `/claim` → should unblock without leasing a second job (idempotency key) or heal + single logical attempt.
3. **Idempotency TTL:** Replay `/claim` with same `Idempotency-Key` at 601s with job still `running` → must not rotate token under active worker (TTL fall-through); document expected 409 vs new claim.
4. **Per-key concurrency:** Fill 64 `running` leases; claim 65th → 429; fail/release one → next claim succeeds; verify count ignores `pending` rows with stale `claiming_api_key_id`.
5. **Multi-replica claim rate (if applicable):** Two API processes; hammer `/claim` for one muni; assert whether effective limit is `N` or `2N` per minute.
6. **`/complete` slot timeout:** Saturate `WORKER_COMPLETE_MAX_*`; assert 503 `complete_concurrency_limited`, worker retry, single terminal completion (idempotent duplicate `/complete`).
7. **Success then `/fail` fallback:** Complete job; `/fail` with stale token → `WORKER_FAIL_DUPLICATE`, status stays `completed`.
---
## Alternatives / likely false positives
- **Lease reaper** (scheduler, outside packet) may requeue expired `running` jobs—could duplicate stale-heal if both fire; interaction **not verified** here.
- **409 `worker_already_owns_job`** within 150s is intentional, not stuck work.
- **In-memory rate/slot limits** are design tradeoffs for single-process or low replica count; false positive as “bug” if deploy is strictly one API instance.
- **Zip `prepare_zip_manifest` double `commit`** (lines ~4609–4625 in packet) is a separate consistency smell, not analyzed as queue lifecycle.
---
## Missing evidence / consequence
- `_worker_lease_reaper_loop()` and when it clears `running` vs `pending` — cannot fully sign off on stuck-`running` recovery without reaper.
- Mac worker behavior on 410 vs retry on `/complete` — affects whether duplicate uploads retry safely.
- Whether production runs **multiple** API replicas — determines severity of claim-rate and complete-slot drift.
**Next useful action:** Implement the `_claim_client_heartbeat_seen` (or equivalent) gate on stale heal plus test (1); run SOL/cluster review if changing lease semantics is production-critical.Primary judge's stated reason
Forced weak preference for B: its lock-release/re-lock recommendation and concurrent-heartbeat check provide a more directly actionable way to prevent completion admission from obstructing lease renewal. This is not an established material quality gap; A's broader coverage and B's overstated starvation narrative make independent rejection of the preference reasonable.
This reason is the judge's assessment. No independent factual-defect finding is asserted by this record.
Battle wave: bc72a6bd-1168-4bad-b5a9-fbf90203e5d7. Pair: brp1_33360b959761707258b49af9eb00fa016bdc34c7b4d8222e752b6f809ecd7a59. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.