0035. Analysis generations and job outcome rules
Source:
docs/decisions/0035-analysis-generations-and-job-outcomes.md. Generated at build time; edit the source file.
Date: 2026-11-21 Status: Accepted. Implements 0030 and 0032; changes the job semantics of 0028.
Context
Section titled “Context”The TS worker analysed a game once per protocol: analysis_status = 'done' AND analysis_protocol = ANALYSIS_PROTOCOL returned early, and analysis_attempts only ever grew. A user who asked for a re-analysis (a “force”) could not bypass “already done”, and a game that had used up its attempts stayed capped for ever. On shutdown, a BullMQ job on its final attempt was dead-lettered, so a deploy could fail games that were never at fault. BullMQ ids (resume-import-<runId>) allowed several live imports per account, and the circuit breaker created a new import_runs row on every re-delay. R1 replaces BullMQ with the Postgres queue (ADR 0032), so these rules are restated here.
Decision
Section titled “Decision”- Generations.
games.analysis_generation integer NOT NULL DEFAULT 0counts re-analysis requests.games.analysed_generation integeris the generation the stored analysis belongs to. The migration setsanalysed_generation = 0for games alreadydone. A game is finished only whenanalysis_status = 'done' AND analysis_protocol = ANALYSIS_PROTOCOL AND analysed_generation = analysis_generation. Only then does the handler returndonewithout writes. request_reanalysis(pool, queue, game_id)setsanalysis_generation + 1,analysis_attempts = 0, statuspending,analysis_error = NULLandpending_since = now()where the game is notanalysing, then enqueues it (analyse:<game_id>, so a live job is reused). It returnsfalsefor a missing game or one mid-analysis. Resetting the attempts per generation means a capped game (analysis_attempts >= 6, indexed bygames_attempt_cap_idxfor the reconciler) can be retried by the user.- The fence. Each attempt claims the game (
analysis_attempts + 1,RETURNING analysis_attempts, analysis_generation). Every later write (heartbeat, skipped, done, pending, failed) carriesAND analysis_attempts = <claimed> AND analysis_generation = <claimed>. The generation is part of the fence becauserequest_reanalysisresets the attempt counter. Without it, a stale run of generation 0 holding attempt 1 could complete generation 1 after the reset. - Job outcomes of the analyse handler.
- Game row missing:
Unrecoverable(the only unrecoverable case). - Unsupported variant or fewer than 2 plies: a fenced
skipped. Any other PGN error is the game’s own (poison) and is retried like an engine error. - The fence misses:
Ok(superseded), nothing written. - Shutdown or a closed engine pool releases the job (
Release { delay: 0, reason: "shutdown" }) on any attempt, after a fenced write ofpendingwithpending_since = now()and the error message. A cancelled job token (shutdown, lost lease, hard timeout) counts as a shutdown. TS dead-lettered such a job on its final attempt. - Deadline overrun (10 minutes):
Retryable { code: "timeout" }, handled like any other error below. - Any other error: a non-final attempt writes
pending(withpending_since). The final attempt writesfailed(error at most 2000 characters) and publishesjob.failed {kind: "analyse-game", gameId, reason}only if the fenced write hit the row. Both returnRetryable. on_dead(the runner dead-letters the job, including a stalled one) writesfailedonly where the status is not alreadydone,failedorskippedandanalysis_attempts > 0, and publishesjob.failedonly if a row came back. It therefore never duplicates the handler’s own final-attempt event. It also never overwrites a re-analysis that landed between the final attempt and the dead-lettering:request_reanalysisresets the attempts to 0, and every attempt of the new generation claims (so raises them) before it can fail. Known gap (Task 22):on_deadis not generation-fenced. It runs after the runner’s dead-letter commit, so a re-analysis whose new generation is claimed (attempts back to 1, statusanalysing) in the milliseconds between that commit and theon_deadwrite can still be marked failed. Task 22 should close it, for example by passing the generation of the dead job’s last attempt toon_dead, or by fencing onanalysis_status = 'pending' OR analysis_started_at < <dead-letter time>.- A heartbeat whose fenced write misses means a newer attempt owns the game: the run cancels its own token, so a superseded duplicate frees its engine slots at once, and returns
superseded. - An evaluation that completed is persisted even if the deadline fires just after it (the persist is fenced).
- Game row missing:
- Re-analysis handoff.
request_reanalysisenqueues under the live-only dedupe key, so a request that lands while the game’s job is still running is deduped onto that job (the dedupe is logged). After the handler writes a final status (it commitsdone, writesskipped, or writesfailedon the final attempt), or takes the early return, it re-reads the game. A non-final failure needs no check: the queue retries it anyway, and its next claim takes the new generation. If the game is nowpendingat ananalysis_generationabove the one this run processed, it returns a zero-delayRelease { reason: "reanalysis" }. A zero-delay re-queue keepsrun_at, so the same job runs again at once and claims the new generation. If that re-read fails, or the job vanishes, the reconciler is the final backstop: it re-enqueues pending games that have no live job.- A handed-off generation inherits the job’s used attempts. The game’s
analysis_attemptsrestarts at 0, but the queue job keeps its ownattempts(a release does not use one, yet the attempts already spent stay spent). A generation handed off from a job on its final attempt therefore runs as that job’s final attempt: one failure dead-letters it, and the game is failed for that generation. The user can request another re-analysis, which enqueues a fresh job with a full budget once the old one is finished.
- A handed-off generation inherits the job’s used attempts. The game’s
- The deadline token is a child of the job’s cancellation token (no linking task). On expiry the run’s token is cancelled and the same future is awaited to its end, so the partial statistics are still recorded.
- Rules owned by Task 21 (import), recorded here. A user-level
not_found(the chess.com archive list, the Lichess user stream) is unrecoverable: the run fails at once witherror_code = not_found, andjob.failedis published. An open or half-open breaker re-delays the job without using an attempt, floored atmax(5 s, probe timeout)plus jitter, and reuses the account’spausedrun row (found throughimport_runs_paused_idx) instead of inserting a new one.pausedis non-terminal. - One live import per account (dedupe key
import:<account_id>, ADR 0032), and one live analyse job per game (analyse:<game_id>,user_key = account_id,max_attempts = 3).
Consequences
Section titled “Consequences”- A deploy never fails a game: its job is released and a fresh worker completes it (Task 22 tests this end to end).
- A re-analysis is cheap to request and safe against stale runs. The eval cache is keyed by
(fen_key, protocol), so a re-analysis at the same protocol is served mostly from the cache. - A job that is released on every attempt (a pool that is always closed) is re-queued without bound. The worker’s shutdown order (stop claiming before closing the pool, Task 22) keeps that from looping.