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)

craig_api Supervisor/WorkerHealth substrate (order-serializing watchers, manifest, drain, typed errors, standalone()/detached()); craig-mq contain/panic_message_bounded exports; DbPool::connect_lazy_with; full unit + deterministic-race + drain matrix

Done (2026-07-31) — MR !1116; deviation from D1 recorded: mark_disabled takes an explicit criticality param (a Disabled report row needs its tier; deriving it from the manifest would couple the two stores); post-J-review battery catch: the blocking fn-name-and lint renamed record_and_react → settle_worker_exit

U2 (#1222)

AppState { db, auth, mq: MqRequirement, workers }; pure evaluate_readiness/evaluate_health seams; discriminating 503 body; serve(router, port, token) + serve_with_listener bounded HTTP drain; Extension channel deleted; Supervisor::install() at the 8 mains; signal bridge Critical; idempotency-cleanup Observed; 11 literal sites; lib.rs false-citation fix

Done (2026-07-31) — MR !1117; deviations from D2 recorded: (1) build_router at the 8 mains takes supervisor: &Supervisor instead of a bare token — AppState.workers and ServerOptions.shutdown both derive from the one supervisor, so a mismatched token/registry pair cannot be passed (also keeps the widest build_router`s at 7 params, under the too-many-arguments gate); (2) the now-caller-less `shutdown_token() is DELETED outright (pre-1.0, no shims); (3) evaluate_readiness is total fail-closed — a skipped DB probe without a workers gate reads not ready: database, pinned by test. Live post-rebuild receipt: rules /healthz reports rabbitmq: "ok" + the workers block; J-review 2 P3 J5 findings remediated pre-commit (record on !1117)

U3 (#1223)

crates/craig-api/tests/fault/ proof layer: capstone chain, hung-request forced-close, dedicated-connection MQ-disconnect readyz, healthz-degraded-with-healthy-deps; 7× service healthz_reports_rabbitmq_ok (RED captured during U2 development, receipts preserved)

Done (2026-07-31) — MR !1118; RED/GREEN JUnit receipts uploaded to the GitLab project (RED = pre-U2 devstack, 7/7 failed "n/a" vs "ok": /uploads/3310c50dd66231c637446f60b590dcc9/1186-u3-red.xml; GREEN = post-U2 rebuild, 7/7 pass: /uploads/3b81f2b5280a71cb44876923ddcbbb82/1186-u3-green.xml); the 7 pins ride the shared typed craig_test_lib::HealthzBody (J-review F1: the dynamic-Value originals put B3b OVER its lock); the four fault-layer tests are green-only by design (recorded); F-024 battery catch: the redundant devstack_available() guards were removed pre-publish

U4 (#1186)

Option-returning helpers (interval arm only), retention-test updates, AuthzBootSpec/Result seam, 8-service spawn_workers → supervisor + manifests, composition harness scaffolding, exact-set drift tests written first + recorded RED

Done (2026-07-31) — MR !1119; drift receipts uploaded (RED 10/10 /uploads/969074a281d53b14c8b830d237a685d9/1186-u4-red.xml, GREEN 10/10 first-run /uploads/38a45ce43d12d2d8ba678fda2587b249/1186-u4-green.xml); deviations: spawn_workers takes supervisor: &Supervisor (one-source token+registry); the D11 consent refusal stays in-task (a mis-wired unconsented spawn under a Critical watcher fail-fasts loudly); detection’s pre-existing Option arm reused; J-review 2 P3s (spawn_local_sweep arm tests, shared-crates field list) remediated pre-commit; #1186 stays OPEN until U6 (Relates-to on !1119)

U5 (#1224)

Exchange send-dispatch JoinSet drain + contain wrap + injectable seam + fault test; ADR-justified non-propagation

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 is select!(shutdown_signal(), token.cancelled()) then cancel() — 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. Replaces shutdown_token() at the 8 mains.

  • Supervisor methods: token(), expect(&[WorkerSpec]) (manifest — creates Missing entries 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-cleanup are 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(), and standalone() (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-sorted WorkerReport { name, criticality, state }), detached() (own never-cancelled token — the 3 harness AppState sites; harnesses register only Observed workers). ApiServer::router’s `build_protected_routes registers idempotency-cleanup Observed via state.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-death token.cancel() (load-bearing for test sync). Observed deaths always warn! structured; Critical deaths error! + cancel.

  • Testability: the watcher converts Result<(), JoinError> to internal ExitKind { CleanExit, Panicked(String), Aborted } (JoinError is unconstructible); pure classify(kind, shutdown_observed_first) carries the full matrix; conversion covered by real-spawn tests. panic_message_bounded (exported from craig-mq with contain) 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 (cases keyed_harness.rs:277, security authz_fallback.rs:196/archive_engine.rs:163) fixed in-unit; harnesses use NotApplicable + 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 const HTTP_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.

Table 1. Tier table (Critical = event-driven / money-moving / security-monitoring / compliance / a shipped staleness guarantee; Observed = self-healing-on-restart hygiene)
Service Critical Observed

all 8

outbox; signal-bridge (install); authz-invalidation, authz-ttl-refresh (authz boot)

idempotency-cleanup (router)

cases

—

jws-cleanup, attachment-scanner

composition

composition-invalidation

—

exchange

events-subscriber, send-worker

send-jobs-sweep*, attachment-scanner

financial

events-subscriber, subsidy-generator, review-sweep

reconcile-sweep*

placement, reporting

events-subscriber

—

rules

events-subscriber, cache-invalidation, decision-refresh, retention-archive*

—

security

audit-subscriber, dlq-subscriber, detection-scheduler, retention-archive

—

  • = knob-gated (watch_optional/mark_disabled; the spawn_local_sweep consumers 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 enabled before 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 on window_days == 0; spawn_archive_worker → None on interval_seconds == 0. Consent-disabled paths call workers.mark_disabled("retention-archive"). Direct helper tests + the worker.rs:191 retention-test updates.

  • AuthzBootSpec gains pub workers: WorkerHealth; boot registers invalidation + ttl Critical; AuthzBootResult drops 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 + default http://localhost:8009; the manual .ports.env writer (xtask docker.rs:671 area) gains composition + writer/build_env tests; devstack_available() + its "eight endpoints" doc updated; NEW services/craig-composition/tests/api.rs
    tests/api/health.rs carrying composition’s healthz_reports_rabbitmq_ok (the 8th MQ pin — no RED receipt possible, its harness postdates U2; the live pre-fix curl n/a receipt 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 classify matrix; 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_exit names+ordering; drain timeout 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_exit names 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 (shutdown_token() deleted), supervisor.rs (U2-anchored rustdoc flipped to present tense); craig-bootstrap: lib.rs (context field + layer deletion + module-doc recipe) + Cargo.toml (craig-api dep dropped — the field was its only use); 8 service mains/lib.rs (install + build_router(&supervisor) + AppState + serve + drain/check_exit); 3 harness sites; stale shutdown_token() doc mentions (craig-mq outbox.rs, cases jws_cleanup_worker.rs); deployment-guide (probe table + readiness list + shutdown/fail-fast), shared-crates (craig-api/craig-bootstrap sections), developer-guide (crate row + init snippets + orchestrator shape), CHANGELOG (scorecard moved to U3/U6 — U2 does not change its rows)

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 HealthzBody mirror — B3b); 7× services/*/tests/api/health.rs; test-coverage-scorecard (health-endpoints row)

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.

Edit this page · latest