Worker Supervision & Readiness (epic &76 / #1186)
Status
Program: Done (2026-07-31) — all seven units merged (!1115 U0, !1116 U1, !1117 U2, !1118 U3, !1119 U4, !1120 U5, !1121 U6); #1186 closed as the program-complete act; follow-ups #1226–#1237 filed.
| Unit | Description | Status |
|---|---|---|
U0 (#1220) |
ADR-061 + this plan page + nav; ADR-003 Amendment #1186 |
Done (2026-07-31) — MR !1115; J-review J5 tense findings remediated pre-commit; first battery push env-failed (host I/O starvation, root-caused, receipts on #1220), retried green |
U1 (#1221) |
|
Done (2026-07-31) — MR !1116; deviation from D1 recorded: |
U2 (#1222) |
|
Done (2026-07-31) — MR !1117; deviations from D2 recorded: (1) |
U3 (#1223) |
|
Done (2026-07-31) — MR !1118; RED/GREEN JUnit receipts uploaded to the GitLab project (RED = pre-U2 devstack, 7/7 failed |
U4 (#1186) |
Option-returning helpers (interval arm only), retention-test updates, AuthzBootSpec/Result seam, 8-service |
Done (2026-07-31) — MR !1119; drift receipts uploaded (RED 10/10 |
U5 (#1224) |
Exchange send-dispatch JoinSet drain + |
Done (2026-07-31) — MR !1120; J-review 1 P1 (JoinSet reaping) + 1 P2 (detach-not-abort doc honesty) + 3 P3s (4s drain margin, #1224 tag, parking_lot test sink) all remediated pre-commit; the craig-api test-sink precedent (supervisor.rs, std::sync::Mutex) deferred to #1237 |
U6 (#1225) |
The doc inventory sweep + CLAUDE.md decision + scorecard |
Done (2026-07-31) — MR !1121; CLAUDE.md decision N/A recorded; J-review CLEAN (one P3 wording nit remediated) |
Program: child epic &76 (under &74; the &75 restructure precedent) — one issue/branch/MR
per unit; each unit’s MR Closes its own child issue; U4’s MR uses Relates to #1186, and
#1186 closes MANUALLY after U6 lands.
Design authority: ADR-061
(decisions + alternatives); THIS page carries the mechanics.
Follow-ups filed at preflight (all related to #1186): #1226 JWKS loop, #1227 OIDC loop,
#1228 eval-thread liveness, #1229 web/intake/keyring story, #1230 dispatch-panic counter,
#1231 heartbeat/last-success metrics, #1232 dlq early-return live-handle, #1233 token
dual-path consolidation, #1234 healthz raw dep-error strings, #1235 publisher-channel
health, #1236 pool-probe token+registration.
Context
Verified W3c+W3d: every long-lived worker handle fleet-wide is discarded or
retained-unobserved; no supervisor; a panicked task vanishes. LIVE-CONFIRMED during
planning: the Extension(MqHealth) never reaches the outer-router health routes
(crates/craig-bootstrap/src/lib.rs:175 vs crates/craig-api/src/lib.rs:318-321), so
healthz reports rabbitmq: "n/a" on connected services and readyz has been DB-only
fleet-wide. The "ADR-022 / Step 6" comment at lib.rs:313 is a false citation (real
source: the archived platform-stabilization plan D8 Step 6) — corrected in U2.
User-decided policy (fixed): fail-fast on Critical death; the MqHealth gap is fixed inside this program (U2 carries it). Honest observability: after fail-fast cancels, a fresh probe may see connection refusal rather than 503 — either fails the probe, so the pod leaves rotation; no reliable-network-503 claim is made. Known limitation (stated): HANDLE-liveness, not functional health (#1231).
Design mechanics
D1 — Supervisor + WorkerHealth (crates/craig-api/src/supervisor.rs, U1)
-
Supervisor::install()— creates THE process token, spawns + registers the signal→token bridge as Critical (signal-bridge); the bridge body isselect!(shutdown_signal(), token.cancelled())thencancel()— a worker-death fail-fast COMPLETES the bridge (its watcher classifies Completed via the token branch); a signal-only await would stall every crash exit for the full drain deadline. Replacesshutdown_token()at the 8 mains. -
Supervisormethods:token(),expect(&[WorkerSpec])(manifest — createsMissingentries at READ time only: expected ∧ neither registered nor Disabled; registration never validates against it; no manifest ⇒ permissive, so U2 ships manifest-less and U4 adds them;signal-bridge/idempotency-cleanupare implicit),drain(deadline)(bounded join of the watcher tasks;WORKER_DRAIN_DEADLINE = 5s; timed-out names reported
warn!),check_exit()(Err naming dead/missing criticals → mains exit NONZERO),health(), andstandalone()(public test constructor: token, NO bridge — the U3 capstone drives drain/check_exit through it; doc’d as test-support). -
WorkerHealth(Clone) is the REGISTRY HANDLE —Arc<inner{registry: parking_lot::RwLock <BTreeMap<&'static str, Entry>>, manifest, token}>— carrying register AND read:watch(name, criticality, JoinHandle<()>) → Result<(), RegisterError>(duplicate name = typed error — no stale-watcher race),watch_optional(None ⇒ Disabled entry),mark_disabled,any_critical_dead_or_missing(),snapshot()(name-sortedWorkerReport { name, criticality, state }),detached()(own never-cancelled token — the 3 harness AppState sites; harnesses register only Observed workers).ApiServer::router’s `build_protected_routesregistersidempotency-cleanupObserved viastate.workers.watch(..). -
Types:
Criticality { Critical, Observed };WorkerState { Running, Disabled, Completed, Dead { panicked: bool }, Missing }(full panic text ONLY in the registry for logs/check_exit — never on the wire);RegisterError(&'static str);CriticalWorkerDied { names: Vec<&'static str> };DrainReport { drained, timed_out }. -
The order-serializing watcher (fixes causality loss):
select! { biased; token.cancelled() ⇒ { classify(handle.await): panic ⇒ Dead{panicked}, else Completed }, &mut handle ⇒ { panic ⇒ Dead{panicked}; CleanExit/Aborted ⇒ Dead (exited while shutdown NOT requested) } }— biased TOWARD the token so a tie classifies Completed (benign: loses a diagnostic during real shutdown, never a false Dead on clean SIGTERM). RECORD happens BEFORE the Critical-deathtoken.cancel()(load-bearing for test sync). Observed deaths alwayswarn!structured; Critical deathserror!+ cancel. -
Testability: the watcher converts
Result<(), JoinError>to internalExitKind { CleanExit, Panicked(String), Aborted }(JoinError is unconstructible); pureclassify(kind, shutdown_observed_first)carries the full matrix; conversion covered by real-spawn tests.panic_message_bounded(exported from craig-mq withcontain) bounds the log text.
D2 — readiness semantics (U2; pre-1.0 behavior change)
-
AppState { db, auth, mq: MqRequirement, workers: WorkerHealth };MqRequirement::{Required(MqHealth), NotApplicable}— no Option, no Default. 8 production + 3 harness literal sites (caseskeyed_harness.rs:277, securityauthz_fallback.rs:196/archive_engine.rs:163) fixed in-unit; harnesses useNotApplicable+WorkerHealth::detached().StandardExtensionContext.mq_health+ its Extension layer DELETED. -
Pure seams:
evaluate_readiness/evaluate_health— handlers are ≤10-line wrappers; the workers-first short-circuit (DB/MQ checks run ONLY when workers pass) is pinned by pure unit tests, no timing inference. -
/readyz: 503 +Retry-After: 5+ body"not ready: <check[, check]>"on Critical Dead/Missing (first, short-circuit) OR DB fail OR Required-MQ disconnected. Observed never gates. MQ arm reflects the PARENT connection only (documented; #1235). -
/healthz:checks.workers= typed per-worker{ criticality, state, panicked? }; no raw text. Pre-existing raw DB-error strings → #1234. -
ApiServer::serve(router, port, token)→serve_with_listener(listener, router, token)(+ injectable drain deadline; prod constHTTP_DRAIN_DEADLINE = 20s): select graceful-completion vs cancelled→deadline → serve RETURNS + warn!. No in-flight-teardown claim (connection tasks end at process exit). Mains:serve(…).await?; supervisor.drain(WORKER_DRAIN_DEADLINE).await; supervisor.check_exit()?;.
D3 — fleet registration (U4)
spawn_workers gains supervisor: &Supervisor (expect once + health() for the
watches); boot fns (boot_archiver, boot_authz_engine) receive WorkerHealth only.
| Service | Critical | Observed |
|---|---|---|
all 8 |
|
|
cases |
— |
|
composition |
|
— |
exchange |
|
|
financial |
|
|
placement, reporting |
|
— |
rules |
|
— |
security |
|
— |
-
= knob-gated (
watch_optional/mark_disabled; thespawn_local_sweepconsumers are knob-gated once the helper returns Option — devstack windows default nonzero, so both run Running). Devstack defaults for the exact-set drift tests: financial’s subsidy-generator IS enabled (docker-compose.yml:441, 3600s) — Running; review-sweep Disabled.decision-refresh(the #1188 sweep, itself a new detached handle at rules main.rs:227) registers Critical. -
Helper rule (drift-proof, boot-safe): the boot-level CONSENT gate stays caller-side (rules/security check
enabledbefore touching object-store config; a disabled archiver must never fail boot; the helper’s duplicate check is defense-in-depth). Only the interval/window arm moves in:spawn_local_sweep→ None onwindow_days == 0;spawn_archive_worker→ None oninterval_seconds == 0. Consent-disabled paths callworkers.mark_disabled("retention-archive"). Direct helper tests + the worker.rs:191 retention-test updates. -
AuthzBootSpecgainspub workers: WorkerHealth; boot registers invalidation + ttl Critical;AuthzBootResultdrops ALL THREE handle fields (warmup: dropped-detached, bounded one-shot, never registered); false Drop-semantics docs corrected. -
Composition harness (new work):
TestConfig.composition_url+CRAIG_TEST__COMPOSITION_URL+ defaulthttp://localhost:8009; the manual.ports.envwriter (xtask docker.rs:671 area) gains composition + writer/build_env tests;devstack_available()+ its "eight endpoints" doc updated; NEWservices/craig-composition/tests/api.rs
tests/api/health.rscarrying composition’shealthz_reports_rabbitmq_ok(the 8th MQ pin — no RED receipt possible, its harness postdates U2; the live pre-fix curln/areceipt covers the class) + its workers drift test.
D4 — exchange dispatch (U5) and out-of-scope
U5: the send worker owns a JoinSet for in-flight dispatches (bounded drain on shutdown;
drop-abort stragglers is lease-safe per #1185); dispatch body wrapped in
craig_mq::contain → error!(job_id, panic); injectable seam + REQUIRED fault test;
non-propagation to the Critical parent is ADR-061-justified. Out-of-scope surfaces:
ADR-061 §Consequences + the follow-up list above.
Tests
Devstack tests #[ignore = "requires devstack"]; every test @axis:-tagged. (The
test-authoring guard-vs-F-024-lint standards contradiction is escalated:
claude-quickstart#27 note 3625381094; this plan follows the executable lint.)
-
U1: full pure
classifymatrix; real-spawn conversion (panic/clean/abort); deterministic order tests via oneshot gates (cancel-then-complete ⇒ Completed; complete-then-observe-then-cancel ⇒ Dead — no sleeps); duplicate registration typed Err; Critical CLEAN early exit ⇒ Dead + cancel; Observed death ⇒ bounded-poll Dead + token live + structured warn (tracing capture); Missing gates / Disabled never;check_exitnames+ordering;draintimeout reporting;connect_lazy_with_never_dials. -
U2: pure-seam short-circuit-order pins; oneshot body discrimination (
"not ready: workers"vs"not ready: database"— probative: a gate-less build yields the other body); typed healthz worker-block shape. -
U3 (
crates/craig-api/tests/fault/): the capstone chain (Supervisor::standalone()+serve_with_listener, pre-bound listener + request barrier: Critical panic → registry Dead → token cancelled → serve returns within deadline+ε → drain →check_exitnames the worker); hung-request forced-close (injectable deadline); MQ-disconnect readyz via a DEDICATED test lapin connection (poisons nothing); healthz-degraded with HEALTHY deps; 7×healthz_reports_rabbitmq_ok. RED mechanics: authored on U3’s branch, run against the still-pre-U2 devstack DURING U2 development, receipts copied aside (/tmp/1186-u3-{red,green}.xml— nextest overwrites fixed junit paths); GREEN post-U2-rebuild. -
U4: exact-set drift tests per service asserting the FULL
name → (criticality, state)map (Running/Disabled per devstack defaults; all 8 include outbox, signal-bridge, idempotency-cleanup, authz-invalidation, authz-ttl-refresh) — written FIRST, recorded RED post-U2 (only the two implicit workers registered then); helper Option tests. -
U5: panicking dispatch → contained +
error!with job id (tracing capture)
send-worker still Running + lease re-admission (or seam-level equivalent); bounded JoinSet drain.
No existing test weakened; harness routers legitimately carry Observed workers.
Docs inventory (U2 riders + U6)
deployment-guide (health table, readiness list, drain/exit); shared-crates
(craig-api/mq/db/bootstrap/retention + TestConfig); developer-guide:98 recipe;
architecture:96 + services:27 contract lines; the non-archived opentelemetry plan (:623
Option<Extension<MqHealth>> prescription reconciled); craig-mq subscriber module doc; MqHealth
struct doc; lib.rs:313 citation; scorecard:79-82; inline crate docs; CLAUDE.md explicit
N/A-or-update decision. CHANGELOG per unit (U2 carries the Fixed/Changed migration notes
for every source/wire break).
Verification
Per unit, gates separately: targeted clippy -D warnings (U2/U4 workspace-wide — the
breaks span services); targeted nextest per touched crate (U1: craig-api/mq/db; U4 adds
bootstrap/retention/test-lib/xtask); integration suites for U3/U4; cargo xtask api-docs
(U2, expect drift-free); scoped cargo llvm-cov nextest -p craig-api; quality-budgets
fail-on-regression; axis-coverage; plan-lint; check-docs (exit 3 standing); Antora render
for U0/U2/U6; full battery via pre-push per push. Pre-empts: fns ≤40; F-054 (Supervisor ~7
pub methods, WorkerHealth ~7); B4 zero new allows; B8 exports/shared-builder only; B3a
typed structs; craig-api deny(missing_docs)/deny(unreachable_pub).
Files touched (per unit)
| Unit | Files |
|---|---|
U0 |
adr-061 (new), adr-003 (§Amendment), this page (new), nav.adoc |
U1 |
craig-api: supervisor.rs (new), lib.rs (mod+re-exports), Cargo.toml (parking_lot); craig-mq: subscriber.rs + lib.rs (exports); craig-db: lib.rs (connect_lazy_with); CHANGELOG |
U2 |
craig-api: lib.rs (AppState, handlers, seams, serve/serve_with_listener, build_protected_routes, :313 comment, readiness tests), bootstrap.rs ( |
U3 |
crates/craig-api/tests/fault/ (new layer: fault.rs + supervision_chain.rs + readiness_live.rs); craig-test-lib client.rs + lib.rs (the shared typed |
U4 |
craig-mq retention.rs; craig-retention worker.rs (+tests); craig-bootstrap authz.rs; 8 service spawn_workers regions; rules/security retention_archive.rs; craig-test-lib config.rs/lib.rs; xtask docker.rs (+tests); composition tests/api (new); CHANGELOG |
U5 |
services/craig-exchange/src/send_worker.rs (+ seam + fault test); CHANGELOG |
U6 |
shared-crates, developer-guide, architecture, services, opentelemetry plan, craig-mq module doc, CLAUDE.md decision |
Review-round log (plan-lifecycle)
r1 internal (Plan-agent design + drift-proof Option-helper refinement) → r2 contextless
(P1 non-probative test pair → discriminating 503 body; P2 composition harness scoped) →
r3 EXTERNAL ITERATE, ~45 findings: 12 stop-ship design defects (stale-watcher race,
wrong-token wiring, causality loss, missing dual drain, unbounded HTTP shutdown,
unobservable 503, bridge SPOF, Option fail-open ×2, unimplementable helper rule,
panic-text leak, dispatch invisibility) + API/test/docs/delivery corrections — all folded
or ADR-justified → r4 contextless ITERATE: P1 bridge signal-only-await stall (fixed:
select signal|token); P1 idempotency-registration channel unspecified (fixed: WorkerHealth
is the token-bound registry handle); P2s manifest semantics / drain constant /
serve_with_listener; P3s folded → r5 contextless ITERATE: P1 tier table dangling
stale vs the mid-planning #1188 decision-refresh worker (inlined + decision row); P2s
manifest placement in the shared inner + Supervisor::standalone(); P3s folded →
r6 contextless convergence: fleet JoinHandle<()> uniformity verified; one P2 (U0 in
the child-issue enumeration) + two P3s — folded; SHIP. External (user) review approved
2026-07-31 at ExitPlanMode.