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 (anApprovedActionnever leaves process memory — thelost_proofclass follows from it), ADR-067 (each executor is a PROMOTEDworkeranchor 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.rstables — cases 1, financial 5, placement 1, reporting 4, rules 2, security 2 — plusPOST /v1/admin/events/replay, pushed into Batch UNCONDITIONALLY on every router byCeilingConfig::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, casesGET ncands-export). -
The manifest (route → kind, owning service): placement
POST expiry-sweep/run→expiry_sweep; securityPOST archive/run→archive_run; rulesPOST sets/{id}/promote/preview→promote_preview; reportingPOST ncands/generate→ncands_generate; financialPOST 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): financialclaims/generateand rulespromote(execute) ride the BUDGETEDclaim_first(a 10 sSET LOCAL,request_claims.rs:328-343) in one short tx; securityarchive/purgeis a bounded slice (PurgeParams1..=100, selection EMPTY until DFCS names a schedule); reportingafcars/generateis the #949 zero-record stub (afcars.rs:53). The two reporting exports FLIP to Extended; casesGET ncands-exportis 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 acreated_atrange 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_unbudgetedsitesncands_generate.rs:99(a 10 k-row UNNEST after a whole-FFY S2S hop) andsubsidy_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; callersarchive.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’sCasesClient(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/runandfinalizeare BODYLESS, andPromotePreviewRequest(craig-rules-contracts/src/lifecycle.rs:22) andExecuteSweepRequest(craig-financial-contracts/src/subsidy_review_sweep.rs:170) carry noclient_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 getWORKER_DRAIN_DEADLINE5 s (supervisor.rs:125);expiry_sweep::run_pass(expiry_sweep.rs:256) andfinalizetake no token and check no boundary; the retention engine’srun_passdoes (craig-retention/src/engine.rs:301-345) but rebuilds everyTableStateper 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 EVERYexecutingrun whenever the lease is free,mark_run_failed(:1617-1628) stampsRunCounters::default()— zeros; execute refuses a preview older than 15 min from the run’sstarted_at(:2042-2050,expired). Import finalize’s batch / record ledger IS progress, butfinalize_oneSWALLOWS record-level infra errors intotally.infra_errorsand returnsOkwithstatus = finalizingand rows still staged (import_batch/finalize.rs:240-262) — the xtask’s 20-pass loop is what retries; the response isFinalizeReport { batch_id, status, expected_count, newly_materialized, newly_rejected, remaining_staged, total_materialized, rejections }(:540-548). Generation has NO run row (run_idminted in memory,subsidy/generator.rs:279); every month shares ONE globalsubsidy-gensession 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 reportreceived_at(store/referrals.rs:114-118), so it can appear behind a cursor. -
ADR-074 proofs cannot leave process memory:
ApprovedActionhas private fields and no ctor / serde (subsidy/approvals.rs:472-483);coversre-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(exchangescreening.rs:154-162);ClaimOutcome::Replay { entity_id }re-reads the entity (request_claims.rs:193-196); the house DB-row queue isexchange_send_jobs(SKIP LOCKED+ lease +claim_generationCAS); the supervisor’sCriticality::{Critical, Observed}(supervisor.rs:45-54;watch:316 /watch_optional:338); the request-claims pruner runs onCRAIGREQUEST_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 onspawn_blockingwith 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 parsesallowonly (engine.rs:1565) — list scopes never apply to a GET;rules-bootstrapmust 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-libimpl ServiceClientis at the F-054 16-method ceiling;serde_json::Valueis refused in business logic.
Decisions
-
A job is a LOGICAL resource; executions are ATTEMPTS. Per service, behind ONE
craig_api::jobsmodule (therequest_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 }andbackground_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 aresucceededandfailed, and they are immutable (the terminal UPDATE is byid+version);interruptedandcrashare ATTEMPT outcomes after which the recovery rule (D4) either re-queues the job (attempt, lineage in the attempts table,
1queuedagain — the same row, claim andLocation) or ends itfailed.kindis the closed wire vocabulary of the manifest (expiry_sweep,archive_run,promote_preview,ncands_generate,subsidy_generate,import_finalize,sweep_preview,sweep_execute);dedup_keyper kind (subsidy_generate:<month>,import_finalize:<batch_id>,sweep_execute:<run_id>,promote_preview:<rule_set_id>,ncands_generate:<ffy>, the singletonsexpiry_sweep,archive_run,sweep_preview:<jurisdiction>);lease_keyper kind names the engine lease the job will hold (subsidy-genfor 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 409JOB_ALREADY_ACTIVE. Retention is claim-joined, not arithmetic: the pruner (the claims pruner’s cadence, knobCRAIGBACKGROUND_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 aReplay; 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 arithmeticjobs ≥ claims + 1(claims0means forever). -
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 anIntentV1projection of the jobinput(the rulespromote_rule_setshape).claim_firstis 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’senter_finalizing; sweep execute’s token / CAS / authority refusals with the run movedpreviewed → consented— D6; the arbiter’s 409); the job row is insertedqueuedwithowner_instance= the enqueuing replica andqueued_at = now(); commit; the handler answers 202 with theJobViewbody plusLocation: /v1/<svc>/jobs/{id}. Transport replay vs operator resumption: the SAMEclient_request_id⇒ClaimOutcome::Replay { entity_id }⇒ the same job (202 again, whatever its state — afailedjob replays asfailed); a FRESHclient_request_idis 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:Locationwith an empty body; an optional id (an implicit dual-accept). -
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 (atokio::sync::Notifywake plus a scan every 15 s; the first scan runs at boot), registered with the supervisor asCriticality::Critical(a PROMOTED contestedworkeranchor with drain + crash legs). Dispatch is bylease_key: at most ONE running job per lease key per instance; other queued jobs of that key stayqueuedand 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); awaiting_for_leasephase (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&CancellationTokenparameter 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 withUPDATE … 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’sversion-CAS transition. Stale classification (any replica’s scan, 15 s cadence, boot included): arunningjob whoseheartbeat_atis older than 30 s ⇒ attemptcrash; aqueuedjob whosequeued_atis 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: attemptlost_proof, jobfailed(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 (CASowner_instance+version) and run it frominput+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 everyqueuedrow 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-runningrow and misses it); an overwritable terminal state. -
Recovery policy (per attempt outcome, applied by whoever classifies).
interrupted(the engine returned at a boundary on the shutdown token insideWORKER_DRAIN_DEADLINE5 s) andcrash(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) asattempt + 1up tomax_attempts = 3, thenfailed(exhausted); a consent kind endsfailedon its firstcrash(finalize resumes per record on the operator’s next POST — a fresh id; aconsented/executingsweep run flipsfailedwith its preview burned and its counters PRESERVED — D6) and re-queues only on a gracefulinterruptedwhere the proof is still in memory (same process; drain then restart is a new process — so in practice never: aninterruptedconsent attempt is stamped and the job endsfailed(interrupted)with the re-POST rule inerror.detail). A re-queued job keeps its id, claim andLocation; the poll showsattempt,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). -
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 NEWResourceType::BackgroundJob({j}-authz-background_job.json×2 — admin realm-flat; the creator viaassigned_worker_sub = created_by, which serves humans AND service principals) — no nil-id exceptions, twin parity bytexas_authz_inputs_are_the_georgia_twins_plus_the_declared_extras, theresource_type_iter_covers_all_known_typescount 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-storeon 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’sresourcelink 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). -
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 ofTableState`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 atengine.rs:308-316is the loop bug); it endssucceededatmore = false,failed(no_progress)when a pass archives zero batches whilemorestays true,interruptedon the token; the D11 consent knob is re-checked at START (refused_at_start); the endpoint’s freshCancellationToken::new()(archive.rs:164) is retired. -
promote_preview: result ={ preview_id, report }; thepreviewsrow still inserted at the end;--confirm-preview <preview_id>and the executeIntentV1unchanged; the canary checks the cancel flag per item. -
ncands_generate: the job’sinputcarriesreporting_year+as_of = queued_at. The cases hop becomes PAGED BY REFERRAL:GET /v1/cases/ncands-export?ffy&as_of&after&limit≤500returns whole referrals (each with ALL its allegation rows — a referral is never split across pages) from the FIXED cohortreceived_at ∈ [ffy) AND screened_in AND created_at ≤ as_of(a referral converted after enqueue is excluded deterministically, whatever its reportreceived_at), ordered(received_at, id),after= an opaque cursor over the LAST SCANNED referral,next = nullon exhaustion (an all-unclassifiable page returns zero rows and a non-nullnext); each page under the 8 s hop budget. Completion is atomic with the domain write: the job’s final tx inserts the submission withid = job.id(ON CONFLICT (id) DO NOTHING+ re-read), its rows, AND the job’sresource_id+ terminalsucceeded— one commit, no window; a recovery attempt first reads the submission byjob.idand, if present, completes without regenerating. A page failure fails the attempt with zero rows written. -
subsidy_generate: gains the REQUIREDclient_request_id(pre-1.0Changed) and asubsidy_generation_runsrow fed by BOTH initiators;lease_key = subsidy-gen(one running month per instance; the hourly tick is awaiting_for_lease); result =GenerationReport. -
import_finalize: gate tx sync (enter_finalizing); the job runs PASSES of the unchanged per-record engine untilstatus ∈ {finalized, aborted},progressfrom the record ledger,result = FinalizeReport(the LAST pass’s — it carries status, remaining, totals, rejections); a pass withremaining_staged > 0that materialized and rejected nothing counts as no-progress; three consecutive ⇒failed(no_progress)with the report (the swallowed infra errors offinalize_oneare 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 jobresultcarriestoken_state: available. Token issuance is an explicit POST,POST /v1/financial/subsidy-reviews/sweep/runs/{run_id}/token: requires the jobsucceeded, the runpreviewedandstarted_at + 15 min > now(else 409sweep-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 409sweep-token-issued; the plaintext never rests. -
sweep_execute: the enqueue tx performs today’s pre-CAS refusals and moves the runpreviewed → consented(a NEW run state: the token burned, the set pinned, no lease held); the attempt movesconsented → executingunder the sweep lease;reap_stranded_runskeeps reaping ONLYexecuting(aconsentedrun is the job’s, never the lease reaper’s); alost_proof/crashon the job flips its runfailedwith the accumulated counters PRESERVED —mark_run_failedand the per-agreement tx now commit counters as they go (no moreRunCounters::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.
-
-
The class deletion is the close-out.
CeilingClass = Standard | Extended;BATCH_REQUEST_CEILING,BATCH_CALLER_BUDGET, the 4-argwith_durationsand the admin-replay auto-entry, bothclaim_first_unbudgetedsites, CLIpost_batch+ theclients/mod.rs:130macro arm, the xtask mirror const, reporting’shop_budget, and the censusedceilings.rsBatch 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: aBatchvariant left in place. -
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-waitprints 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 proxiesGET /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 andxtask/route-to-client-method.tomlregenerated per unit (the unmappedncands/{id}/exportand the two/export/downloadGETs 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 CHANGELOGChangedentry (the old 200 body → the 202JobView+ poll; the new REQUIREDclient_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 |
1 |
U1 |
#1933 |
The substrate + the pilot: |
8 |
U2 |
#1934 |
security |
3 |
U3 |
#1935 |
rules |
3 |
U4 |
#1936 |
reporting |
5 |
U5 |
#1937 |
financial |
5 |
U6 |
#1938 |
financial |
5 |
U7 |
#1939 |
financial |
5 |
U8 |
#1940 |
Close-out (after the admin-replay |
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_idafter the job finished → 202, the SAME job, no second execution — including afailedjob (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 → 409sweep-token-issued, an expired preview → 409sweep-preview-expired; forgedkind/input/state/owner_instance/resulton the wire → typed 400 (deny_unknown_fields) at enqueue,failedat dispatch; a consent job’slost_proofcan never be adopted by another replica (pinned: a second instance’s scan sees a stale queuedimport_finalize→failed(lost_proof), neverrunning). -
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 endfailed(finalize staysfinalizingand a fresh-id re-POST resumes per record exactly-once; aconsented/executingsweep run readsfailedwith its counters intact); (ii) LEASE-CONNECTION loss (pg_terminate_backendon 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 falsecrash; (iii) death in the commit-before-handoff window (kill after the enqueue commit, before the Notify) → the queued row ages past 30 s →lost_prooffor 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 →interruptedwithin 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_pendingin 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 holdingsubsidy-gen→waiting_for_leaseoutside the permits, then success; three no-progress finalize passes →failed(no_progress)withremaining_stagedin the report; an archive pass that archives nothing withmore = 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), losersReplay; 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); aconsentedsweep run is invisible toreap_stranded_runswhile 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 readingsucceeded. -
Happy: each of the eight backgrounded routes → 202 +
Location+JobView{queued}→ poll → a terminalresultequal to today’s 200 body (the finalize’s = the lastFinalizeReport);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 newworkeranchor fires its graceful-close + crash legs underfault-preflight; the paged cases GET returns whole referrals, a fixed cohort underas_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 ofsucceeded/failed; every attempt outcome maps to exactly one job transition per kind class);dedup_key/lease_keyderivation 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 |