xai / grok-4.7-efficient / high / high 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 / high / high effort answer
The queue does not recover a job whose claim response is lost and whose worker keeps polling without a stable Idempotency-Key. The stale-lease self-heal requeues and re-claims that job in the same transaction with no retry ceiling, so the lease never expires and the attempt budget never trips.
**Conclusion.** The lost-response path documented at `worker_queue.py:142-156` becomes an unbounded reclaim loop. A claim can commit and still never deliver `claim_token`. The worker cannot heartbeat, complete, or release. The next `/claim` for that `worker_id` finds the live lease (`worker_queue.py:3028-3044`). Within 150 seconds it returns 409 (`worker_queue.py:3057-3067`). After 150 seconds the stale branch sets the row back to `pending` and clears the lease columns, but it does not read `attempt_count` and does not call `_max_attempts_for` or `_graceful_release_absolute_ceiling` (`worker_queue.py:3068-3086`). The same transaction then `SELECT … FOR UPDATE SKIP LOCKED` and re-claims that row: `attempt_count` increments and `leased_until` / `heartbeat_at` are refreshed (`worker_queue.py:3119-3167`, `3240-3248`). PostgreSQL does not skip a row this transaction already holds, and the pending update is invisible to other workers until commit, so the healed job is not offered to anyone else in between.
Each cycle also calls `record_claim_for_municipality` after commit (`worker_queue.py:3538-3551`) and keeps one API-key concurrency slot occupied (`leased_until > now` at `worker_queue.py:3009-3016`). `/fail` and `/release` both stop at a ceiling (`worker_queue.py:8164-8176`, `8684-8734`). `/release` even documents that a claim/release cycle with no charged failure must have an absolute ceiling or it loops forever (`worker_queue.py:8593-8604`). Stale reclaim is that same shape and has no ceiling. While this worker polls, the supplied code never terminal-fails the job and never lets the lease expire, so an expiry-based reaper cannot see it either.
A stable Idempotency-Key within 600 seconds does recover: replay rotates the token and does not increment `attempt_count` (`worker_queue.py:3046-3056`, `3217-3231`, `305-317`). Workers that omit the header are explicitly on the old path (`worker_queue.py:2941-2943`).
**Smallest safe change.** In the stale branch, before resetting the row to `pending`, if `attempt_count >= _graceful_release_absolute_ceiling(job.job_type)`, terminal-fail it with the same lease clear, footage-reuse restore, and media stamp `/release` already uses at the ceiling (`worker_queue.py:8726-8783`), audit, commit, and return `None`. Do not fall through into a new claim. Use the graceful absolute ceiling, not `_max_attempts_for` alone, so a few lost responses are not treated as real processing failures. No new column or response shape.
**Secondary capacity leak.** `acquire_complete_slots` increments `_global_in_flight` / `_muni_in_flight` inside the `asyncio.wait_for` task (`worker_complete_slots.py:78-88`) and decrements only after `wait_for` returns (`worker_complete_slots.py:99-109`). The timeout path raises and does not decrement (`worker_complete_slots.py:92-96`). If cancellation lands after the increment, during `Condition.__aexit__`, the slot stays taken and a cancelled lock release can wedge later acquires. Increment only after `wait_for` succeeds, and decrement in a `finally` that runs if and only if that increment happened.
**Discarded.** Idempotent `/complete`, `/fail`, and `/release` guards do stop completed-to-pending resurrection. `SKIP LOCKED` does stop two workers taking the same pending row. Claim-rate counts are not reversed on later release; that matches "successful claims," not a leak. The API-key cap is checked before replay/stale-heal (`worker_queue.py:2999-3026`), so a full cap delays self-heal, but the count itself drops when `leased_until` passes; that is delayed recovery, not the unbounded loop. Holding the job row lock across `/complete` storage I/O can stall heartbeats, but a finished or rolled-back request releases it.
**Missing.** `max_attempts_for` and the lease reaper live outside this packet (`app.constants.worker_job_types`, `scheduler.py`). If the worker stops polling, this code will not select a `running` row whose lease has already expired (`worker_queue.py:3119-3135`). Recovery then depends entirely on that reaper. Stale heal is also same-`worker_id` only; a restart that changes `worker_id` cannot clear the orphan here.
**Checks.** Drop the claim response and poll `/claim` with no Idempotency-Key: 409 until 150 seconds, then reclaim with `attempt_count` increased and `leased_until` refreshed; at the absolute ceiling the job must be `failed`, lease columns cleared, media not left `processing`, and a later claim must not re-lease it. Control: the same loss with a stable Idempotency-Key inside 600 seconds replays once, does not increment `attempt_count`, and does not terminal-fail. Separately, cancel `acquire_complete_slots` after a slot is taken and assert `in_flight_counts()` returns to zero.
Confidence: high on the stale-reclaim loop and that this code does not recover it while that worker polls. Medium on how often the complete-slot cancel window hits; the missing compensating decrement is structural.
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
Weak, forced preference for A: its primary recommendation more directly bounds the repeated-interruption failure it analyzes and specifies reusable cleanup plus a terminal-state check. This is not an established material quality gap; B's broader capacity coverage and A's overstated failure and cancellation claims make independent rejection of this 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_f603a661fc1c01e50be98fa835ee16e5bcd8827c505242622a338ec7ae29a4cf. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.