← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / high / high 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 / 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 / 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 provides the more reliable actionable review: its demonstrated graceful-interruption failure and more carefully bounded concurrency findings better support safe fixes and failure injection. This is a clear comparative advantage, not merely a forced slight preference, although B contributes a valuable additional stale-reclaim safeguard and neither answer establishes runtime observations.

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