openai / gpt-6.1-sol / low / low effort preferred over openai / gpt-6.1-sol / high / high 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.
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.
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`).
Primary judge's stated reason
B receives a weak, forced preference because its lock discussion avoids directing engineers toward a reproduction contradicted by the AV rollback path. A's additional actionable ZIP finding substantially counterbalances that advantage. This is not an established material overall quality gap; an independent review could reasonably prefer A's broader useful coverage.
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_9b05e1cb69d8b7937d6ce7331ecfbd26522b05a4bd0377c549d93203071b1e2c. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.