← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / low / low effort preferred over deepseek / deepseek-flash / none / unknown 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.

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 provides materially more useful corrective guidance: authorize non-capacity-increasing replay before fresh admission, and consistently account for graceful credits. Its focused checks reproduce both failures and distinguish endpoint recovery from reliance on an external reaper. This is a clear task-correctness advantage, not a slight forced preference; uncertainty about cancellation behavior does not determine the choice.

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