← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / low / low effort preferred over xai / grok-4.7-efficient / high / high 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 / low / low effort answer

## Independent assessment

**The snapshot establishes retry-accounting and claim-admission defects. Completion interruption also exposes a plausible slot leak.** Analysis was direct and read-only.

### 1. Lost claim responses cannot recover at the API-key capacity limit — high confidence

Exact state:

1. A key already holds `MAX_ACTIVE_LEASES_PER_API_KEY - 1` live leases.
2. Worker W claims J with an idempotency key. The transaction commits, bringing the key to its limit, but the response is lost (`worker_queue.py:3529–3537`).
3. W retries the identical request.
4. The API-key count returns the limit and raises 429 **before** the same-worker lookup and idempotency replay (`2992–3014`, `3024–3046`).
5. W never obtains J’s token. The same ordering also prevents the 150-second stale-lease repair.

**Recovery:** other jobs completing can unblock replay; otherwise J must expire and depend on the external reaper. Expiry removes it from the capacity count, but `/claim` itself selects only pending rows (`3117–3121`), not expired running rows.

**Smallest safe change:** identify and authorize replay before applying fresh-claim capacity admission. Apply the cap only to operations that add a live lease. Serialize fresh admission per API-key principal: the current count-then-claim sequence is also racy across different workers, whose advisory locks differ (`2982–2986`).

### 2. Graceful interruption credits disappear on the next genuine failure — high confidence

Exact state, using a job type with retry cap C:

1. J undergoes C graceful claim/release cycles.
2. Raw `attempt_count = C`; `graceful_release_count = C`; each graceful release correctly requeues using the effective count (`8687–8702`).
3. The next claim increments raw attempts to C+1 (`3241`).
4. Its first genuine retryable failure invokes `_record_failure`, which compares **raw** attempts with C and terminal-fails J (`8158–8170`).

The default `reason="attempt_failed"` release likewise ignores accumulated graceful credits (`8703–8704`).

**Recovery:** none in these endpoints; J is terminal. This contradicts the stated graceful-interruption policy (`8625–8631`).

**Smallest safe change:** centralize effective-attempt calculation and use it consistently in failure and release decisions. Preserve the raw absolute ceiling as a separate backstop. Audit the external reaper for parity before shipping.

### 3. Cancellation can strand completion capacity — plausible, moderate confidence

`acquire_complete_slots` increments counters inside a child coroutine passed to `asyncio.wait_for` (`worker_complete_slots.py:74–84`). Its release `finally` starts only **after** that await returns (`95–106`).

A request cancellation racing with successful child admission can therefore leave:

```text
_global_in_flight = 1
_muni_in_flight[M] = 1
no live handler owning that reservation
```

If cancellation propagates before entering the release-protected region, no decrement or notification runs. Repetition can exhaust all slots; subsequent requests time out into 503 (`worker_queue.py:5976–5987`).

**Recovery:** no reconciliation exists in this module; process restart clears these process-local counters.

**Smallest safe change:** protect admission and execution with one outer `try/finally`, tracking whether admission occurred. Prefer same-task timeout-based waiting where supported, avoiding the child-task ownership handoff.

### Other material observations

- **Rate limiting is advisory, not a strict shared limit.** Municipality eligibility is checked before selection, but recorded only after commit (`worker_queue.py:3147–3155`, `3529–3537`). Concurrent claims can all pass the same snapshot. State is process-local (`worker_claim_rate.py:22–24`), so multiple API processes multiply the effective budget.
- **Completion waiters retain database locks**, except the AV branch. `/complete` locks J before waiting for slots (`7812–7821`, `8051–8079`); heartbeat also needs that lock (`3746–3753`). This can delay heartbeat during congestion. `now` is captured before the lock wait and slot wait, so several branches validate using an outdated clock.
- **Fresh same-worker claims without an idempotency header are not serialized.** Two requests can both observe no existing lease and select different pending rows using `SKIP LOCKED` (`2965–2986`, `3024–3028`, `3157–3165`). Whether a database constraint prevents this is outside the packet.
- Terminal completion/failure/release guards and lease clearing substantially reduce completed-job resurrection risk (`7827–7835`, `8525–8550`, `8651–8683`). They do not justify assuming every interruption path is safe.

## Focused failure-injection checks

1. **Capacity-bound lost response:** commit the last permitted claim, drop its response, retry the same key; require the same job, unchanged attempts, and no 429.
2. **Concurrent admission:** synchronize different workers immediately after the capacity count; require total live leases never exceed the key cap.
3. **Graceful-credit parity:** perform C graceful releases, then one genuine retryable failure; require requeue unless the raw absolute ceiling is reached. Repeat through default release and the reaper.
4. **Slot cancellation race:** cancel immediately after reservation but before context entry; require counters return to baseline and another waiter enters. Also cancel during waiting and handler execution.
5. **Completion congestion:** occupy all slots, start a non-AV completion, then heartbeat J. Measure lock blocking and test lease expiry during the wait.
6. **Rate-limit burst:** synchronize claims at the last available municipality budget unit, including multiple API processes; verify the intended strict or advisory behavior.

**Uncertainty:** the packet excludes database constraints, session cleanup, scheduler/reaper implementation, worker retry behavior, and configuration values. These determine eventual recovery and production impact; they do not remove the demonstrated graceful-accounting inconsistency or replay-before-cap ordering defect.

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.

Primary judge's stated reason

A offers the more reliable actionable review overall: its graceful-credit defect and capacity-bound replay trace establish specific failure states without relying on repeated response loss, and its checks cover their interactions. This is a clear comparative advantage in correctness and required lifecycle coverage, not merely a preference for additional detail. B's stale-reclaim finding remains valuable under narrower conditions.

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_56fa86320524d3d21b5265263b3795b699e7693779178f54a5f715ebd763d745. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.