openai / gpt-6.1-sol / high / high effort preferred over xai / grok-4.7-efficient / low / low effort · clear 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.
openai / gpt-6.1-sol / high / high effort answer
## Conclusion
**The snapshot establishes retry-accounting and admission defects, plus a plausible ZIP completion race that can overwrite terminal failure.** Completion-slot acquisition also has a cancellation ownership gap whose reproducibility depends on the Python runtime.
Independent, read-only assessment; no external files or tools used.
Paths below refer to:
- `[REDACTED: private project name]/backend/app/routers/worker_queue.py`
- `[REDACTED: private project name]/backend/app/services/worker_claim_rate.py`
- `[REDACTED: private project name]/backend/app/services/worker_complete_slots.py`
## Findings and focused fixes
### 1. ZIP completion can validate cached claim state after another request terminalizes the job
**Confidence: high under the documented session behavior.**
Exact plausible trace:
1. Request A starts `/zip-complete` with a valid token. It loads the running job, validates it, and commits before checking storage (`worker_queue.py:5062–5114`).
2. The source explicitly documents `expire_on_commit=False` (`5065–5069`), so A retains its loaded running job and token.
3. Pause A’s sentinel check. Request B calls `/fail` with the same valid token and `retryable=False`. B commits `status="failed"` and clears the lease (`8549–8572`, `8169–8183`).
4. A resumes and executes another `SELECT … FOR UPDATE`. That query lacks `populate_existing=True` (`5128–5140`). SQLAlchemy can return A’s already-loaded instance without refreshing its attributes.
5. Consequently, the terminal and token checks inspect cached running state (`5141–5163`). A then materializes children and commits the job as completed (`5445–5508`).
**Recovery:** this is not merely delayed recovery: A can overwrite B’s terminal result and publish children. The intended phase-B fence is ineffective when it reads cached state.
**Smallest safe change:** add `.execution_options(populate_existing=True)` to the phase-B job query before checking status, receipt, and token. The canonical PDF media query already uses this pattern (`5843–5853`).
**Injection check:** pause `storage.exists`, terminal-fail the ZIP job in another session, then resume. Expect 410, unchanged failure, and no children. Repeat with release/reclaim and verify the old token cannot complete the new claim.
### 2. API-key admission blocks legitimate claim replay and is not atomic
**Confidence: high for ordering; concurrent overshoot assumes no unseen database enforcement.**
- The active-lease cap runs **before** idempotent replay detection (`worker_queue.py:2992–3015` versus `3030–3047`).
- At the cap, a committed claim whose response was lost receives 429 on retry—even with the matching idempotency key. The retry should return an existing lease, not consume capacity.
- Concurrent claims by different worker IDs can both count `cap−1`, then claim different rows and commit `cap+1`. The advisory lock is per worker and only taken when a header is present (`2964–2990`); it does not serialize API-key admission.
- Without the header, two requests for a previously idle worker can also both observe no existing lease and claim separate jobs (`3023–3029`, `3154–3164`).
**Recovery:** cap counts drop when leases expire or complete. However, an expired **running** job is not claimable here: selection requires pending status (`3114–3120`). Actual job recovery requires the external reaper.
**Smallest safe changes:** handle matching replay before fresh-admission limits; serialize same-worker admission regardless of header; serialize per-key count-and-fresh-claim admission.
**Injection checks:** drop a claim response at cap and retry its key; concurrently admit two workers from `cap−1`; concurrently claim twice with one headerless worker ID.
### 3. Completion slots have a cancellation gap and a lock-order stall
**Confidence: high for the ownership gap and lock inversion; runtime-dependent for cancellation reproduction.**
**Counter ownership gap:** `_wait_and_enter()` increments counters inside the child awaited by `asyncio.wait_for`, but the decrementing `finally` starts only after that await returns (`worker_complete_slots.py:74–100`).
On runtimes where cancellation propagates after the child acquires capacity but before its caller resumes, cancellation bypasses the decrement. With a global cap of one, the resulting state is **one counted completion, no owner**. Later completions time out indefinitely.
**Recovery:** no production reconciliation is shown. Process restart resets these process-local counters.
**Smallest safe change:** cover acquisition and execution with one `try/finally`; set an acquired flag alongside the increments and perform cancellation-safe cleanup.
**Injection check:** cancel exactly after incrementing but before acquisition returns. Assert both counts return to zero and another completion enters. Run against the deployed Python version.
**Lock-order stall:** most completion branches hold the job row lock while awaiting a slot (`worker_queue.py:7811–7820`, `8051–8071`). AV completion releases that lock, acquires a slot, then reacquires the job during persistence (`8016–8022`, `6366–6372`).
With one slot:
- AV request A owns the slot.
- Duplicate request B locks A’s job and waits for the slot.
- A waits for B’s job lock.
This stalls until B’s slot timeout and transaction cleanup.
**Smallest safe change:** do not wait for completion capacity while holding job locks. Follow AV’s snapshot/revalidation pattern.
**Injection check:** pause AV before final persistence, start a duplicate completion, then resume. Verify there is no slot→row / row→slot cycle.
### 4. Graceful interruptions still consume later failure budgets
**Confidence: high.**
Let the job’s real-failure cap be `C > 1`:
1. Perform `C−1` graceful claim/release cycles. Raw attempts become `C−1`, graceful releases become `C−1`.
2. Claim again: raw attempts become `C`.
3. Report the **first genuine retryable failure**.
`_record_failure` compares raw attempts with `C` and terminal-fails the job (`worker_queue.py:8155–8169`). Non-graceful release likewise compares raw attempts (`8703`). Only graceful release subtracts the graceful count (`8694–8700`).
**Recovery:** the job becomes terminal prematurely; ordinary queue retry does not recover it.
**Smallest safe change:** share an effective-attempt helper across genuine-failure checks, subtracting the validated graceful count while preserving raw attempts and the separate absolute ceiling. Reaper accounting needs verification outside this packet.
**Injection checks:** mix graceful interruptions with `/fail`, `/complete(status="failed")`, and `release(reason="attempt_failed")`; verify terminalization depends on genuine failures, with the absolute graceful ceiling still enforced.
### 5. Municipality throughput admission is a check/record race
**Confidence: high.**
The claim path reads blocked municipalities before selection, but records usage only after commit (`worker_queue.py:3147–3151`, `3530–3537`). These operations take separate locks (`worker_claim_rate.py:50–66`, `74–84`).
At usage `limit−1`, several requests can all pass and claim different jobs. Counters are also process-local, so multiple API processes have separate budgets.
**Recovery:** timestamps age out after the rolling window. This is excess admission, not permanent queue blockage.
**Smallest safe change:** use atomic post-selection admission—the existing `allow_claim_for_municipality` provides the local check-and-record operation (`97–108`)—with explicit reservation rollback on failed claims. A fleet-wide hard bound requires shared storage.
**Injection checks:** synchronize claims at `limit−1`; verify bounded admission, rollback handling, replay exclusion, and continued draining of another municipality.
## Existing protections and uncertainty
- Normal completion and terminal callbacks clear/fence leases; the old completed→pending release resurrection is **not** established on these guarded paths (`worker_queue.py:7718–7732`, `8529–8548`, `8663–8676`).
- The scheduler/reaper, database constraints, dependency transaction cleanup, storage-helper side effects, and deployed Python version are outside the packet. Their recovery or enforcement behavior cannot be confirmed.
- Start with the ZIP two-session race test and forced slot-acquisition cancellation; these distinguish terminal-state corruption from capacity leakage directly.
MATERIAL_EVIDENCE_CONFLICT: Graceful release promises not to consume the real-failure budget (`worker_queue.py:8624–8632`), but later failure and non-graceful release checks use raw claim counts (`8159–8160`, `8703`).
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.
Primary judge's stated reason
A provides the more reliable basis for remediation: its additional supported terminal-state race has a small, specific correction, and its recovery claims distinguish bounded stalls, premature terminalization, and process-local capacity leakage. This is a clear comparative advantage in failure-trace correctness and actionable coverage, rather than a preference based on presentation or length.
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_5484e0f341aa319ef219e2aa4c6228aa3ccaee3132fecdadd9c284ed1a2a50b4. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.