xai / grok-4.7-efficient / high / high effort preferred over deepseek / deepseek-flash / none / 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.
deepseek / deepseek-flash / none / unknown effort answer
## Conclusion
I cannot confirm a **stuck-work**, **duplicate-execution**, or **capacity-accounting** defect from the supplied evidence. The retry/reclaim/interruption paths are, on inspection, carefully fenced. I traced the strongest candidate failure states and each one recovers. Confidence: moderate–high for the paths visible in the snapshot; explicitly bounded by the missing dependencies noted below.
## Traced failure states (all recover)
**(A) Worker claims, commits, then network drops before response → "orphaned lease."** `/claim` commits a `running` row with `claim_token_hash` set and `leased_until = now + lease` (lines 3233–3247). No token is persisted, so the worker cannot heartbeat/complete/release it. Recovery is explicit and bounded:
- Same `worker_id` returns: the per-worker "max 1 unfulfilled claim" query locks the row (3019–3039). If `heartbeat_at/claimed_at` is older than `STALE_SAME_WORKER_LEASE_SECONDS` (150s) it self-heals the row to `pending` and clears all lease columns (3057–3075). A merely-slow-but-alive worker (60s heartbeat cadence) is not misclassified — the constant is documented as comfortably above cadence (143–148).
- A different worker can't see it (row is `running`), but the lease reaper (`scheduler.py`, outside packet) clears it at expiry, so it is not stuck.
- This is the intended designed recovery, not a defect. **No stuck-work.**
**(B) 5xx-after-commit on `/claim` → duplicate execution.** Addressed by the `Idempotency-Key` stash (2909–2943, 3355–3376). A same-worker replay matching `key_sha256 + worker_id + api_key_id` within `_CLAIM_IDEMPOTENCY_TTL_SECONDS` (600s) rotates the claim token **without** incrementing `attempt_count` and returns the same `output_path` (3285–3298, 3215–3232). Non-matching or expired replays fall through to a normal claim. Residual risk: a worker that *omits* the header keeps the pre-existing behavior (documented, 2929–2931) and can lease a second job on a 5xx replay. That is a **known, documented compatibility tradeoff**, not a snapshot defect. **No undisclosed duplicate execution.**
**(C) Duplicate execution after lease expiry.** `/claim` requires `status='pending'` AND (`leased_until IS NULL` OR `leased_until < now`) (3116–3121); the same-worker branch is `FOR UPDATE` (3026). So a second worker cannot claim a live lease, and a late callback with a stale token is rejected by `_validate_claim` (2369–2397: hash + `leased_until > now`) and the terminal short-circuits on heartbeat/checkpoint/refresh_urls (3763–3774, 3839–3854, 4033–4046). **No duplicate execution on retries.**
**(D) Completed job resurrected to `pending`.** Every completion writer clears the full five-column lease (`leased_until`, `claim_token_hash`, `worker_id`, `heartbeat_at`; e.g. 7725–7731, 6309–6316, 6934–6942, 7016–7022). `/fail` and `/release` return terminal jobs as-is before `_validate_claim` (8529–8557, 8658–8687). The comment at 7718–7728 documents the exact historical bug this fixed. **Recovered.**
**(E) Capacity accounting: per-key concurrency cap.** `MAX_ACTIVE_LEASES_PER_API_KEY` counts `status='running' AND leased_until > now` scoped to `claiming_api_key_id` (2995–3023). Completed/failed rows don't count either condition; expired leases drop out automatically. The claim only sets `claiming_api_key_id` in the fresh-claim branch (3242), and the replay branch intentionally leaves it unchanged. **Accounting is self-healing and correct.** No stuck/leaked counter.
**(F) `/complete` backpressure accounting (`worker_complete_slots.py`).** Global + per-muni counters increment inside the condition after acquiring the lock and decrement in `finally` under the same condition (72–110). `wait_for` timeout raises before increment, so no leak on timeout. One residual: a **cancellation** between the unconditional `await asyncio.wait_for(...)` returning and entering the `try/finally` yields would leak a slot. That is a hard-to-trigger edge (cancellation delivery at a single await point inside a request handler), and I cannot see the surrounding cancellation policy for `/complete` in the packet. Flagging as **unconfirmed/likely false positive** unless cancellation is injected there.
**(G) `worker_claim_rate.py` accounting.** In-process monotonic-clock deques per municipality, pruned under a lock; empty munis removed (54–65). It's per-process (restart loses the window — degrades to more permissive, not stuck). `/claim` filters blocked munis rather than 429ing the head-of-line job (3144–3152). **No capacity-accounting defect for the queue lifecycle.**
## Alternatives / discarded hypotheses
- **"Stuck retryable job"** — `/fail` requeues only while `attempt_count < _max_attempts_for(job_type)` (8155–8160); `/release` bounds graceful cycles via `attempt_count - graceful_release_count >= cap` plus the absolute multiplier ceiling `max(cap*5, 15)` (8588–8608, 8695–8704). A flapping worker is bounded, not infinite.
- **"Lost cleanup row on convert-only follow-up IntegrityError"** — explicitly fixed with a savepoint (6848–6910); not a defect.
## Missing evidence / dependencies (uncertainty)
`app.services.scheduler` (the lease reaper, `_worker_lease_reaper_loop`) is **not in the packet**, yet it is the recovery mechanism for categories (A)/(C) — the code comments at 148–156 and 7712–7717 attest to its behavior but I cannot verify it here. Likewise `app.constants.worker_job_types.max_attempts_for`, `app.services.pack_ingest`, `queue_settings.get_effective_worker_queue_enabled`, and `processor.py` finalizers are outside the snapshot. Consequently I cannot prove: the reaper's own attempt-count/terminal-stamp logic, whether the `pack_ingest` zero-observation rollback path re-validates the lease after its internal `db.rollback()`, or the `/complete` cancellation policy needed to settle (F). None of these gaps, based on the snapshot alone, establishes a defect.
## Recommendation (smallest safe change) + focused checks
No source change is warranted by the evidence. If you want to harden the one genuinely *unconfirmed* edge (F), the smallest change is to move the increment inside the `try` or wrap it so any exception after slot acquisition is caught by `finally` — but this is belt-and-suspenders, not a demonstrated bug.
Focused failure-injection checks to convert the "no defect" conclusion into proof:
1. **Orphan-lease reclaim:** claim, drop the response, re-claim with same `worker_id` at <150s (expect 409) and >150s (expect self-heal to `pending`, then re-claim).
2. **Idempotent replay:** claim with an `Idempotency-Key`, replay the same key within 600s (expect same `job_id`, same `review_pack_key`, `attempt_count` unchanged); replay at >600s (expect a normal new claim).
3. **Late callback fencing:** complete a job, then POST `/fail`, `/release`, `/heartbeat`, `/checkpoint`, `/refresh_urls` with the old token (expect idempotent terminal return or 410, no `pending` resurrection).
4. **Concurrency accounting:** verify `MAX_ACTIVE_LEASES_PER_API_KEY` count excludes completed/expired rows and that a replay does not double-count.
5. **Complete-slot leak:** inject `asyncio.CancelledError` at the acquisition boundary in `acquire_complete_slots` and assert `in_flight_counts()` returns to its start value on the next call.
6. **Rate-window accounting:** assert `rate_limited_municipality_ids` prunes empty munis and blocks only at `>= per_min`.
Primary judge's stated reason
A offers the slightly more useful starting point for reproducing repeated stale-reclaim cycles and adding a bounded safeguard, while avoiding B's immediate-retry second-job misdiagnosis. This is a weak, forced preference, not an established material quality gap; A's trigger needs qualification and its cancellation mechanism needs correction. An independent review could reject this balance.
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_f372719100240c827917cfd7b9a560e0d6532e646d7e519dc19f25b5fff44fc4. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.