Plan: The collection run as a background job, and on a schedule
Status
Done (2026-11-30) — a collection runs as a background job on craig-exchange, which mounts the job substrate for it: the run route enqueues and answers 202, the run stops cleanly on a shutdown and is run again, and a schedule, off by default, collects each consented collection when it is due.
Closes: #3190. Epic: &124. Relates to: #3188 (the collection run this changes), ADR-068 (the request ceiling
and its background-jobs amendment), ADR-089 (a collection is a partner crate’s). Tree: written against main at
e6aec1c68.
Maintainer (2026-11-30): the run route keeps only the refusals that need no lookup (an undeclared leg, consent
off); a partner that cannot be resolved or an agreement that does not admit fail the job as refused_at_start.
Context
POST /v1/exchange/collections/run (#3188) runs a collection inside one HTTP request. A request is cut at 20
seconds (craig_common::ceiling::STANDARD_REQUEST_CEILING), and the run posts each admitted report to its owner one
at a time, so it finishes only for a small document. A run the ceiling cuts answers 504 and leaves no transaction
and no event. ADR-068 sends such work to a background job (craig_api::jobs), which craig-financial,
craig-placement, craig-reporting, craig-rules and craig-security mount and craig-exchange does not. The pilot is
placement’s expiry sweep (services/craig-placement/src/jobs.rs, api/expiry_sweep.rs); this plan follows its
shape. The weekly file should also be collected without an operator.
Scope
In scope: craig-exchange mounts the substrate (D1); the collection run is a job kind (D2); the route enqueues (D3); the run checkpoints and records an interruption (D4); a schedule (D5); the CLI, the test client and the journey (D6).
Out of scope: resuming a run in the middle of a document (a rerun posts every report again, as today); posting reports in parallel; one interval per interface; any change to what a collection admits or what its owner stores.
Design
D1. craig-exchange mounts the substrate
-
Migration
services/craig-exchange/migrations/20261130120000_background_jobs.sql: the tables, checks and indexes ofservices/craig-placement/migrations/20260918120000_background_jobs.sqlunchanged (background_jobs,background_job_attempts, the active-dedup unique index, the two scan indexes,request_claims_entity_id_idx), and one more index for D5’s read:exchange_transactions (exchange_type, initiated_at DESC) WHERE origin = 'collection'. Additive: noschema_compat_floorbump. -
Runtime in new
services/craig-exchange/src/jobs.rs:SERVICE_SLUG = "exchange"andbuild_runtime(pool, collections), which registers D2’s kind. It is the one constructor, used byruninlib.rsand by the tests. -
Poll route in new
services/craig-exchange/src/api/jobs.rs: the thin wrapper overcraig_api::jobs::get_jobthatservices/craig-placement/src/api/jobs.rsis, atGET /v1/exchange/jobs/{id}, registered in the service’s OpenAPI with thecraig_common::jobsschemas. Thebackground_jobauthorization ruleset is per resource type and both jurisdictions' layers already carry it, so no configuration repository changes. -
Workers in
services/craig-exchange/src/lib.rs: the runtime is layered asExtension<Arc<JobsRuntime>>; the executor is watched asbackground-jobs(Critical) and added toEXPECTED_WORKERS; the pruner is spawned withbackground_jobs_window_days(). The executor’sworkers.watch(call is the last.watch(call in the file, so the existing contested anchors keep their index and the new one isworker.craig-exchange.main.watch.4. -
Baselines:
xtask/baselines/authz-engine-wired.tomlgainsservices/craig-exchange/src/api/jobs.rs::get_job;xtask/baselines/contested-surfaces.tomlgains the new anchor ascoveredwith a drain leg and a crash leg (Tests).
D2. The job kind
CollectionRunKind in services/craig-exchange/src/jobs.rs: KIND = "collection_run", CONSENT = false, input
CollectionRunInput { interface, leg } (strict), dedup_key = "collection_run" (one active run per deployment, as
the lease is today), lease_key = Some("collection"), three attempts. One attempt is one
CollectionRuntime::run (D4) for the enqueuing admin. Its output is CollectionRunReport { transaction_id, status,
failure, applied, stale, not_listed, unattributable, failed }: today’s 200 body plus failure, the class of a
failed run.
Two vocabularies exist today and both stay. The run’s summary and its event say completed or failed
(status_of in collections/mod.rs), and that is the status of the job’s result. The ledger row says success
or failed (create_collection_transaction in store/transactions.rs), and that is what D5 reads.
What a job’s end says about the record:
-
A job that ends
succeedednames a recorded run in its result, whether that run completed or failed (the_job_result_carries_the_transaction_status_and_counts,an_unreadable_document_succeeds_the_job_as_a_failed_run). -
A job refused at its start called no partner and recorded nothing (
each_refusal_at_start_fails_the_job_with_its_classasserts the partner stub saw no request and the ledger holds no row). -
An interrupted attempt records its run (D4) and the job is re-queued, so a job that ends
failedwithexhaustedhas a recorded run for each attempt (an_interrupted_run_is_recorded_and_its_rerun_completespins the record of one attempt). -
A store error ends the job
engine_failed. Whether a run was recorded then depends on where the error fell: the transaction row and the event are written byclosein one database transaction, as today.
| The run | The job |
|---|---|
Ran to its end, every admitted report taken |
|
Ran to its end, the owner did not take every report |
|
The partner’s document could not be read (a 503 today) |
|
The lease is held (a scheduled run is in progress) |
|
Consent off, the leg undeclared, no one usable partner, or the agreement does not admit, read at attempt start |
|
Interrupted by shutdown (D4) |
the attempt is |
A store or staging error |
|
The doc comments of JobFailure::RefusedAtStart (crates/craig-api/src/jobs/kind.rs) and of the
refused_at_start token (crates/craig-common/src/jobs.rs) say "a consent knob"; they are widened to "a consent
knob or a precondition" in the same change. No token is added.
D3. The route enqueues
POST /v1/exchange/collections/run (services/craig-exchange/src/api/collections.rs) takes { client_request_id,
interface, leg } and, after the admin check it has today:
-
answers 400
collection-undeclaredwhen the deployment holds no such collection, and 409collection-disabledwhen the interface’s consent is off. Both are read from the registries and the settings, with no lookup; -
runs
craig_api::jobs::claim_enqueue::<CollectionRunKind>under the claim scopeexchange.collection_run(entity kindbackground_job), whose intent is{ interface, leg }, built in newservices/craig-exchange/src/api/intents/jobs.rsasservices/craig-placement/src/api/intents/jobs.rsbuilds the sweep’s; -
answers 202 with
Location: /v1/exchange/jobs/{id}and theJobView. The sameclient_request_idreplays the same job whatever its state; a fresh one while a run is queued or running is 409job-already-active.
The route no longer answers collection-running, collection-partner-unresolved, agreement-does-not-admit or
partner-unreachable. Those four constants in crates/craig-common/src/error.rs (problem_types) have no other
user and are deleted. The handler lists 202, 400, 401, 403, 409, 413, 415 and 422 in its responses(…).
D4. Checkpoints, and an interrupted run is recorded
CollectionRuntime::run (services/craig-exchange/src/collections/mod.rs) takes two more arguments: who runs it,
Initiator::{Operator(Uuid), Scheduled}, and a &JobBoundary.
-
boundary.checkpoint()is called before each admitted report is posted, andset_totaldeclares their number, so the poll’sprogresscounts reports. -
The partner fetch and each post are awaited together with
boundary.token().cancelled(). A post may take its whole hop budget (8 s), which is longer than the worker drain deadline (5 s): without this an interrupted attempt would be killed mid-post, read as a crash, and leave no record. -
On an interruption the run closes as it closes any other end: one
exchange_transactionsrow (failed,error_message = interrupted) and oneexchange.collection_completedevent, with the counts so far and every unposted report countedfailed. It then returnsRefusal::Interrupted, which the kind maps toJobFailure::Interrupted. The rerun posts every report again; the owner answersstalefor those it holds. -
GIVE_UP_AFTER(three unwell answers in a row end the posting) stays.
D5. The schedule
-
Setting:
ExchangeSettings.collection_schedule.interval_secondsincrates/craig-common/src/settings.rs(CRAIG_EXCHANGECOLLECTION_SCHEDULEINTERVAL_SECONDS, default 0). It is a group of its own becauseCOLLECTIONS__*is the consent map keyed by interface. 0 spawns no worker. -
Worker
collection-schedule(Observed, inEXPECTED_WORKERS), spawned inlib.rsthrough the lastwatch_optional(call in the file (new anchorworker.craig-exchange.main.watch_optional.5). It ticks everymin(interval, 60 s)and, for each collection the registries hold whose interface is consented, callsCollectionRuntime::run_if_due. -
Due is decided under the run’s lease, from the ledger: a collection is due when the newest
origin = 'collection'transaction of its<interface>.<leg>is older than the interval, or there is none (store::transactions::last_collection). So a restart or a second replica does not fetch a document that was collected within the interval, and an operator’s run counts. A run of any status counts: a failed scheduled run waits for the next interval. A run refused before the partner leaves no row and is tried again each tick; the refusal is logged when it changes, not every tick. -
Actor: a scheduled run records
initiated_by = "system"; its event carries nouser_id, and its audit header names the actor throughAuditActor::namedon that text, as the expiry sweep’s events do. The publisher (publish_collection_completedinservices/craig-exchange/src/events.rs) gets a row inSYSTEM_OR_RECORDLESSand the ceiling goes from 54 to 55 (services/craig-security/src/audit_header_census_tests.rs): a system-actor act is a visible edit. -
Heartbeat:
collection-schedulerecords a success (worker_heartbeat::record_success) at the end of a tick only when both hold: no due collection was refused or errored on this tick, and the newest ledger row of every consented collection that has one hasstatus = 'success'(store::transactions::last_collectionreturns the row’sinitiated_atandstatus). So a failed run withholds the heartbeat on its own tick and on every later tick until a run of that collection succeeds, the scheduled one an interval later or an operator’s. The gauge goes stale past three ticks, which is the deployment guide’s alert rule. -
The job and the schedule share the lease: a job that finds it held waits (
waiting_for_lease); a tick that finds it held skips.
D6. The CLI, the test client and the journey
-
craig exchange collection-run(services/craig-cli/src/cmd/exchange.rs, dispatched with the session ashome expiry-sweepis inservices/craig-cli/src/main.rs): posts{ client_request_id, interface, leg }, thenwait_for_job(session, "exchange", id, format)andprint_terminal;--client-request-idand--no-waitas the sweep has. -
crates/craig-test-lib/src/clients/exchange/service.rs:run_collectionanswers aJobView; tests wait withcraig_test_lib::jobs::wait_for_job. -
tests/e2e/lib/doe-education.ts:collect()sends aclient_request_id, pollsGET /v1/exchange/jobs/{id}until the job is terminal, and returns itsresult.
Steps
One MR each, in this order.
-
The plan page.
-
The job (D1 to D4, D6). The wire change, the CLI and the journey land together, since each breaks without the others.
-
The schedule (D5). Its MR closes #3190.
Erratum (2026-11-30): Initiator lands with step 3, where its Scheduled variant has a caller; in step 2 run
gains the boundary and keeps actor: Uuid.
Erratum (2026-11-30): a post’s budget is 3 s (POST_TIMEOUT), not 8 s, so it is the partner fetch (a 30 s send
budget) that outlasts the 5 s drain deadline. D4 stands: both are awaited with the token.
Erratum (2026-11-30): the run route loses its // authz: skip comment and its authz-exempt-routes.toml row. It
answers the job read back through the poll’s authorization, on a fresh enqueue and on a replay, so every 202 rests
on an engine decision; the coverage gate refuses a skip comment beside an engine call, and the devstack’s authz
witness refuses a 2xx with neither. The operator check is unchanged and still first.
Erratum (2026-11-30): a run a shutdown interrupted does not count toward the interval (maintainer, 2026-11-30): the
schedule runs the collection again at its next look. D5 said a run of any status counts; every other failed run
still does. The heartbeat reads the newest run that counts.
Erratum (2026-11-30): the event’s audit actor is built from the optional subject the event already holds
(map_or(System, Sub)), not through AuditActor::named on text. The header is the same.
Risks
-
Two runs at once (two enqueues, a job beside a scheduled run, two replicas) — fail-closed: the dedup key refuses a second active job, and the lease makes a job wait and a tick skip. Tests:
two_enqueues_leave_one_active_job,a_job_waits_while_the_schedule_holds_the_lease,a_tick_skips_a_collection_another_run_holds. -
An interrupted run loses reports or applies them twice — silent. Mitigation: the interruption is recorded with its counts, the substrate re-queues the attempt, and the rerun posts every report again against an owner that answers
stalefor what it holds:an_interrupted_run_is_recorded_and_its_rerun_completes. -
An interruption waits out a post and the attempt is killed — silent (no record of that attempt). Mitigation: D4’s await on the token:
an_interruption_during_a_post_does_not_wait_for_it. -
The schedule fetches on every restart or replica — silent (repeat fetches, audit noise). Mitigation: D5’s due read under the lease:
a_collection_recorded_within_the_interval_is_not_due,two_ticks_run_a_due_collection_once. -
A failed scheduled run waits a whole interval — silent. Mitigation: the run is recorded
failedwith its event, and the heartbeat stays withheld until a run of that collection succeeds, so the staleness alert fires and holds:a_failed_run_withholds_the_heartbeat_until_a_run_completes(the failing tick records no success; the next tick, on which nothing is due, records none either; after a completed run the tick records one). An operator runs it by hand. -
Consent is turned off, or the partner removed, between the enqueue and the run — fail-closed: read again at attempt start:
each_refusal_at_start_fails_the_job_with_its_class. -
A new
watchcall renumbers the contested anchors — fail-closed (cargo xtask contested-censusrefuses the drift). Mitigation: both new calls are last in the file. -
An older CLI or script posts the old body — fail-closed: 422, no
client_request_id. The changelog says so. No compatibility shim. -
A scheduled run has no acting person and nobody decided that — silent. Mitigation: the allowlist row and the raised ceiling, in review.
-
A queued job outlives the binary that understands its input — fail-closed: strict input decode fails the job
engine_failed(input_decode), the substrate’s rule.
Tests
-
Concurrency:
two_enqueues_leave_one_active_job(the route, twice, fresh ids: one 202, one 409job-already-active, one row);a_job_waits_while_the_schedule_holds_the_lease;a_tick_skips_a_collection_another_run_holds;two_ticks_run_a_due_collection_once. The existinga_second_collection_run_is_refused_while_one_holds_the_leasekeeps the engine’s lease. -
Contract (wire):
the_run_route_answers_202_with_the_job_and_its_location;the_job_result_carries_the_transaction_status_and_counts;an_unreadable_document_succeeds_the_job_as_a_failed_run;the_intent_is_keyed_on_the_interface_and_leg;the_route_documents_every_refusal_it_answers(existing, for the new status set);a_scheduled_run_names_the_system_and_no_user;the_collection_schedule_is_off_unless_an_interval_is_set; the CLI’scollection_run_posts_the_interface_and_leg_to_the_run_route(existing; the body now also carries the id) andcollection_run_waits_for_the_job_and_prints_its_result. -
Property:
a_collection_is_due_exactly_when_the_interval_has_passed(proptestover the last-run instant, now and the interval: no panic, and due if and only if the difference is at least the interval or there is no run). -
Regression: the tests of
services/craig-exchange/src/collections/tests.rskeep their names and assertions and driverunas an operator with a detached boundary. Inservices/craig-exchange/src/api/collections_refusal_tests.rs,each_refusal_answers_its_own_status_and_problem_typecovers the two refusals the route still answers, and the four that moved are asserted byeach_refusal_at_start_fails_the_job_with_its_class.services/craig-exchange/tests/api/outbound_triggers/collections_evil.rskeeps its three tests and adds a body with noclient_request_idto the refused bodies. -
Devstack:
a_run_longer_than_the_request_ceiling_completes(the owner stub delays each post so that the run takes longer thanSTANDARD_REQUEST_CEILING; the job succeeds with every report applied);an_interrupted_run_is_recorded_and_its_rerun_completes;an_interruption_during_a_post_does_not_wait_for_it;a_collection_recorded_within_the_interval_is_not_due;a_failed_run_withholds_the_heartbeat_until_a_run_completes(the tick returns whether it recorded a success, and the test asserts that value on three ticks: the failing one, the next with nothing due, and one after a completed run);each_refusal_at_start_fails_the_job_with_its_class. -
Contested legs (registered in
contested-surfaces.toml): for the executor,the_collection_job_executor_drains_promptly_on_cancelanda_stale_collection_job_is_classified_crash_and_its_requeue_completes; for the schedule,the_collection_schedule_drains_promptly_on_cancelanda_scheduled_run_cut_before_its_close_leaves_no_record_and_is_due_again. -
Journey:
tests/e2e/specs/journey-lifecycle-reunification.spec.tscollects through the polled job, its education assertions unchanged.
Delivery
-
Canonical page:
docs/modules/ROOT/pages/deployment-guide.adoc, section "Collecting DOE’s weekly student data": the run as a job, what its states mean, the schedule and its variable; and acollection-schedulerow in that page’s worker-heartbeat table. -
Other docs, with the step that changes the surface:
docs/modules/ROOT/pages/api/craig-exchange.adoc(regenerated bycargo xtask api-docs);cli.adoc(collection-run);configuration-reference.adoc(the schedule variable);implementation-guide.adoc(the two routes' rows);shared-crates.adoc(the removed problem types, the setting). -
CHANGELOG entry:
changelog.d/3190.collection-job.changed.adoc(step 2; Ops: the route’s body and answer changed, and scripts must sendclient_request_idand poll) andchangelog.d/3190.collection-schedule.added.adoc(step 3; Ops: the variable, off by default). -
Plan page: committed as
docs/modules/ROOT/pages/plans/collection-background-job.adocwith step 1,In progressat step 2,Doneand archived at step 3. -
Close: step 3’s MR closes #3190, with the merge SHA noted on it and on &124.
Review log
| Round | Vendor | Resolved model | Verdict |
|---|---|---|---|
1 |
Anthropic |
vertex-anthropic/claude-fable-5-2 |
FLAGS (2): the heartbeat mitigation was defeated by the due rule (fixed: the heartbeat follows the newest run’s status, and the test spans the next tick); D2’s "exactly when" claims contradicted D4 (fixed: four statements, each with its test). |
2 |
vertex-gemini/gemini-4-carbon |
FLAGS (1): the ledger row’s status is |
|
3 |
Human |
the maintainer |
Approved (2026-11-30). |