← Model losses

Head-to-head comparison

cursor / composer-2.5 / Composer 2.5 default / unknown effort preferred over deepseek / deepseek-flash / none / unknown 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.

cursor / composer-2.5 / Composer 2.5 default / unknown effort answer

## Conclusion

The claim/complete lifecycle is largely self-healing for HTTP retries, terminal idempotency, and lease-based concurrency, but one **in-packet** path can produce **duplicate work** and skew **attempt/capacity accounting**: same-`worker_id` **stale-lease self-heal** after 150s without `heartbeat_at`/`claimed_at` activity, while the original worker may still be running. Multi-process deployments also **under-enforce** per-municipality claim throughput and `/complete` concurrency because those counters are **process-local**.

**Confidence:** High for the stale-heal duplicate-work trace (logic is explicit in `worker_queue.py`). Medium for multi-replica capacity drift (`worker_claim_rate.py`, `worker_complete_slots.py`). Low for lease-reaper behavior (referenced but not in packet).

---

## Exact plausible failure trace (stuck → duplicate → accounting)

**Setup:** Worker `W` claims job `J` (`status=running`, `leased_until` ≈ now+25–60m, `heartbeat_at=claimed_at=now`, `attempt_count` incremented). `W` keeps processing locally (long download, paused debugger, heartbeat bug, or API unreachable) and sends **no** `/heartbeat` for **>150s**.

**Step 1 — Stale heal on next `/claim` from same `worker_id`:**  
`existing_job` is selected `FOR UPDATE` with live lease. `last_activity = heartbeat_at or claimed_at`. Because wall clock advanced >150s with no new heartbeat, `is_stale` is true. The handler sets `J` back to `pending`, clears `worker_id`, `claim_token_hash`, `leased_until`, etc., audits `WORKER_CLAIM_STALE_LEASE_RECLAIMED`, and **does not** decrement `attempt_count` (release/fail semantics don’t apply here).

**Step 2 — Same transaction claims again:**  
`J` (or another job) is claimed fresh: `attempt_count` **+1 again**, new `claim_token`, possibly new `output_path` (`…/attempt-{n}` when `n` increased).

**Step 3 — Duplicate execution:**  
`W` still believes it owns `J` with the **old** token and old `review_pack_key`. A second claimant (often the same `W` on its next poll) runs the same media job in parallel. First `/complete` may succeed; the other gets **410** (`lease_expired_or_invalid`) or writes to a **different attempt prefix** if it completes before conflict detection.

**Capacity accounting after retries/interruption:**

| Mechanism | Effect |
|-----------|--------|
| Per-API-key cap (`claiming_api_key_id`, `status=running`, `leased_until>now`) | Healed job drops out immediately → slot freed **before** duplicate claim; cap can **under-count** real in-flight work (ghost worker + new lease). |
| Per-muni claim rate (`record_claim_for_municipality` after commit, not on idempotent replay) | **Second successful claim counts again** → throughput budget burned twice for one logical run. |
| `attempt_count` | **+1 per claim**, including re-claim after stale heal → retries/interrupts inflate attempts without a matching `/fail`. |
| `/complete` slots | Unaffected by stale heal; duplicate completes compete for slots separately. |

**Does the queue recover?** **Partially.** `worker_id` is unblocked; `J` returns to the pool; terminal `/complete`/`/fail`/`/release` guards prevent resurrecting `completed`/`failed`/`cancelled` rows. **Recovery does not guarantee single execution** or correct attempt/rate accounting when a live worker outlives stale heal.

**What works (contrasting evidence):** Idempotent `/claim` with `Idempotency-Key` (advisory lock + token rotation, 600s TTL); bound `/complete` sets `status=completed` and clears lease (avoids reaper re-queue duplicate); terminal short-circuit on `/fail`/`/release`/`/heartbeat`; `SKIP LOCKED` prevents two workers claiming the same row in one instant; per-key concurrency excludes expired leases (`leased_until <= now`).

---

## Smallest safe change (recommendation)

