Plan: Background Jobs for the Batch-Class Engines — 202 + a Durable Job Resource + Poll; Retire the 600 s Ceiling Class (#1571)

Archive record

Merge requests: !1661 (U0 plan page + ADR-068 § Amendment — #1571 Proposed, Relates #1571) + !1662 (U1, Closes #1933) + !1663 (U2 + U3, Closes #1934 / #1935) + !1664 (U5, Closes #1937) + !1666 (the #1941 prerequisite fix:, Closes #1941) + !1667 (U4, Closes #1936) + !1668 (U6, Closes #1938) + !1669 (U7, Closes #1939) + !1670 (U8, Closes #1940 / #1571)

2026-09-18 — rev 3 approved in plan mode 2026-09-17 after a contextless round 1 (6 blockers) and the maintainer’s 21-finding gate: the eight engines that rode ADR-068’s 600 s Batch ceiling (expiry_sweep, archive_run, promote_preview, ncands_generate, subsidy_generate, import_finalize, sweep_preview, sweep_execute — five owning services) became durable background jobs behind ONE craig_api::jobs module (the request_claims ×8 shape): the enqueue IS the ADR-062 claim transaction — a REQUIRED client_request_id on every route, the consent gates in the same tx, the (jurisdiction, dedup_key) partial-unique arbiter (typed 409 job-already-active), 202 + Location
the JobView; a per-service Criticality::Critical owner-pinned executor (lease-key dispatch, four permits with one reserved for consent kinds, 5 s heartbeat, 15 s scan, 30 s stale classification of running AND queued rows from the owner’s last sign of life) whose in-memory ADR-074 proofs decide recovery — convergent kinds re-queue up to three attempts and are adoptable by any replica, consent kinds (import_finalize, sweep_execute) end failed(lost_proof) / failed on crash and are never adopted; ONE engine change each — a &JobBoundary checked at the natural boundary (archive additionally run_passes with preserved TableState); the generic read-only GET /v1/<svc>/jobs/{id} on the new BackgroundJob resource type ({j}-authz-background_job.json ×2, bootstrapped BEFORE the first adopting image; the fleet 403, no-store); claim-joined retention; the sweep token moved to an explicit single-use issuance POST under the 15-min TTL, the run’s consented state, counters preserved on failure; the reporting → cases whole-FFY hop PAGED BY REFERRAL under a fixed as_of cohort with the submission and the job completed in ONE tx; the four FALSE-Batch routes (claims/generate, promote execute, archive/purge, afcars/generate) back to Standard, the two exports to Extended; every caller (CLI / xtask / test-lib wait_for_job / the web poll fragment) polls to terminal and re-authenticates on a 401 mid-poll; then the close-out — CeilingClass = Standard \| Extended, BATCH_REQUEST_CEILING / BATCH_CALLER_BUDGET / the 4-arg with_durations / the admin-replay auto-entry / CLI post_batch deleted, both claim_first_unbudgeted sites gone (D1a: every HTTP-plane domain statement runs under the 10 s budget; long statements belong to jobs), POST /v1/admin/events/replay Standard after the #1941 (created_at, id) index + batched, budgeted re-stage (≤ 20 × 5 000 rows per call; a full 100 k-row call ≈ 0.63 s, max batch ≈ 33 ms ≈ 0.3 % of the 10 s budget, index build ≈ 22 ms). Rulings: R1 admin-replay OUT of scope, its fix: U8’s prerequisite; R2 the FFY hop paged by referral under a fixed cohort; R3 the exports FLIP to Extended sync (#1572 streams the downloads); R4 the sweep token is an explicit POST; R5 re-queue ≤ 3 for convergent kinds, failed and never adopted for consent kinds; R6 the four FALSE-Batch reversions by name; R7 #949 lands job-first on this substrate; R8 executors Critical; R9 the REQUIRED client_request_id on every caller; R10 one boundary check per engine. ADR-068 § Amendment — #1571 Accepted (no new ADR); 14 errata recorded on the page; follow-ups #1942 (consent-kind pickup), #1943 (Studio jobs page), #949, #1572.

Status

Done (2026-09-18) — !1670

Anchors

#1571 (epic &96; children U1–U8 — U8 closes the anchor), ADR-068 § Amendment — #1571 (Proposed at U0 — the class table shrinks to Standard + Extended, D1a’s invariant is restated, the "Background jobs" section, the FALSE-Batch reclassifications by name; Accepted at U8; no new ADR), ADR-062 (§ Decision › "HTTP — in-transaction request claims" gains its background-jobs entry — the enqueue IS the claim transaction and Replay { entity_id } is the same job), ADR-074 (an ApprovedAction never leaves process memory — the lost_proof class follows from it), ADR-067 (each executor is a PROMOTED worker anchor with drain + crash legs), ADR-055 / ADR-057 (the crash-resumable money engines the deploy-drain gap has survived on), #1404 (the ADR-068 program whose class this plan retires), #1572 (the streaming download half of the exports — after and independent), #949 (AFCARS generate — lands job-first on this substrate).

Errata

Erratum (2026-09-18): unknown/forged body fields answer the fleet extractor’s 422 validation-failed, not a typed 400 (R-U1-3).

Erratum (2026-09-18): the engine seam is one &JobBoundary (wrapping the CancellationToken + a progress counter) checked once per home (R-U1-8).

Erratum (2026-09-18): a queued row’s staleness is measured from its owner’s LAST sign of life — GREATEST(queued_at, heartbeat_at), the owner keep-aliving its own queued backlog every pass — so a row waiting behind a permit or a lease key is never adopted or failed lost_proof while its owner lives (D3 read as "the heartbeat proves it").

Erratum (2026-09-18): lease_key is NULLABLE — ncands_generate holds no lease (D1 wrote NOT NULL).

Erratum (2026-09-18): the hourly generator tick keeps taking the subsidy-gen lease directly and skips (info) while a job holds it; a job attempt that finds the tick holding it reads waiting_for_lease (D6 wrote the tick as the waiter).

Erratum (2026-09-18): ncands_generate’s resource is empty — no submission GET exists; the submission id equals the job id in the result.

Erratum (2026-09-18): same-tx completion is the substrate’s complete_in_tx keyed on (id, running, owner, attempt), not the version (the heartbeat bumps it).

Erratum (2026-09-18): the import_finalize pass loop ends on ANY batch status other than finalizing — staging (live rejections) is a pass-terminal succeeded, and aborted is unreachable inside finalize (D6 wrote {finalized, aborted}; R-U6-3).

Erratum (2026-09-18): failed(no_progress) carries NO result (result is present iff succeeded) — the categorical counts remaining_staged / passes ride error.detail and the batch ledger sits behind the job’s resource link (D6 wrote "with the report"; R-U67-4).

Erratum (2026-09-18): import_finalize’s `resource_type is the path token financial/subsidy-imports (the href is /v1/financial/subsidy-imports/{id}) — the type token IS the path segment under /v1/.

Erratum (2026-09-18): import_finalize’s `input is { batch_id, as_of } — the jurisdiction business date captured at enqueue that every pass classifies against (D1 listed the batch id alone; R-U6-1).

Erratum (2026-09-18): the sweep token POST consults the supervisor review_sweep Update row AND the background_job read row on the preview job (its creator, or an admin) — D5’s "no GET writes anything" holds, the POST is the write; a run no preview job wrote (preview_job_id NULL — scheduled / pre-#1939) is 409 sweep-run-state for everyone, and the execute enqueue’s window refusal shares the token POST’s 409 sweep-preview-expired (D6 left it on sweep-run-state; R-U7-2).

Erratum (2026-09-18): the preview job’s result is PreviewSweepResult — the pinned sets plus a CLOSED token_state (available | issued | expired, written available at finalize; the run row is the live source) and NO execute_token / expires_at; the plaintext rides only the POST’s SweepTokenResponse (D6 named only available; R-U7-1).

Erratum (2026-09-18): mark_run_failed PRESERVES counters by COALESCE under the guard state IN ('observed', 'consented', 'executing') — a terminal run is never re-stamped, and a consented run failed before its attempt started keeps NULL counters, not zeros (D6 wrote "the accumulated counters preserved"; R-U7-3).

Context

ADR-068 (#1404) bounded every request with a route-class ceiling — Standard 20 s, Extended 300 s, Batch 600 s — and paired the Batch class with 610 s caller budgets as an explicit, inventoried exception. Its Consequences record the durable fix as a filed follow-up: background the engines (202 + a durable job resource + poll), which removes the class’s reason to exist and closes the deploy-drain gap (HTTP_DRAIN_DEADLINE 20 s abandons a 600 s route mid-flight — survivable today only because the money engines are crash-resumable by ADR-055 / ADR-057 design). A five-lane read-only census (2026-09-17), its anchors re-verified by the round-1 reviewer and the maintainer’s gate, established what the decisions depend on:

  • The census: 15 registrations + 1 built-in. ceilings.rs tables — cases 1, financial 5, placement 1, reporting 4, rules 2, security 2 — plus POST /v1/admin/events/replay, pushed into Batch UNCONDITIONALLY on every router by CeilingConfig::with_durations (crates/craig-common/src/ceiling.rs:172-173); ADR-068’s own table omits four registered routes (claims/generate, expiry-sweep/run, promote EXECUTE, cases GET ncands-export).

  • The manifest (route → kind, owning service): placement POST expiry-sweep/run → expiry_sweep; security POST archive/run → archive_run; rules POST sets/{id}/promote/preview → promote_preview; reporting POST ncands/generate → ncands_generate; financial POST subsidy-payments/generate → subsidy_generate, POST subsidy-imports/{id}/finalize → import_finalize, POST subsidy-reviews/sweep/preview → sweep_preview, POST subsidy-reviews/sweep/{run_id}/execute → sweep_execute — eight backgrounded POSTs, five owning services, five executors, five job GETs. Four registered routes are FALSE Batch (the ceiling shelters nothing): financial claims/generate and rules promote (execute) ride the BUDGETED claim_first (a 10 s SET LOCAL, request_claims.rs:328-343) in one short tx; security archive/purge is a bounded slice (PurgeParams 1..=100, selection EMPTY until DFCS names a schedule); reporting afcars/generate is the #949 zero-record stub (afcars.rs:53). The two reporting exports FLIP to Extended; cases GET ncands-export is paged. Admin-replay (crates/craig-api/src/admin_replay.rs:139-146) is one COUNT + one UPDATE straight on the pool, unbounded by the 10 s domain budget, over a created_at range the outbox’s partial index (WHERE published_at IS NULL) does not serve — an index / batching defect, not a duration class.

  • Exactly two statements need more than 10 s — the claim_first_unbudgeted sites ncands_generate.rs:99 (a 10 k-row UNNEST after a whole-FFY S2S hop) and subsidy_review_sweep.rs:216 (the pinned-set write); ADR-068 D1a forbids an UNCLAIMED long variant, so both must leave the HTTP plane rather than gain a new escape.

  • The 610 s budget has three payers: CLI post_batch ×5 (services/craig-cli/src/client/transport.rs:79; callers archive.rs:138/150, claim.rs:125, reporting.rs:188/267), the xtask import mirror (import_subsidy_history.rs:248-262; the 20-pass loop at :358-377), reporting’s CasesClient (cases_client.rs:48 — the whole-FFY hop ADR-068 exempts from the 8 s S2S budget); the web BFF is ALREADY unpaired (craig-bff/transport.rs:346-362; the web proxies ride 30 s). The CLI transport holds ONE bearer for its lifetime (transport.rs:22-27); no refresh path exists in the CLI, the xtask tool or the test-lib.

  • Idempotency today: only generation is claim-less, but expiry-sweep/run, archive/run and finalize are BODYLESS, and PromotePreviewRequest (craig-rules-contracts/src/lifecycle.rs:22) and ExecuteSweepRequest (craig-financial-contracts/src/subsidy_review_sweep.rs:170) carry no client_request_id — a 202 that creates a job needs a claim on every one of the eight.

  • No handler ever sees a cancellation token: a ceiling cut DROPS the future (ceiling.rs:229); workers get WORKER_DRAIN_DEADLINE 5 s (supervisor.rs:125); expiry_sweep::run_pass (expiry_sweep.rs:256) and finalize take no token and check no boundary; the retention engine’s run_pass does (craig-retention/src/engine.rs:301-345) but rebuilds every TableState per pass, so a repeated pass re-selects and re-quarantines the same oversized rows (:308-316) — repeating passes can loop without progress.

  • Durable state today (the wrapper a job row must respect, never replace): sweep execute has a run row with a GET (/v1/financial/subsidy-reviews/sweep/runs/{run_id}) but writes counters only at finalize; reap_stranded_runs (review_sweep.rs:1644-1673) fails EVERY executing run whenever the lease is free, mark_run_failed (:1617-1628) stamps RunCounters::default() — zeros; execute refuses a preview older than 15 min from the run’s started_at (:2042-2050, expired). Import finalize’s batch / record ledger IS progress, but finalize_one SWALLOWS record-level infra errors into tally.infra_errors and returns Ok with status = finalizing and rows still staged (import_batch/finalize.rs:240-262) — the xtask’s 20-pass loop is what retries; the response is FinalizeReport { batch_id, status, expected_count, newly_materialized, newly_rejected, remaining_staged, total_materialized, rejections } (:540-548). Generation has NO run row (run_id minted in memory, subsidy/generator.rs:279); every month shares ONE global subsidy-gen session lease on a detached connection (:286-292); expiry sweep, archive run and generation converge on re-run. Ncands generate commits its claim AND its submission in ONE tx (ncands_generate.rs:93-112) with no independent dedup on the submission — a claim moved to enqueue leaves a crash window between a committed submission and a completed job. Every lease-gated engine acquires its SESSION advisory lease INSIDE the engine — an enqueue cannot hold it.

  • The NCANDS source: the cases collector is ONE range SELECT … WHERE received_at IN [ffy) AND screened_in ORDER BY received_at (store/referrals.rs:305-320) fixing a cohort at one instant; a referral emits zero-to-many allegation rows (api/ncands.rs:242-248); a late-converted referral keeps its ORIGINAL report received_at (store/referrals.rs:114-118), so it can appear behind a cursor.

  • ADR-074 proofs cannot leave process memory: ApprovedAction has private fields and no ctor / serde (subsidy/approvals.rs:472-483); covers re-checks by key + rank (:548-590) — a consent job (finalize, sweep execute) whose owning process dies before its attempt starts has LOST its proof; nothing can reconstruct it.

  • Precedents: 202 = the entity in the body with a status, no Location (exchange screening.rs:154-162); ClaimOutcome::Replay { entity_id } re-reads the entity (request_claims.rs:193-196); the house DB-row queue is exchange_send_jobs (SKIP LOCKED + lease + claim_generation CAS); the supervisor’s Criticality::{Critical, Observed} (supervisor.rs:45-54; watch :316 / watch_optional :338); the request-claims pruner runs on CRAIGREQUEST_CLAIMSWINDOW_DAYS (default 30; 0 = keep claims FOREVER, craig-api/src/lib.rs:739-741); the devstack generator ticks hourly (docker-compose.yml:766) while placement’s expiry interval is 0 (:589); the rules canary runs on spawn_blocking with its own runtime (api/lifecycle/canary.rs:36-53); the BFF’s CSRF stage skips GET / HEAD / OPTIONS / TRACE (craig-bff/src/middleware.rs:132-135) and axum routes HEAD to the GET handler; the engine’s CHECK parses allow only (engine.rs:1565) — list scopes never apply to a GET; rules-bootstrap must precede the first image that consults a new family (xtask/src/cmd/rules_bootstrap.rs:3-11); the three SDKs are INTAKE SDKs (sdks/{python,typescript,test-vectors}) and expose none of these routes; the test-lib impl ServiceClient is at the F-054 16-method ceiling; serde_json::Value is refused in business logic.

Decisions

  1. A job is a LOGICAL resource; executions are ATTEMPTS. Per service, behind ONE craig_api::jobs module (the request_claims ×8 precedent — one migration per service, one code path): background_jobs { id UUID (= the claim’s entity_id), kind, jurisdiction, created_by UUID, dedup_key TEXT NOT NULL, lease_key TEXT NOT NULL, input JSONB NOT NULL (typed per kind: month + scope | reporting_year + as_of | batch id | run id | rule set id + from_revision | preview params | archive pass params), resource_type / resource_id (nullable), state CHECK IN ('queued','running','succeeded','failed'), attempt INT, max_attempts INT, progress JSONB NOT NULL = ONE typed Progress { phase, done, total? }, result JSONB (the former 200 body, typed per kind), error JSONB (an RFC-9457 problem with a CLOSED type token: lost_proof | crash | exhausted | no_progress | refused_at_start | engine_failed — categorical, never partner or PII text), owner_instance TEXT NOT NULL, queued_at, started_at, finished_at, heartbeat_at, version BIGINT } and background_job_attempts { job_id, attempt_no, owner_instance, started_at, finished_at, outcome CHECK IN ('succeeded','failed','interrupted','crash','lost_proof'), detail }. The only TERMINAL job states are succeeded and failed, and they are immutable (the terminal UPDATE is by id + version); interrupted and crash are ATTEMPT outcomes after which the recovery rule (D4) either re-queues the job (attempt
    1
    , lineage in the attempts table, queued again — the same row, claim and Location) or ends it failed. kind is the closed wire vocabulary of the manifest (expiry_sweep, archive_run, promote_preview, ncands_generate, subsidy_generate, import_finalize, sweep_preview, sweep_execute); dedup_key per kind (subsidy_generate:<month>, import_finalize:<batch_id>, sweep_execute:<run_id>, promote_preview:<rule_set_id>, ncands_generate:<ffy>, the singletons expiry_sweep, archive_run, sweep_preview:<jurisdiction>); lease_key per kind names the engine lease the job will hold (subsidy-gen for EVERY month, retention-archive, expiry, import:<batch_id>, sweep, promote:<rule_set_id>, none for ncands). The enqueue-time arbiter is a partial-unique index (jurisdiction, dedup_key) WHERE state IN ('queued','running'): a second enqueue while one is active is typed 409 JOB_ALREADY_ACTIVE. Retention is claim-joined, not arithmetic: the pruner (the claims pruner’s cadence, knob CRAIGBACKGROUND_JOBSWINDOW_DAYS, default 31, 0 = disabled) deletes only TERMINAL jobs older than the window whose claim row no longer exists (NOT EXISTS request_claims WHERE entity_id = job.id) — a claim kept forever keeps its job forever, a pruner backlog can never orphan a Replay; attempts go with their job. Rejected: a new shared crate (B8); MQ-borne jobs (an inbox attempt is OLTP-bounded); promoting each engine’s run table to the contract (three vocabularies); probing the engine lease at enqueue (TOCTOU); an arithmetic jobs ≥ claims + 1 (claims 0 means forever).

  2. The enqueue IS the ADR-062 claim transaction, on every one of the eight. Each backgrounded route takes a REQUIRED client_request_id — the three bodyless routes gain a JSON body { client_request_id } (expiry run, archive run, finalize); PromotePreviewRequest / ExecuteSweepRequest / generation / ncands / sweep preview add or keep the field — with a claim scope <svc>.<kind> and an IntentV1 projection of the job input (the rules promote_rule_set shape). claim_first is the domain tx’s first statement; every engine gate that is a CONSENT ACT stays in that same synchronous tx and keeps its typed 4xx (import finalize’s enter_finalizing; sweep execute’s token / CAS / authority refusals with the run moved previewed → consented — D6; the arbiter’s 409); the job row is inserted queued with owner_instance = the enqueuing replica and queued_at = now(); commit; the handler answers 202 with the JobView body plus Location: /v1/<svc>/jobs/{id}. Transport replay vs operator resumption: the SAME client_request_id ⇒ ClaimOutcome::Replay { entity_id } ⇒ the same job (202 again, whatever its state — a failed job replays as failed); a FRESH client_request_id is a new job, admitted by the arbiter only when none is active. Callers mint per invocation (the CLI / xtask per command; the BFF per render, the ERR precedent). Rejected: Location with an empty body; an optional id (an implicit dual-accept).

  3. Execution is a per-service executor in the worker plane; ownership covers QUEUED rows too. The enqueuing handler hands (job_id, Executor) — the in-memory ADR-074 proof / authority snapshot / Initiator — to its replica’s executor (a tokio::sync::Notify wake plus a scan every 15 s; the first scan runs at boot), registered with the supervisor as Criticality::Critical (a PROMOTED contested worker anchor with drain + crash legs). Dispatch is by lease_key: at most ONE running job per lease key per instance; other queued jobs of that key stay queued and hold no permit. Running engines take one of 4 permits (one RESERVED for consent kinds so a finalize is never starved by three months of generation); a waiting_for_lease phase (the engine’s lease held by a SCHEDULED pass — the hourly generator, the retention worker) is a 5 s re-dispatch OUTSIDE the permit, never a failure and never a timeout. The executor runs the engine with ONE change per engine — a &CancellationToken parameter checked at its natural boundary (expiry per home, finalize per record, archive per batch, generation per child batch; ncands has no boundary before its commit) — under the worker-plane session default (30 s statement budget, ADR-068), heartbeats every 5 s with UPDATE … WHERE id AND state = 'running' AND owner_instance = me (0 rows ⇒ the row was reclassified ⇒ the executor drops the engine future and logs), and stamps the attempt’s outcome + the job’s version-CAS transition. Stale classification (any replica’s scan, 15 s cadence, boot included): a running job whose heartbeat_at is older than 30 s ⇒ attempt crash; a queued job whose queued_at is older than 30 s ⇒ its owner died between commit and handoff (or before a permit) — for a CONSENT kind (import_finalize, sweep_execute) the proof is gone: attempt lost_proof, job failed(lost_proof) (terminal; the caller re-POSTs with a fresh id); for a PROOF-LESS kind (expiry_sweep, archive_run, subsidy_generate, ncands_generate, promote_preview, sweep_preview) ANY replica may ADOPT the row (CAS owner_instance + version) and run it from input + created_by — the one, bounded, cross-replica pickup; consent kinds never move. No timer-based re-classification of a job whose owner is alive: the heartbeat proves it. ONE test seam, drain_pending() → usize (runs every queued row of this service to terminal on the caller’s task, serially, permits ignored); devstack executors ON. Rejected: any-replica pickup for consent kinds (ADR-074 blocker); a serial executor; boot-only recovery (a five-second restart sees a still-running row and misses it); an overwritable terminal state.

  4. Recovery policy (per attempt outcome, applied by whoever classifies). interrupted (the engine returned at a boundary on the shutdown token inside WORKER_DRAIN_DEADLINE 5 s) and crash (stale heartbeat — the future was dropped or the process died; a statement in flight finished or rolled back server-side) re-queue a convergent kind (expiry_sweep, archive_run, subsidy_generate, ncands_generate, promote_preview, sweep_preview) as attempt + 1 up to max_attempts = 3, then failed(exhausted); a consent kind ends failed on its first crash (finalize resumes per record on the operator’s next POST — a fresh id; a consented / executing sweep run flips failed with its preview burned and its counters PRESERVED — D6) and re-queues only on a graceful interrupted where the proof is still in memory (same process; drain then restart is a new process — so in practice never: an interrupted consent attempt is stamped and the job ends failed(interrupted) with the re-POST rule in error.detail). A re-queued job keeps its id, claim and Location; the poll shows attempt, attempts[] and the last outcome. The 20 s HTTP drain gap becomes a 5 s worker drain CLOSED by the attempt ledger + stale classification, not by long ceilings. Rejected: re-queue everywhere (a consent job cannot re-mint its proof); never re-queue (a rollout would strand every convergent pass until an operator notices).

  5. The poll is generic and read-only: GET /v1/<svc>/jobs/{id} → JobView { id, kind, state, attempt, attempts[], progress, result?, error?, resource? { type, id, href }, queued_at, started_at, finished_at }, authorized on a NEW ResourceType::BackgroundJob ({j}-authz-background_job.json ×2 — admin realm-flat; the creator via assigned_worker_sub = created_by, which serves humans AND service principals) — no nil-id exceptions, twin parity by texas_authz_inputs_are_the_georgia_twins_plus_the_declared_extras, the resource_type_iter_covers_all_known_types count bumped, and the family bootstrapped per environment BEFORE the first image that consults it. ONE authz contract: a deny is the fleet’s typed 403; a missing row is 404; no existence collapse. Cache-Control: no-store on the GET and on the web fragment. Every backgrounded route returns a job; where the engine has its own row (sweep run, import batch, ncands submission) the job’s resource link points at it. No GET writes anything for any kind (the sweep token moved to an explicit POST — D6). Rejected: per-engine polls; a stored-ref authz (nil-id exceptions); a 404 collapse; a token-minting GET (HEAD reaches the same handler and would burn the token; CSRF skips GET / HEAD).

  6. Engine outcomes (the manifest, ruled per route).

    • expiry_sweep (the pilot): result = ExpirySweepReport; the token seam per home.

    • archive_run: the job holds ONE set of TableState`s for its whole life and calls a new engine entry `run_passes(states, max_batches_per_pass, shutdown) that PRESERVES quarantine across passes (the per-pass rebuild at engine.rs:308-316 is the loop bug); it ends succeeded at more = false, failed(no_progress) when a pass archives zero batches while more stays true, interrupted on the token; the D11 consent knob is re-checked at START (refused_at_start); the endpoint’s fresh CancellationToken::new() (archive.rs:164) is retired.

    • promote_preview: result = { preview_id, report }; the previews row still inserted at the end; --confirm-preview <preview_id> and the execute IntentV1 unchanged; the canary checks the cancel flag per item.

    • ncands_generate: the job’s input carries reporting_year + as_of = queued_at. The cases hop becomes PAGED BY REFERRAL: GET /v1/cases/ncands-export?ffy&as_of&after&limit≤500 returns whole referrals (each with ALL its allegation rows — a referral is never split across pages) from the FIXED cohort received_at ∈ [ffy) AND screened_in AND created_at ≤ as_of (a referral converted after enqueue is excluded deterministically, whatever its report received_at), ordered (received_at, id), after = an opaque cursor over the LAST SCANNED referral, next = null on exhaustion (an all-unclassifiable page returns zero rows and a non-null next); each page under the 8 s hop budget. Completion is atomic with the domain write: the job’s final tx inserts the submission with id = job.id (ON CONFLICT (id) DO NOTHING + re-read), its rows, AND the job’s resource_id + terminal succeeded — one commit, no window; a recovery attempt first reads the submission by job.id and, if present, completes without regenerating. A page failure fails the attempt with zero rows written.

    • subsidy_generate: gains the REQUIRED client_request_id (pre-1.0 Changed) and a subsidy_generation_runs row fed by BOTH initiators; lease_key = subsidy-gen (one running month per instance; the hourly tick is a waiting_for_lease); result = GenerationReport.

    • import_finalize: gate tx sync (enter_finalizing); the job runs PASSES of the unchanged per-record engine until status ∈ {finalized, aborted}, progress from the record ledger, result = FinalizeReport (the LAST pass’s — it carries status, remaining, totals, rejections); a pass with remaining_staged > 0 that materialized and rejected nothing counts as no-progress; three consecutive ⇒ failed(no_progress) with the report (the swallowed infra errors of finalize_one are what the loop retries; the xtask’s own 20-pass loop and mirrored const are deleted only because the job now owns the retry).

    • sweep_preview: the previewed run row is written at attempt finalize with NO token; the job result carries token_state: available. Token issuance is an explicit POST, POST /v1/financial/subsidy-reviews/sweep/runs/{run_id}/token: requires the job succeeded, the run previewed and started_at + 15 min > now (else 409 sweep-preview-expired → re-preview), single-use by CAS (token_issued_at IS NULL), Cache-Control: no-store, behind the BFF’s POST CSRF path; a second call reads 409 sweep-token-issued; the plaintext never rests.

    • sweep_execute: the enqueue tx performs today’s pre-CAS refusals and moves the run previewed → consented (a NEW run state: the token burned, the set pinned, no lease held); the attempt moves consented → executing under the sweep lease; reap_stranded_runs keeps reaping ONLY executing (a consented run is the job’s, never the lease reaper’s); a lost_proof / crash on the job flips its run failed with the accumulated counters PRESERVED — mark_run_failed and the per-agreement tx now commit counters as they go (no more RunCounters::default() on failure); Location = the job, resource = the run.

    • Reverted to Standard, no 202 (FALSE Batch): claims/generate, promote (execute), archive/purge, afcars/generate (the stub — #949 lands job-first on this substrate); the CLI calls them with a plain POST.

    • Admin-replay: reclassified Standard ONLY AFTER its fix: lands (a (created_at)-serving index and a batched, budgeted re-stage on the 10 s domain budget — a prerequisite MR of U8, not this plan’s scope); admin_replay_is_always_batch (ceiling.rs:451) re-pinned in the same diff.

    • Exports (ncands|afcars/{id}/export): FLIP Batch → Extended sync with the BFF per-request extended budget on the two POSTs — no ADR-062 §U change; the download half is #1572.

  7. The class deletion is the close-out. CeilingClass = Standard | Extended; BATCH_REQUEST_CEILING, BATCH_CALLER_BUDGET, the 4-arg with_durations and the admin-replay auto-entry, both claim_first_unbudgeted sites, CLI post_batch + the clients/mod.rs:130 macro arm, the xtask mirror const, reporting’s hop_budget, and the censused ceilings.rs Batch rows (15 at the census: 13 deleted, the two export rows flipped) — all gone; the coverage tests pass with zero Batch rows; the D1a invariant becomes "every HTTP-plane domain statement runs under the 10 s budget; long statements belong to jobs". Rejected: a Batch variant left in place.

  8. Client surface, once. craig_test_lib::jobs::wait_for_job(&ServiceClient, service, job_id) — a FREE function (F-054); the CLI and the xtask tool poll to terminal by default and print the result (--no-wait prints the id; no client-side deadline — Ctrl-C is the operator’s budget) and re-authenticate on a 401 mid-poll through the same login path that minted their bearer, resuming the SAME job id — a poll never re-POSTs; craig-web / BFF gain ONE poll fragment (the BFF proxies GET /jobs/<svc>/<id>; hx-trigger="every 2s" until a terminal state swaps in a fragment WITHOUT the trigger; no-store) used by the reporting actions and sweep pages; api-docs and xtask/route-to-client-method.toml regenerated per unit (the unmapped ncands/{id}/export and the two /export/download GETs mapped in U4). The three intake SDKs are untouched (they expose none of these routes). Every backgrounded route’s wire change is a pre-1.0 CHANGELOG Changed entry (the old 200 body → the 202 JobView + poll; the new REQUIRED client_request_id).

Units — each Relates to #1571; U8 Closes #1571

MR Issue Scope W

U0

#1571

This page (Active nav), the ADR-068 amendment (Proposed: the class table, D1a, the "Background jobs" section, the FALSE-Batch reclassifications by name), the ADR-062 request-claims row, epic + children, follow-ups filed (the admin-replay index + batched re-stage fix: — U8’s prerequisite; the deferred consent-kind pickup; a Studio jobs page; a note on #949), label Plan::BG-JOBS

1

U1

#1933

The substrate + the pilot: craig_api::jobs (jobs + attempts rows, typed Progress / per-kind input + result, enqueue_in_claim with the dedup arbiter and queued ownership, the executor: lease-key dispatch, 4 permits with one reserved, Notify + 15 s scan, 5 s heartbeat, 30 s stale classification for running AND queued rows, lost_proof vs adoption by kind, the recovery policy with max_attempts, drain_pending; JobView; the generic read-only GET with no-store; the claim-joined pruner; the BackgroundJob resource type + rulesets ×2 + the count pin), placement’s migration + Critical executor (the new worker anchor), the expiry engine’s token seam, POST expiry-sweep/run → body { client_request_id } + 202, its Batch row deleted, toml / api-docs / wait_for_job / CLI poll + 401 re-auth

8

U2

#1934

security archive/run → job ({ client_request_id }, run_passes with preserved TableState, no-progress terminal, shutdown token, knob re-check); archive/purge → Standard (plain CLI POST); CLI post_batch ×2 removed; security Batch rows deleted

3

U3

#1935

rules promote/preview → job (client_request_id on PromotePreviewRequest, { preview_id, report }, the canary cancel flag); promote execute → Standard; cargo xtask rules-promote polls + re-auths; rules Batch rows deleted

3

U4

#1936

reporting ncands/generate → job (as_of cohort, referral-paged cases GET with the opaque cursor, same-tx completion, cases' Batch row + hop_budget deleted); afcars/generate → Standard (plain CLI POST); the two export rows → Extended + the BFF extended budget; CLI post_batch ×2 removed; the web poll fragment on reporting actions; the toml gaps; reporting Batch rows deleted

5

U5

#1937

financial subsidy-payments/generate → job (REQUIRED client_request_id, subsidy_generation_runs fed by both initiators, lease_key = subsidy-gen, the generation token seam); claims/generate → Standard; financial’s Critical executor; CLI post_batch (claim) removed; the two financial Batch rows

5

U6

#1938

financial subsidy-imports/{id}/finalize → job ({ client_request_id }, gate sync, the pass loop with the no-progress bound, FinalizeReport result, the finalize token seam); xtask POST-once → poll + re-auth (the 20-pass loop + mirrored const deleted); its Batch row

5

U7

#1939

financial sweep/preview → job (client_request_id, token_state) + the token issuance POST (TTL, single-use CAS, no-store) + sweep/{run_id}/execute → consented run state (migration), 202 after the pre-CAS refusals, per-agreement counter commits, mark_run_failed preserving counters, the reaper unchanged for executing; the web sweep pages poll + call the token POST; claim_first_unbudgeted DELETED (last site); the two Batch rows

5

U8

#1940

Close-out (after the admin-replay fix: MR): CeilingClass = Standard | Extended, the consts / 4-arg with_durations / admin-replay auto-entry deleted (test re-pinned), CLI post_batch + macro arm removed, the BFF pairing note, ADR-068 amendment Accepted, deployment-guide rollout (bootstrap step, re-POST rules), testing-reference, .claude/CLAUDE.md; plan archived

2

Order: U0 → U1 → (U2 ∥ U3 ∥ U4 ∥ U5) → U6 (after U5) → U7 (after U5, U4) → U8 (after all + the admin-replay fix:) — U1 lands the substrate every later unit consumes and proves it on the one proof-less, lease-gated, bodyless pilot; U2–U5 touch four different services and may run in parallel; U6 and U7 ride financial’s executor (U5), and U7 also reuses the web poll fragment U4 lands; U8 deletes the class only once every Batch row is gone and the admin-replay fix: has landed, so no route is ever left under a class that no longer exists.

Follow-ups filed at U0: #1941 (fix: admin-replay — a (created_at)-serving index + a batched, budgeted re-stage on the 10 s domain budget; U8’s prerequisite), #1942 (the deferred consent-kind pickup — rejected in D3 as an ADR-074 blocker), #1943 (a Studio jobs page), #949 (a note: AFCARS generate lands job-first on this substrate).

Test matrix (by risk)

  • Evil: replay the enqueue with the same client_request_id after the job finished → 202, the SAME job, no second execution — including a failed job (replay reports the failure; only a fresh id resumes); poll another actor’s job → the fleet’s typed 403 (the read policy: admin allowed, creator allowed, another worker denied, a service principal that did not enqueue denied), an unknown id → 404; the sweep token is issued by exactly ONE POST; a HEAD on the job GET issues nothing (nothing to issue); a second token POST → 409 sweep-token-issued, an expired preview → 409 sweep-preview-expired; forged kind / input / state / owner_instance / result on the wire → typed 400 (deny_unknown_fields) at enqueue, failed at dispatch; a consent job’s lost_proof can never be adopted by another replica (pinned: a second instance’s scan sees a stale queued import_finalize → failed(lost_proof), never running).

  • Sad (each crash oracle SEPARATELY): (i) PROCESS death mid-attempt (the C20 docker-kill rig) → stale classification after 30 s by another replica’s scan → crash; convergent kinds re-queue and converge (expiry / archive / generation / ncands / previews), consent kinds end failed (finalize stays finalizing and a fresh-id re-POST resumes per record exactly-once; a consented / executing sweep run reads failed with its counters intact); (ii) LEASE-CONNECTION loss (pg_terminate_backend on the detached lease socket while the executor lives) → the engine’s own posture (it converges / the reaper’s self-heal), the job’s heartbeat continues, no false crash; (iii) death in the commit-before-handoff window (kill after the enqueue commit, before the Notify) → the queued row ages past 30 s → lost_proof for a consent kind, adoption + completion for a proof-less kind; (iv) a FAST restart (5 s) → the new process’s boot scan does NOT misclassify the live-looking row; its next scans do once the heartbeat is 30 s stale; the shutdown token during a running attempt → interrupted within 5 s at the engine’s boundary (the seam), nothing half-committed, the convergent job re-queued and completed by the next boot; an attempt whose heartbeat updates 0 rows drops its engine and the reclassified row stays as classified (the later terminal UPDATE loses the CAS, logged); a lost Notify → the 15 s scan runs the row (drain_pending in tests); a knob flipped OFF between enqueue and start → failed(refused_at_start); a paged cases hop 503s at 8 s → the attempt fails with zero rows; a scheduled generator tick holding subsidy-gen → waiting_for_lease outside the permits, then success; three no-progress finalize passes → failed(no_progress) with remaining_staged in the report; an archive pass that archives nothing with more = true → failed(no_progress), never a spin; a CLI poll whose bearer expires → one 401, re-auth, the same job id, no second job.

  • Concurrency: two enqueues of generation for one month → one 202 + one typed 409 JOB_ALREADY_ACTIVE; two archive runs → one job, the second 409; an N-way same-cid volley → one job, ONE held connection (ADR-062), losers Replay; two finalizes of DIFFERENT batches run in parallel (two lease keys), four months of generation → one running + three queued and a finalize still admitted on the reserved permit; a poll during execution observes MONOTONE progress and an immutable terminal state; a live owner’s heartbeat inside 30 s is never reclassified (injected clock); a consented sweep run is invisible to reap_stranded_runs while a scheduled pass runs; two concurrent token POSTs → exactly one token; a crash between the ncands submission commit and job completion CANNOT exist (the same tx) — pinned by killing right after that commit and reading succeeded.

  • Happy: each of the eight backgrounded routes → 202 + Location + JobView{queued} → poll → a terminal result equal to today’s 200 body (the finalize’s = the last FinalizeReport); wait_for_job / the CLI / the xtask return it; the FALSE-Batch routes answer 200 under Standard with their 610 s callers deleted; the two exports answer under Extended; the coverage tests pass with zero Batch rows; every new worker anchor fires its graceful-close + crash legs under fault-preflight; the paged cases GET returns whole referrals, a fixed cohort under as_of, and the same row set as today’s one-shot collector for the same instant.

  • Property: JobView ↔ row round-trip total; the job state machine total (no transition out of succeeded / failed; every attempt outcome maps to exactly one job transition per kind class); dedup_key / lease_key derivation total per kind; the cursor decodes only what it encoded and orders (received_at, id) totally; the claim-joined prune never deletes a job with a live claim (proptest over interleaved windows).

Verification

Per MR: fmt, clippy, the budgets (F-054, B3a / B7 / B8), the lints (validate-authz-coverage with the new GET, contested-census with each new worker anchor, rules check for the two new files, mq-topology unchanged), check-docs, plan-lint, api-docs regen, the pre-push battery. Live probe after U1: POST /v1/placement/expiry-sweep/run { client_request_id } → 202 + Location; the poll reaches succeeded; a repeat with the same id returns the same job; a second enqueue while it runs → 409; docker kill of placement mid-attempt → after 30 s another replica (or the restarted one) classifies crash, re-queues and completes attempt 2; a kill right after the enqueue commit → the queued row is adopted (expiry is proof-less) and completes. After U7: a sweep run reads consented between the 202 and the attempt start, executing under the lease, counters climbing per agreement; the token POST issues once and refuses after 15 min. After U8: rg -n 'CeilingClass::Batch|BATCH_REQUEST_CEILING|BATCH_CALLER_BUDGET|post_batch|post_empty_batch' crates services xtask finds nothing; the ceiling coverage tests enumerate two classes.

Rollout + risks

Per environment: cargo xtask rules-bootstrap the {j}-authz-background_job.json ×2 BEFORE the first image carrying U1 (the deployment guide’s bootstrap step; the devstack seeds it); each service’s background_jobs + _attempts migrations are additive (the sweep-run consented state is a CHECK widening — no floor bump) and ship with the executor in the same image; a route flips to 202 in the SAME release as its CLI / xtask / web caller (every caller mints the now-REQUIRED client_request_id); U8 is last and follows the admin-replay fix:. k8s: the executor drains on SIGTERM inside WORKER_DRAIN_DEADLINE; a job cut by a rollout reads interrupted / crash in its attempts and the guide names the rule per kind (system re-queue for convergent kinds up to three attempts; failed + a fresh-id re-POST for finalize / sweep execute).

Risks: five new BLOCKING worker anchors; every engine gains a token seam (a small, reviewed change each — "unchanged" no longer holds literally); the consent kinds' lost_proof is a NEW visible failure class (the commit-before-handoff window is sub-second but real; the test matrix pins it); the sweep run’s non-resumability becomes visible through the poll; the FFY hop paging is a pre-1.0 S2S change with a fixed-cohort semantic (as_of) the one-shot collector never needed to state; the REQUIRED client_request_id is a wire change on seven routes' callers (double-enqueue on retry is the defect it closes); the canary’s blocking thread outlives a cancelled preview unless the per-item flag is honoured; the regen surface is 8 POSTs + 5 GETs + 1 token POST across toml / api-docs / test-lib / CLI + cli.adoc / 6 web pages.

Rulings (approved 2026-09-17, plan mode)

R1 admin-replay is OUT of scope; its fix: (index + batched, budgeted re-stage) is U8’s prerequisite, and U8 reclassifies it Standard with the measured bound recorded — not a craig-api job table ×8. R2 the reporting → cases whole-FFY hop is PAGED BY REFERRAL under a FIXED cohort (as_of = queued_at; a pre-1.0 S2S change; cases' Batch row and the 610 s CasesClient budget deleted) — not a synchronous cases GET under Extended with a ≤ 300 s proof at Georgia scale. R3 the exports FLIP to Extended sync with the BFF per-request extended budget (#1572 streams the downloads) — not a job with a late-bound digest. R4 the sweep preview token is an explicit single-use issuance POST honouring the 15-min TTL (the job GET stays read-only for every kind) — not a token in the job result. R5 convergent kinds re-queue up to 3 attempts and are adoptable by any replica; consent kinds end failed on lost_proof / crash and are never adopted — not re-queue everywhere, not never re-queue. R6 the FALSE-Batch reversions to Standard with no 202 are confirmed by name: claims/generate, promote execute, archive/purge, afcars/generate. R7 #949 lands job-first on this substrate (U1 gates #949’s real generate) — the sequencing confirmed. R8 the executors are Criticality::Critical — not Observed. R9 the REQUIRED client_request_id body on the three bodyless routes (expiry run, archive run, finalize) and the new field on preview / execute / generation — a pre-1.0 wire change on every caller — confirmed. R10 each engine gains a &CancellationToken boundary check (the ONE change per engine; archive additionally run_passes with preserved state) — "engines unchanged" is read exactly this narrowly. Recorded as decisions with their rejected alternatives: the per-service table behind craig_api::jobs with the dedup_key arbiter and the attempts ledger (D1), claim-joined retention (D1), the generic read-only jobs GET on a BackgroundJob resource type with the fleet 403 (D5), in-memory proofs on an owner-pinned executor with immutable terminal states, lease-key dispatch and a reserved consent permit (D3), executors ON in the devstack (D3), #1572 after and independent (D6), the sweep run’s consented state (D6).

Review log

Rev 1 went to a contextless round 1 (no-ship — 6 blockers, folded into rev 2); rev 2 took the maintainer’s plan-mode gate (21 findings + 4 corrections, each verified against source and folded into rev 3); rev 3 was approved 2026-09-17.

Round Vendor Resolved model Verdict

1

Anthropic — one fresh contextless subagent, the four plan-lifecycle questions, over the plan + the rules

Claude Fable 5.1

no-ship (2026-09-17; 6 blockers — the enqueue arbiter, terminal immutability vs the reap race, no durable input, two poll-authz contracts, token custody, executor concurrency — and 14 observations) → all folded into rev 2

2

open — run by the maintainer through another vendor’s model

open

open

Edit this page · latest