← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / high / high 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 / 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`).

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

B provides materially more useful guidance for the requested lifecycle review: reproducible admission and retry-budget failures, explicit recovery limits, small corrective changes, and focused injection checks. This supports a clear preference rather than a slight forced choice, despite the unsupported lock-cycle example and runtime-dependent cancellation concern.

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