**Tighten stale same-worker heal so it cannot return a **still-leased** job to `pending` while `leased_until > now`**, unless the heal is explicitly the “orphaned claim” case (client never had a live session).

Practical minimal variant aligned with existing comments (Mys-MacBook incident): **only stale-heal when `heartbeat_at` is still the claim-time stamp *and* there has never been a successful client `/heartbeat`** (e.g. compare `heartbeat_at == claimed_at` and optional monotonic `heartbeat_count` if added later), **or** require `leased_until <= now` for heal when any post-claim heartbeat occurred.

Today, server sets `heartbeat_at` at claim, so “no client heartbeat” is indistinguishable from “client heartbeating” without a separate flag—**smallest incremental fix:** add `config_json._claim_client_heartbeat_seen: true` on first successful `/heartbeat`, and stale-heal only when that flag is absent **and** `(now - claimed_at) > STALE_SAME_WORKER_LEASE_SECONDS`. Orphaned-response workers never heartbeat → still heal at 150s. Live workers that heartbeat at 60s → never heal while lease valid.

If a one-line behavior change is unacceptable, **smallest operational mitigation without schema:** raise `STALE_SAME_WORKER_LEASE_SECONDS` above worst-case first-heartbeat delay (weak; does not fix heartbeat outages).

---

## Focused failure-injection checks

1. **Stale heal vs live worker:** Claim job; block `/heartbeat` for 151s while a background task simulates work; call `/claim` same `worker_id`; assert whether job returned to `pending` and `attempt_count` increased; assert first worker `/complete` → 410 and whether second run created a second `output_path` attempt directory.
2. **Orphan claim (intended heal):** `/claim` commit; drop HTTP response before client reads `claim_token`; no heartbeats; after 151s same `worker_id` `/claim` → should unblock without leasing a second job (idempotency key) or heal + single logical attempt.
3. **Idempotency TTL:** Replay `/claim` with same `Idempotency-Key` at 601s with job still `running` → must not rotate token under active worker (TTL fall-through); document expected 409 vs new claim.
4. **Per-key concurrency:** Fill 64 `running` leases; claim 65th → 429; fail/release one → next claim succeeds; verify count ignores `pending` rows with stale `claiming_api_key_id`.
5. **Multi-replica claim rate (if applicable):** Two API processes; hammer `/claim` for one muni; assert whether effective limit is `N` or `2N` per minute.
6. **`/complete` slot timeout:** Saturate `WORKER_COMPLETE_MAX_*`; assert 503 `complete_concurrency_limited`, worker retry, single terminal completion (idempotent duplicate `/complete`).
7. **Success then `/fail` fallback:** Complete job; `/fail` with stale token → `WORKER_FAIL_DUPLICATE`, status stays `completed`.

---

## Alternatives / likely false positives

- **Lease reaper** (scheduler, outside packet) may requeue expired `running` jobs—could duplicate stale-heal if both fire; interaction **not verified** here.
- **409 `worker_already_owns_job`** within 150s is intentional, not stuck work.
- **In-memory rate/slot limits** are design tradeoffs for single-process or low replica count; false positive as “bug” if deploy is strictly one API instance.
- **Zip `prepare_zip_manifest` double `commit`** (lines ~4609–4625 in packet) is a separate consistency smell, not analyzed as queue lifecycle.

---

## Missing evidence / consequence

- `_worker_lease_reaper_loop()` and when it clears `running` vs `pending` — cannot fully sign off on stuck-`running` recovery without reaper.
- Mac worker behavior on 410 vs retry on `/complete` — affects whether duplicate uploads retry safely.
- Whether production runs **multiple** API replicas — determines severity of claim-rate and complete-slot drift.

**Next useful action:** Implement the `_claim_client_heartbeat_seen` (or equivalent) gate on stale heal plus test (1); run SOL/cluster review if changing lease semantics is production-critical.

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 the more useful interruption review by exposing an actionable overlapping-execution scenario that B incorrectly rules out. The preference is weak rather than a proven material quality gap: A's remedy is incomplete, while B offers stronger cancellation-focused testing. An independent review could reasonably challenge the balance.

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