Testing Reference (CRAIG)

Contents

Critical Rules

  1. Never dismiss test failures as transient — investigate root cause. Only classify as edge case after thorough analysis.

  2. All checks must pass before push — the pre-push hook runs the fast battery (fmt, lints, clippy, unit tests); the merge train’s car runs the whole battery (integration, E2E, k6 smoke) and is the merge gate

  3. Test results in test-results/ — check this directory for failure context before investigating

  4. Never weaken a test to make code pass — fix the code, not the test. Specifically:

    • Never delete or weaken a test to make CI pass

    • Never [ignore] a test to silence a failure. Distinct from [ignore = "requires devstack"] which is the mandated canonical pattern per Plan D F-024 — see Devstack-gated tests section below

    • Never loosen assertions (e.g., assert_eq! → assert!, widening tolerance, removing checks) to accommodate broken code

    • Never change expected values to match wrong output

    • The ONLY reason to modify a test is if the test itself is genuinely incorrect — and that must be explained in the commit message

  5. All test types produce JUnit XML — unit, integration, and E2E tests all output to test-results/

Audit platform invariants before code-level smells

A code-quality or "incomplete work" audit runs in two passes, in this order — pass-1 findings outrank pass-2 findings even when pass-2 has more items:

  1. Platform invariants. Does encryption fail closed? Does auth validate audience and scope? Are events transactional with the DB write? Are DLQs actually wired? Do health checks distinguish ready / live / degraded? Is idempotency persistent? Are cross-service references reconciled?

  2. Code-level smells. TODO / FIXME, dead code, test-skips, dependency duplicates — the standard greps.

Storage shape is not verification. Reading "the table exists, the worker is spawned, the helper is exposed" confirms scaffolding, not semantic correctness under concurrency and failure. For each invariant, name the failure mode you would have to test — "if two replicas run this at once, what should happen, and is there a test that fires that scenario?" If the test does not exist, the invariant is unverified. Recurring examples where the shape passed but the semantics failed:

  • Idempotency — (middleware-era, historical) a real table and middleware, but ON CONFLICT DO NOTHING on the response write after the handler ran was not an atomic claim before it; two concurrent same-key POSTs both missed the cache and both executed the handler. The ADR-062 §B request_claims substrate (claim-first inside the domain tx, B2 #1194) is the current answer; its battery pins the one-execution property directly.

  • Outbox — a spawned worker with SELECT-then-UPDATE, but no FOR UPDATE SKIP LOCKED / lease column means multi-replica double-publish.

  • Inbox — ON CONFLICT DO NOTHING claims the row before the handler runs, so on handler failure the redelivery hits the existing row, short-circuits, and the work never retries.

Distinguish layers explicitly (fail-closed on cipher error is a different layer from fail-closed when the key is not configured), and when triangulating with multiple agents, give each a different verification mechanism — one reads source, one greps, one writes a hypothetical failing test — so they do not verify the same surface three ways. A test-framework gap that structurally cannot fire the failure mode is itself a debt item: absence of a failing test is not evidence of correctness. This is the storage-shape-vs-semantics lesson the Process rule below embodies.

Mandatory Rules

  • NEVER dismiss test failures as transient. Investigate root cause. Only classify as edge case after thorough analysis.

  • Test results location: All test output (unit, integration, E2E) is saved to test-results/ at the repo root. Check test-results/e2e/artifacts/ for failure screenshots and error context, test-results/e2e/junit.xml for structured results. Always check these files when investigating failures.

  • Full test battery REQUIRED after code changes:

    1. cargo nextest run --workspace --lib

    2. cargo xtask dev restart (schema change) or cargo xtask dev reload (code-only)

    3. cargo nextest run --workspace

    4. cargo xtask e2e

Diagnosing load-dependent flakes

When a test passes in isolation but fails under cargo nextest run --workspace, do not accept "infra flake" as the answer — there is almost always a real bug. Reject the infra-flake hypothesis unless you can prove there is zero code-level mechanism; hardware capacity is not the bottleneck on a modern dev machine. Instead:

  • Instrument what the failure needs. Add reviewer-spec’d fields at the suspected callsites (username / attempt / elapsed / status; cache hit-miss-negative; upstream elapsed) — never raw secrets — so a captured failure ties symptom to mechanism.

  • Capture per-service logs from an actual failed run. Bracket each repro with timestamps and pull docker logs craig-<svc>-1 --since <start> --until <end> for every service; --since/--until retrieve whatever the daemon buffered even if a background tailer died. Look for cross-service signal — one bad pattern (rollback storm, lock contention, retry storm) touching multiple services is the smoking gun, not the single service whose test failed.

  • A shared precise duration is a lead, not noise. If every failure takes the same wall-clock time (e.g. exactly 30.1 s), that is a hard timeout being hit, not flakiness — find what hangs upstream.

  • Read the transport legs before calling an event wait slow (#1897). Every cargo xtask e2e Playwright invocation writes test-results/e2e/transport-legs.txt; its first line names the window (since …). For each event a journey given waits on (case.created → placement / financial, placement.activated → financial) it gives three legs as p50 / p95 / max on the one devstack clock: relay (outbox created_at → published_at), claim (created_at → the first committed inbox claim) and retry (first claim → the successful attempt’s start; 0 means the first attempt won). It counts every envelope that stopped short by class and lists up to ten ids per class: unpublished (the outbox’s pipelined relay; attempts=0 is still queued, more is a failing publish), unclaimed (no committed claim: the broker, a consumer session in reconnect backoff, or a crash-class attempt that rolled its claim back; grep the service logs for the subscriber’s teardown / reconnect lines), unprocessed (claimed and failing, with error_count=) or dead_lettered (the 2-strike dead letter, operator-paced; see known-issues). An invocation that awaited nothing (the two-phase runner’s @restart-phase leg) keeps the file. Two blind spots: created_at is the producer transaction’s start, so relay includes the producer’s commit; and no row holds the final attempt’s duration or commit time, so a slow attempt or a stalled commit reads as done with the legs of its start (seeing it needs commit timestamps, track_commit_timestamp or a clock_timestamp() stamp, and neither is on). A wait that expired is classified by that file, and the remedy follows the class, never a wider poll budget.

    Measured 2026-09-15 (CI job 16523564871, the e2e leg straight after the full nextest battery): craig-placement and craig-financial each handled case.created 0.15–0.93 s after the case’s UUIDv7 id was minted, over the 10 cases in the failure-log tail, consistent with the outbox worker’s 1 s poll (poll_ms: 1000). A measurement, not a budget.

  • Reproduce at the source before fixing. Reproduce the failure at the Postgres prompt (docker exec … psql … -c "…") — that is stronger evidence than reading the code and inferring the cause.

  • Ship the fix as a clean diff. Revert the diagnostic instrumentation before shipping; the diagnostic pass and the fix have different audit surfaces.

A whole test binary dies by a signal (#1917)

The shape: every test of ONE binary fails within a second, each by a signal (SIGSEGV, SIGBUS, SIGILL), and no other binary fails. Suspect the artifact before the tests. It is still a defect, never "load".

validate’s battery records each test binary’s path before the run (the test-binary inventory step). After a red run, it copies each binary whose every executed test died by a signal to target/quarantine/<file>.<sha12>, keeping its mode so the copy runs, and prints the binary, the copy, its sha256 and the cores command. The run stays red. The copy is the evidence: do NOT rebuild before step 3.

Diagnose, in order:

  1. coredumpctl list <binary-path>, then coredumpctl info <PID>: look at the crashing thread and frame #0. A jump to a tiny address straight out of test::run_test is the #1917 signature. Cores rotate: read them the same day, or coredumpctl dump <PID> -o <file>.

  2. Run the kept copy with nextest’s argv, from the package directory: <copy> --exact <test> --nocapture, plus --ignored for an `#[ignore]`d test. A crash every time on a transactional, rolled-back test indicts the artifact.

  3. Force the relink: rm <binary-path> (the kept copy is the evidence), then cargo build --workspace --tests --locked, and re-run the same test. Since #2135, a plain rebuild finds the bad binary fresh.

  4. cmp -l <copy> <binary-path> | wc -l. A handful of differing bytes points at at-rest corruption (RAM, disk); a large span points at the link inputs (an sccache-served rlib, the linker). No differing bytes: the link inputs or the code are at fault; rebuild with RUSTC_WRAPPER= after moving the copy out of target/ (cargo clean deletes target/quarantine/).

Record the outcome on a new fix: issue that relates #1917. The bound recorded on #1917: incremental off, sccache on, a relink wave (#2135, fixed).

Multi-agent test-failure diagnosis

For a real (non-infra) test failure, a single diagnostic pass plus a hand-written fix is brittle — independent diagnoses frequently surface different real findings, and a synthesis over all of them can land a cleaner fix than any single diagnosis would (e.g. adopting a sibling handler’s established pattern instead of the literal fix each diagnosis proposed). The proven shape:

  1. Diagnose — N parallel agents with different framing angles (test-setup shape / handler-logic order / shared-fixture), each returning a structured diagnosis (root cause, proposed fix, fix target, risk notes).

  2. Fix — one synthesis agent receives all diagnoses, applies the chosen fix, and runs the verification commands.

  3. Verify — M parallel adversarial verifiers, each independently trying to refute the fix; an M-of-N majority passes.

Do not dispatch this for infra failures (CI runner disk OOM, devstack port collision, an e2e flake on admin pages) or for a single-handler fix whose failure mode is obvious from the error message.

Reconcile test-count deltas

When the test count changes between two runs, surface the delta explicitly — do not wave it away with "all green" if the numbers do not reconcile:

  1. List the tests removed (by name).

  2. List the tests added (by name).

  3. State the arithmetic: "removed N, added M, net +X — matches the observed delta of +X."

  4. If the numbers do not reconcile, find the discrepancy (skipped tests? #[ignore]? dependency gating?) before declaring done.

The same discipline applies to any quantitative claim — LOC counts, file counts, MR counts.

The never-easier checklist (contested-environment program)

Standing maintainer constraint (2026-08-17): tests never get easier. "The application needs to be able to handle a contested environment. Life is never 0% system usage." Every J-review in the contested-environment program (epic &83, ADR-067; disposition procedure in the arbitration runbook) runs this checklist, and it is the bar for any fix that touches a load-dependent or fault test anywhere:

  • Zero .config/nextest.toml serialization/envelope hunks — unless a test is semantically order-dependent AND the ordering is called out in the review. Adding a [test-groups] max-threads = 1 to make a flake pass is weakening the battery, not fixing it.

  • No timeout/envelope widening to make a leg pass. A per-leg setup ceiling (≤90s in this program) is a fixture ceiling — the budget for arranging the scenario — never an assertion-widening budget. If the assertion needs more time, the component is slow: that is the finding.

  • No assertion loosening, no [ignore] to dodge a real failure. The only legitimate [ignore] here is fault-layer gating (#[ignore = "requires devstack+fault"]), enforced by cargo xtask fault-preflight — it is a hard gate, not a skip (M9: a zero-fault green battery is a FAILURE).

  • Tests stay exposed to ambient load. A leg must not quiesce the box (kill neighbors, pin to a reserved core, sleep the world) to pass. It must be honest under the same contention the real system faces.

  • A ceiling breach or an added serialization is a blocking review finding — split the fixture or fix the slow path; a genuine exception needs a maintainer-approved amendment recorded in the plan.

The rationale is the arbitration instrument: a test made easier can no longer tell a real component defect from a bad fixture, which is the entire value the program exists to create.

Scenario inventory (the narrative layer, #665 / ADR-071)

The machine-audited answer to "are the important journeys tested?": compliance/scenario-inventory/{stage}.toml (core corpus)
each config layer’s scenarios/{stage}.toml (packs) hold rows with first-class relational `s and bindings to real tests/specs/fixtures. `cargo xtask scenarios audit derives coverage (never self-graded), fails on inventory lies, reports the burn-down + the journey-critical priority list #668 works from, and compares the derivation against the committed per-ID coverage ledger compliance/scenario-coverage.lock (#669: forward-only; --bless records honest moves). Schema + doctrine: ADR-071; gate detail: Quality Gates § Scenario-inventory audit. When you add or rename a test that a scenario binds, the audit (a battery test) tells you exactly which row to update.

Test Categories

Eight test categories. Most existing tests are Functional; the goal of the test-framework-hardening + platform-stab-2 work is to make Concurrency, Fault-injection, Recovery, and Invariant the second-most- common classes. The taxonomy describes how tests are written, not a quota per service.

Category Description

Functional

Single-fire request → single response → assert status + body. The dominant class. Catches "does this endpoint exist and return the right shape."

Invariant

Asserts a property that holds across many states or many calls. "Every successful POST /v1/cases/persons produces exactly one person.created outbox event with the same UUID as the response body." A failing invariant test usually points at a missing transactional bracket.

Concurrency

N parallel calls against the same endpoint or store function; assert no-double / no-drop / consistent-state. Use craig_test_lib::concurrent::*.

Fault-injection

Wraps a dependency in a wrapper that errors on demand, asserts the error path is reached. Use craig_test_lib::fault::*.

Recovery

Continues past a fault and asserts the system recovers — orphans reaped, in-flight jobs reclaimed, retries succeed.

Contract

End-to-end typed-DTO round-trip. Test client uses the same DTO type the service handler imports. Schema regressions fail compilation, not in production.

Property-based

proptest generators produce inputs; the test asserts a property holds for all of them. Useful for matchers, encoders, sanitizers. Available; not required.

Mutation

cargo mutants --smoke against craig-test-lib-tested modules; surviving mutations indicate uncaught real-world bug shapes. Available via cargo xtask mutants (Phase B). Not enforced as pre-push gate.

File-naming convention

The convention applies to net-new test files; existing tests are not mass-relocated.

Category Path convention

Functional

tests/api/<endpoint>.rs (status quo) or tests/<feature>.rs for cross-endpoint.

Invariant

tests/invariants/<invariant>.rs.

Concurrency

tests/concurrency/<scenario>.rs — filename names the property: idempotency_no_double_handler.rs, outbox_no_double_publish.rs.

Fault-injection

tests/fault/<failure_mode>.rs — filename names the upstream fault: rmq_publish_unavailable.rs, db_pool_timeout.rs.

Recovery

tests/recovery/<scenario>.rs — filename names what is recovered: attachment_orphan_reaped.rs.

Contract

typed-client tests live under crates/craig-test-lib/tests/typed/<svc>_client.rs.

Property-based

tests/properties/<property>.rs.

Mutation

No per-test file; configured at workspace level via .cargo/mutants.toml and run via cargo xtask mutants.

Process rule

Process rule (epic &21 / &22 onward): every concurrency-relevant fix, fault-tolerance fix, or platform-invariant fix MUST ship with at least one Concurrency, Fault-injection, Invariant, or Recovery test — in any combination — in the same MR as the production-code change. Failing-test-first (commit failing test, then commit fix in the same MR) is preferred but not mandated.

Reviewer responsibility: when reviewing an MR labeled concurrency, platform-invariant, durability, or any sub-label of those, the reviewer must explicitly confirm in CR that a test of one of the four categories exists. The MR is blocked until either the test is added or the author argues — and the reviewer accepts — that the change is structurally incapable of regressing the invariant (e.g. comment-only edits).

Linkage: this rule is the embodiment of the two-pass platform-invariant audit storage-shape-vs-semantics lesson. An audit that verifies "table exists" without the matching Concurrency / Recovery test does not constitute platform-invariant verification.

Quality budgets

Style rules in the coding-conventions standard §Style are hard rules — enforced via clippy / xtask lints from Plans H/I, not via declining-baseline budgets. The budget table below lists items that remain in budget form (numeric thresholds without a clippy rule today).

Item Threshold Enforcement

Max route module length

500 LOC

cargo xtask quality-budgets budget B1 (recorded in xtask/baselines/quality-budgets.toml)

Max function length

40 LOC (hard)

Clippy too_many_lines + clippy.toml max_lines=40 per Plan H F-031; subagent triages "important function" overrides per the coding-conventions standard §Style <10% exception. The legacy 80-LOC budget is superseded.

Struct / impl block method count

≤16 (hard, excl. getters/setters/builders)

cargo xtask lints struct-method-count via syn::visit::Visit per Plan I F-054.

serde_json::Value in CRAIG-business-logic code

0 (hard) — partner-edge sites carry // PARTNER-EDGE-UNTYPED: see plans/partner-typed-schemas.adoc until Plan L F-064 retires the carve-out

Plan I F-037 sweep + rg 'serde_json::Value' services/ crates/

unwrap / expect / panic! / unreachable! / unimplemented! / todo! in non-test code

0 (hard) — only main may panic, and only via eprintln! + std::process::exit(1)

Clippy unwrap_used / expect_used / panic / todo / unimplemented / unreachable per Plan H F-031 + F-030 sweep.

let _ = result_expr / .ok(); / .unwrap_or_default() discards on Result types

0 silent (hard) — each site converts to ? propagation, tracing::warn!, or explicit // SILENT-OK: <reason>

Clippy let_underscore_must_use + ignored_unit_patterns per Plan H F-031 + F-051 sweep.

Lint suppressions

reason-required; an outer one is a self-checking #[expect]; every other one registered (hard)

Clippy allow_attributes_without_reason + allow_attributes (deny) and cargo xtask lints lint-regime (R4–R6, Quality Gates & Enforcement (CRAIG) § Lint regimes, #2715).

New dependency duplicates

0

cargo deny check bans (multiple-versions = "deny", deny.toml)

New untyped test clients

0 (post §D8 migration)

cargo xtask quality-budgets budget B7

Mutation-test surviving-mutant ratio on craig-mq, craig-api/request_claims.rs, craig-store/validation.rs

0

cargo xtask mutants --smoke

Migration Naming Convention

  • Format: YYYYMMDDHHMMSS_descriptive_name.sql (sqlx timestamp-based)

  • Initial tables: YYYYMM01000000_create_<service>_tables.sql

  • Subsequent changes: YYYYMMDDHHMMSS_<action>_<objects>.sql (e.g., rename_document_url_to_object_key)

  • Cross-service batch updates share the same date prefix (e.g., 20260305100000_uuid_v7_defaults.sql across all services)

  • Each service has its own migrations/ directory under services/<service>/migrations/

Integration Test Organization

  • Pattern: tests/api.rs (module index) + tests/api/*.rs (per-endpoint files)

  • Module index declares submodules: #[path = "api/auth.rs"] mod auth;

  • Each test file follows the pattern:

    • Devstack gate: #[ignore = "requires devstack"] on the test function (see Devstack-gated tests below) — the legacy if !devstack_available().await { return; } early-return pattern is being swept out by Plan D F-024 and is now an anti-pattern for new tests

    • Setup: TestHarness::new().await → typed client (e.g., caseworker_cases_client(); the harness_clients! matrix emits every client under all seven roles — admin_/supervisor_/caseworker_/readonly_/county_director_/regional_director_/ state_office_ — #1082 added the readonly principal carol.reader, #1094 the three office-authority principals dana.county/rita.regional/sam.state)

    • Action: client method call (e.g., client.create_case(&body).await)

    • Assert: status code + response body validation

  • Naming: tests/api/{endpoint}.rs — e.g., cases.rs, referrals.rs, workflow.rs, auth.rs

The acting-identity census (#2522). cargo nextest run -p craig-test-lib --test acting_identity_census is a hermetic workspace census (crates/craig-test-lib/tests/acting_identity_census.rs; no devstack). It lexes every workspace member’s src/ through the scanner craig_test_lib::token_census (tokens, not text, so comments and strings never trip it) and fails on any bearer_*() read of craig_auth::Claims that PINS does not list. Each pin is the read’s exact rendered text ("{path}: {receiver}.{accessor}") with its reason. The rule runs both ways: an unpinned read fails, and so does a stale pin whose read is gone. A pin owned by an open issue has a reason that starts "#NNNN: ", and the commit that converts the site to claims.acting_worker() deletes the pin. File and acting_worker-token floors keep a walk or lexer that stopped seeing code from passing vacuously. The census replaces the per-service recorder_census.rs tests (#2214, #2250), retired by #2542.

The value-free census (2523). cargo nextest run -p craig-test-lib --test value_free_census is the second hermetic census on the same scanner (crates/craig-test-lib/tests/value_free_census.rs; rules in craig_test_lib::value_free_census). It fails on any site that can render a request or upstream value into an error and that PINS does not list: C1 a relayed .body_text(), C2 a serde decode whose error text reaches a detail or log (a map_err / context closure that uses the error, a ? right after the decode, or an Err(e) arm that uses e), C3 a hand-rolled problem detail probe, C4 an unbounded .text().await refusal read, C5 axum’s value-quoting Path / Query / Form extractors, and C6 an [error(..)] format that captures a field named body (2529). C1 scans all of src/; C2-C6 skip [cfg(test)] items and test files, and SCOPE_EXCEPT exempts craig-common’s problem reader and extract wrappers, craig-bff’s extract, tools/craig-mock-server/ (external wire emulation) and the mock module of the reference partner’s simulator (its control routes are mock-server routes, in the partner crate). Pins, the stale-pin rule and the file and json_detail-token floors work as in the acting-identity census. The module doc names the accepted limits: a decode matched in a later statement, a .bytes().await refusal read, and a format! echo (the evil corpus’s no-echo assertion covers that).

Running tests: the cargo xtask test lanes (#3043)

Bare cargo xtask test runs cargo fmt --check --all, cargo clippy --workspace --all-targets --locked — -D warnings, the template pre-warm (on the project network only) and cargo nextest run --workspace; --skip-lint drops fmt and clippy. A lane flag runs that one lane and nothing else, so a script can name the lanes one at a time (plan ci-dev-loop U1); clap refuses two at once:

Flag Runs

--unit

cargo nextest run --workspace --locked --lib in craig-tools, off the stack’s network, from dev start’s one compile (below): no fmt, clippy or pre-warm (was `--unit-only, which also ran fmt and clippy)

--clippy

cargo clippy --workspace --all-targets --locked — -D warnings twice, under the default features and then the battery’s (lanes::BATTERY_FEATURES), then --lib --bins over the production graph (quality-gates § The clippy passes)

--doc

the two rustdoc gates, public and --document-private-items, concurrently (quality-gates § Rustdoc gate), under their own timing table

--integration [--profile P]

with no --package, the whole battery body (run_devstack_battery_standalone) against a stack that is already up, under the nextest profile P (default integration, the pre-push profile; CI’s is ci-integration); was --fault-gate. It re-executes in craig-tools on the project network

--package <crate> --integration

one package’s suites (below); fmt and clippy run first unless --skip-lint

The old spellings --unit-only and --fault-gate were removed with no alias (pre-1.0).

The battery from one target (#3044)

cargo xtask dev start compiles the workspace once in craig-tools: --workspace --all-targets, the x86_64-unknown-linux-musl target, --profile devstack, the features in xtask/src/lanes.rs (BATTERY_FEATURES), into target/craig-tools/x86_64-unknown-linux-musl/devstack/ (local-dev § dev start compiles once). The devstack images copy their binaries from that build, and in craig-tools every battery cargo call selects the same units (lanes::NEXTEST_SELECTION: --target, --cargo-profile devstack, --features): the test-binary inventory, the nextest run, --package runs (narrowed by the filterset package(=<crate>), never by a narrower cargo selection), the C24 gate’s and the battery lane’s contested-census inventories and test --unit. So after dev start the inventory step reports Finished with nothing compiled; on luchs (2026-11-09) the battery verb went from 16.0 to 9.1 minutes, its nextest run 519 s glibc against 533 s musl. The test binaries are static musl, linked like the services, and they carry the devstack’s features: authz-witness, the two shipped plugins in craig-web and craig-composition, and craig-intake’s self-signed-tls. A test that meets one of them meets what the devstack serves. On the host (validate --skip-devstack, which has no musl toolchain) the census builds glibc into target/ as before.

api-docs and the coverage matrix read the one compile’s binaries (3049). Both get each service’s OpenAPI document from <binary> --print-openapi, and one function decides which binary (api_docs::service_binaries_dir). It runs the binaries in target/craig-tools/x86_64-unknown-linux-musl/devstack/ and compiles nothing when they are current; otherwise it builds the services as before (cargo build --locked -p <service>…, debug, default features) and prints the reason first. "Current" is decided by a stamp, never by a binary being present (devstack_guard/battery_build.rs): the one compile removes battery-build.stamp from that directory before cargo starts and writes it after cargo succeeds, holding the manifest and image-source fingerprints taken before cargo started (the staleness guard’s deps.sha256 and source.sha256 recipes). The binaries are current when the stamp is whole, its fingerprints equal the tree’s, and no requested binary is newer than the stamp. A failed or interrupted compile, an edit since the compile, an edit saved while it ran, and a test run that linked the binaries again from an edited tree each fail one of those, and the verb compiles instead. The static musl binaries run in any x86-64 Linux process (the host, the job container, craig-tools); elsewhere the verb always builds. In a car dev start compiles and stamps before any lane, so api-docs --check (in the job container) and the battery’s coverage matrix (in craig-tools) compile nothing; before #3049 each compiled the nine services again, in debug. On a host with no devstack build, or a stale one, both verbs build with cargo as before, and neither needs a running stack. The battery’s binaries carry the devstack’s features, but no feature changes a document: no cfg(feature …) in the nine services or the crates they link gates a [utoipa::path] handler, an OpenApi derive or a schema, and on one commit all ten documents were byte-identical between a default-feature build and a build with the battery’s features.

Devstack-gated tests

Tests that depend on a running devstack (Postgres, RabbitMQ, Keycloak, garage) use the #[ignore = "requires devstack"] attribute, NOT a runtime devstack_available() early-return. This is canonical per Plan D F-024.

#[tokio::test]
#[ignore = "requires devstack"]
async fn create_report_persists_typed_envelope() {
    let harness = TestHarness::new().await;
    // ...
}

Where a devstack test runs, and what it dials (#2922)

The devstack publishes no host port (plan merge-trains-gate design 3). A devstack-gated test runs on the compose project network, inside the craig-tools container: cargo xtask test --integration (with or without --package), cargo xtask validate’s battery and every other devstack verb re-execute themselves there when started on the host (=⇒ running … in craig-tools`), and cargo xtask dev exec — cargo nextest run … does it by hand. A raw host-side cargo nextest run --run-ignored all reaches nothing and fails at its first connection.

craig_test_lib::TestConfig::from_env() and the URL helpers beside it resolve each endpoint to its container address, overridable one by one through CRAIG_TEST__* (an empty value counts as unset):

Setting (CRAIG_TEST__…) Default

KEYCLOAK_URL

http://keycloak:8080

OIDC_ISSUER (new)

http://keycloak:8080/realms/craig — the iss every devstack token carries; issuer-strict test validators use it and fetch JWKS through KEYCLOAK_URL. dev exec sets it to http://localhost:8180/realms/craig under the dev profile.

RULES_URL … SECURITY_URL, COMPOSITION_URL, INTAKE_URL

http://craig-<svc>:<port>; (8001–8009)

INTAKE_STANDALONE_URL, INTAKE_STANDALONE_SHINES_URL, INTAKE_KEYRING_URL

http://craig-intake-standalone:8009, http://craig-intake-standalone-shines:8009, http://craig-intake-keyring:8010

WEB_URL, PORTAL_URL

http://craig-web:8080, http://craig-portal:8080

RABBITMQ_URL, RABBITMQ_MGMT_URL

amqp://craig-test:craig-test@rabbitmq:5672/%2f, http://rabbitmq:15672

POSTGRES_ADDR, POSTGRES_TEST_ADDR (new)

postgres:5432, postgres-test:5432 (postgres_test_db_url, postgres_test_plane_db_url; xtask’s devstack DSNs read POSTGRES_ADDR too)

MOCK_SERVER_URL, GARAGE_S3_URL (new)

http://mock-server:9090, http://garage:3900

TOXIPROXY_HOST (new)

toxiproxy — the host a leased fault-proxy port is dialled on (toxiproxy:<port>); the control API is CRAIG_TOXIPROXY_URL, default http://toxiproxy:8474

.ports.env and the CRAIG_PORT_* variables are gone; only the separate craigidp project’s multibackend probes still read CRAIG_PORT_<SERVICE>_<PORT>.

cargo nextest run --workspace shows these as (skipped). To run them locally, use cargo xtask test --package <crate> --integration [--test <binary>]… [FILTER]… (#1802). It runs that package’s suites, the ignored ones included, through the push battery’s own steps: ensure_ready; the preamble (on the project network: the fault preflight, verify-seed, the template pre-warm, the C24 record reset); the integration profile without the NEXTEST_* overrides; and the whole-DB invariant gate, which runs even when a test fails. It ends by naming each blocking invariant still returning rows (its rows now, its rows before the run, and whether this run added any; "cannot tell" when the pre-run count already sits at the catalog’s LIMIT 20) and offers cargo xtask dev reseed. It skips the C24 verification, whose floors only a whole battery can meet.

Anti-pattern: raw cargo nextest run … --run-ignored all against the devstack, even with a narrow -E filter. It skips the pre-warm, the C24 reset and the invariant sweep. A test that panics mid-body leaves rows that trip the next pre-push debris scan, which names them and reseeds (#1801); a scoped run or test --integration still fails on them, far from their cause (#1788).

A full local cargo xtask validate runs the whole-workspace battery, as the car does (cargo xtask test --integration --profile ci-integration), and on a merge train it blocks: the train is the merge gate (ADR-086). The unit lane (test --unit) runs only the --lib tests, where these never execute.

Reason strings distinguish the prerequisite class:

Reason Meaning

"requires devstack"

Full devstack (Postgres + RabbitMQ + Keycloak + garage)

"requires devstack postgres"

Postgres only (no broker/IdP needed)

"requires smoke devstack"

Devstack + a freshly-seeded smoke fixture

"requires docker"

A reachable docker daemon (the battery host has one); the leg fails loud without it

"requires identity multibackend"

The identity-multibackend plane: the multibackend IdP stack (authentik + ZITADEL + Kanidm, cargo xtask dev multibackend-up) plus the kanidm / zitadel bootstraps; profile identity-multibackend

"requires cluster-tests rig"

The cluster plane: the stage-owned multi-replica rig; run by cargo xtask cluster-tests (profile cluster)

"seed-hash bless printer"

The seed-bless plane: the seed-hash printer, run by hand (profile seed-bless)

"network"

Live network access: policy_url’s govinfo live-pin leg, the network plane (profile network, #2642)

Plan D F-024 ships cargo xtask lints no-silent-skips, a blocking step of cargo xtask validate. It walks every .rs file under the lint roots (lint_scan::lint_roots: the workspace members' top-level trees, crates/, plugins/, services/, tools/ and xtask/ today), tests/ included, with syn::visit::Visit, and a missing root or an unreadable directory fails it. An unreadable or unparsable file fails it too, naming the file (lint_scan::read_lint_file, #2553), and it prints files_scanned and refuses a scan of fewer files than its recorded floor allows (no-silent-skips.files in xtask/baselines/scan-floors.toml, less one fifth). It flags two shapes (#2368):

  • in any fn, if !<path>devstack_available().await { <skip-return> };

  • in a [test] / [tokio::test(..)] fn, a top-level statement that is let … else { <guard> };, an if <cond> whose then or else branch is { <guard> }, or a match (bare, or a let initializer) with a <guard> arm.

A skip-return is return;, return (); or return Ok));. A guard block skips when it ends in a skip-return and no earlier statement calls a verdict macro (assert*, debug_assert*, prop_assert*, panic, unreachable; fn is_skip_block, #2567). So { eprintln!(..); return; } is a finding: nextest hides a passing test’s output, and a printed skip still reports PASS. { prop_assert!(..); return Ok((; } asserts first, so it is a verdict. Named limit: an unrelated assert! before the return passes as a verdict too. Only top-level statements count (xtask/src/cmd/lints.rs fn test_body_skips): a return inside a closure or a spawned task does not end the test, and one inside a loop is the poll-until-done idiom.

Since #2569 the lint also reads three spellings it used to miss:

  • a test fn made inside a macro (proptest!, macro_rules! such as __evil_test_for_category!; 382 today), found by a token walk (lint_tokens::macro_test_fns) and parsed after $metavar expansion. A body it cannot read (one syn rejects, a spliced $body, a body of bare metavars) is a finding, so the lint fails closed;

  • a block_on(async { … }) body (rt.block_on(..) or …::block_on(..), through ?, .expect(..) and .unwrap()), read as the test body;

  • skip-by-omission: a top-level if let with no else, or a match with an empty / None / Err() arm, whose scrutinee awaits or reads an env var (var, var_os) and which no other top-level statement backs with a verdict macro, so it holds every assertion of the test. A construct whose body or arm panics (panic!, unreachable!) is a fail-loud guard, not an omission.

Its remaining limits are named: a test made by a proc-macro attribute ([rstest]-style; none in the tree), a helper’s early return, and an omission keyed on a sync scrutinee. To fix a finding, a devstack leg keeps [ignore = "requires devstack"] and makes its probe fail loud (.expect(..)); an opt-in plane leg carries its plane’s #[ignore = "<reason>"], fails loud, and is selected by its profile (§ Opt-in planes).

1919 adds the other half: a test that reaches devstack Postgres must carry the [ignore]. The walker test in xtask/src/devstack_gating.rs (it runs with xtask’s unit tests and under cargo xtask baselines check) refuses a default-run [test] / [tokio::test] whose body reaches a devstack-Postgres entry (postgres_test_db_url, postgres_test_plane_db_url, scratch_db, ensure_template, create_from_template, prewarm_all, gate_admin_pool, assert_postgres_only_gate), directly or through helpers in the same file: free fns, impl fns (Self:: included), methods, and calls inside macro bodies. Any [ignore …] reason gates a test. Its blind spots are named in the module doc: a helper in another file (mod common;), a turbofish call, a fn passed by value, a trait default method, a fn defined inside a macro invocation, and every craig-test-lib helper outside the entry list above (TestHarness, …). #2367 gated every leg that predated it: the in-body connection probes now .expect(..) and carry [ignore = "requires devstack"], and so do the intake-keyring legs. The baseline (the ledger xtask/baselines/devstack-ungated.toml, keyed by file and leg) holds one off-plane false positive, craig-test-lib’s tests/prewarm.rs unregistered_base_is_refused_with_the_registration_instruction, whose ensure_template call refuses before its lazy pool dials anything. It is checked in both directions, so a new leg fails even in a listed file and a fixed leg fails until its row is removed, and the_baseline_is_only_the_off_plane_leg pins it to that one row.

The authz witness in the devstack (#2667)

The devstack builds every service binary with the test-only authz-witness feature: dev start’s one compile enables it (`lanes::BATTERY_FEATURES, #3044); CI’s chef-built images take the Dockerfile’s CRAIG_DEVSTACK_FEATURES build-arg (empty by default), which docker-compose.yml sets to authz-witness and xtask/src/docker.rs keys its build recipes on. The release images (docker-bake.hcl’s `release group) pass no such arg, and the release-artifact gate refuses one there and in CI. So every response from the eight ApiServer services carries authz-decisions: <n>, and a 2xx with no decision on a route that is not a declared exemption answers the 500 authz-unwired. A test that meets it has found an unwired handler: wire it, or declare the exemption (quality-gates § authz coverage). The in-process harnesses build the bare service routes and do not mount the witness; a test that drives the whole ApiServer stack does, since the battery’s test binaries carry the feature (#3044), so its handler makes an authz decision as a real one does (crates/craig-api/tests/request_claims_battery.rs). services/craig-cases/tests/api/authz_witness.rs pins the image’s counts.

Opt-in planes (#2567)

An opt-in plane is a test set that needs a stack the battery never brings up, or (the network plane) an external host the battery must not depend on (2642). Each plane has one ignore reason, one nextest profile and one runner, and every leg is `[ignore]`d and fails loud when its plane is absent, so no plane leg reports PASS without running:

Plane Selection (nextest filterset) Reason Runner

cluster

binary_id(craig-test-lib::multi_replica)

"requires cluster-tests rig"

cargo xtask cluster-tests (weekly CI, the cluster-tests MR label, or by hand); the profile runs one thread

identity-multibackend

binary_id(craig-test-lib::identity_multibackend)

"requires identity multibackend"

cargo xtask identity matrix (#2641): the craigidp project up, the two bootstraps, the profile with --no-tests=fail, teardown. CI runs it on the weekly schedule and on an identity-changing train (§ CI stages); by hand, dev multibackend-up, the bootstraps and cargo nextest run -p craig-test-lib --profile identity-multibackend --run-ignored only

seed-bless

binary_id(craig-seed::sql_byte_identity) and test(=capture_current_hashes_for_bless)

"seed-hash bless printer"

cargo nextest run -p craig-seed --profile seed-bless --run-ignored only

network

binary_id(xtask::bin/xtask) and test(=cmd::policy_url::tests::the_committed_govinfo_pins_match_the_live_documents)

"network"

cargo nextest run -p xtask --profile network --run-ignored only, by hand. #2642 chose exclusion over recorded bytes: the govinfo leg exists to see a live publication change, which a recording cannot

[profile.default] carries default-filter = 'not (<the four selections>)'. integration, ci-integration and ci declare no filter of their own, so they inherit it, and the battery’s run banner counts what it left out ("… skipped via profile.default.default-filter"). Each plane profile replaces the filter with its own selection. nextest intersects a CLI -E with the profile’s filter, so a by-hand run of a plane needs its profile (or --ignore-default-filter). The battery used to "pass" most of these legs without running them: a printed skip in 4-50 ms. There is one real loss: while the multibackend stack happened to be up, the battery ran its legs for real (#1413). The govinfo live-pin leg dialled govinfo.gov on every push until #2642 made it a network leg. Since #2641 CI runs the multibackend plane.

The xtask nextest_profiles pin holds this table (PLANES): the_battery_excludes_exactly_the_opt_in_planes (the default filter is built from the table; the battery’s profiles declare none), each_plane_profile_selects_only_its_plane, and every_plane_leg_carries_its_reason_and_no_other_test_does (over the lint roots; its fixture twin is a_plain_test_in_a_plane_binary_is_named). The rule it enforces: every test in a whole-binary plane’s file is a plane leg, so a plain test never hides in a plane binary, where the battery’s filter would drop it unseen.

Live rigs commit only gate-inert rows (#1923)

A devstack test that COMMITS rows to a shared service database must commit only shapes the invariant gate passes. The gate (craig-manage invariants --gate, after the integration run) reads every committed row. A panic or a nextest kill skips an end-of-test teardown, so a row that is a violation until teardown becomes debris: the next battery’s pre-run scan names it and reseeds (#1801), and a run without that scan fails the gate on it. Prefer a rolled-back transaction or a scratch clone when the code under test can see it. When it must commit:

  • Subsidy agreements: never a bare subsidy_agreements identity row. The status-blind subsidy_zero_head_interval and subsidy_native_missing_caregiver fire on any agreement without its chain. A rig that needs the row but no status semantics commits craig_test_lib::subsidy_fixtures::RawAgreementChain::native_pending through seed_raw_agreement_chain, in one transaction. A rig that needs active commits a full chain (party, open interval, terms from its first day; the placement_ended_void.rs shape), and stays tick-tolerant (see § The subsidy-generation tick is a standing legitimate contender, below).

  • services/craig-financial/tests/invariants/subsidy_rig_shapes.rs pins both halves against the whole craig-financial catalog on a scratch clone.

The TX-jurisdiction live-HTTP harness (#1369)

services/craig-financial/tests/api/tx_live_http.rs boots the REAL craig-financial HTTP application in-process — craig_financial::api::build_router, the identical assembly the bin serves — with jurisdiction = "texas" against the running devstack’s infra (financial DB, broker, Keycloak JWKS with the split-issuer form the compose services use, and the rules service as the engine’s ruleset source), serving on an ephemeral loopback port. It exists because the stock devstack boots every service jurisdiction=georgia, so jurisdiction-differentiated authz (e.g. the TX i_supervises supervisor row-scope, #1084) previously had no full-HTTP leg anywhere.

When to use it: asserting jurisdiction-specific authz THROUGH the production middleware/extension/scope-narrowing stack — anything where "the engine allows" and "the route enforces" could diverge. Pair a TX-instance assertion with the same call against the devstack Georgia instance (the jurisdiction differential) so the behavior difference is attributable to the axis, not fixtures.

The admin-unit legs (#1904, ADR-077 D7): BootSpec::texas verifies the admin-units snapshot before the first request (verify_units); boot_financial returns TxFinancial { base_url, shutdown, units }, the engine’s own source handle, so a leg can refresh_now() after a registry write. dana.county is the supervisor probe, rita.regional the regional probe over RAW-seeded, directly-stamped agreements / payments (every subsidy write route is behind the subsidy-writes gate, which the Texas layer’s bundle does not declare): Harris 200 / Dallas 403 / NULL 403 + list membership, with the Georgia differential; the typed 503 lever (max_age_secs: 0 → stale); the third-county bind → refresh_now() → revoke leg (Bexar); the retained six-key envelope leaving the stamp NULL; a Georgia-side rules-evaluate smoke. In-process siblings (cases and placement now also have live twins, see below): cases tests/api/tx_admin_unit_scope.rs (a real engine over the shipped Texas files + a StaticUnitsSource, seeded through the LIVE devstack rules — the screening act with the four Texas screen-in criteria + the P1 trigger, so the referral rolls up to P1 and its investigation has a window) and placement / financial src/api/regional_check_legs_tests.rs (Fence::with_engine; placement adds the governed foster-home field write twin PUT /v1/placement/homes/{id}, the caregiver-ledger and home-document list legs (#1928 / #1909) and the education / health GET and list leg (#1909 (b))); the rita-admin-unit-bindings nextest group serializes the Bexar leg against the live legs asserting rita’s exact bindings.

The cases and placement twins (#1910): services/craig-cases/tests/api/tx_live_http.rs and services/craig-placement/tests/api/tx_live_http.rs boot craig_cases::api::build_router / craig_placement::api::build_router (each filled through its RouterEnv, the assembly run serves; placement’s HTTP surface moved from the bin into the lib for this) in the same way, and probe with rita.regional (supervisor + regional_director, bound to Harris
Travis): in-unit reads 200, out-of-unit and NULL-stamp reads 403, lists narrowed to her units, plus the Georgia differential. The data planes differ. Cases runs over the keyed throwaway DB (keyed_harness::build_screening, seeded like tx_admin_unit_scope.rs), because the devstack cases service encrypts under a key no test loads. Placement runs over the devstack craig_placement DB with raw stamped rows (the tx_supervisor_scope.rs seeders; placement stores no encrypted column), deleted before the assertions. The differentials differ to match: cases boots a second in-harness instance (BootSpec::georgia() beside BootSpec::texas()) over the same DB with the same bearer, and placement calls the devstack Georgia container (config.placement_url) over the same rows. Neither boots workers (craig-cases.events and craig-placement.events are named shared queues; placement builds its jobs runtime but never spawns it). Neither asserts rita’s exact bindings or seeds Bexar, so neither joins the rita-admin-unit-bindings group.

What it deliberately does NOT boot: the background workers — an in-process events subscriber would compete with the devstack container on the durable shared craig-financial.events queue and steal deliveries mid-battery. The engine’s own invalidation queue is per-instance (<service>.authz-cache.<uuid7>, declared exclusive + auto_delete by craig_authz::invalidation via subscribe_exclusive — where that contract is pinned), so the engine boot is safe. The subsidy jurisdiction reference boots from the georgia bundle (no Texas bundle exists; the reference never feeds authz decisions).

Cost: one extra in-process service boot per test (~0.5 s: engine bulk fetch from the rules service + JWKS fetch + two DB connections) — far cheaper than a compose-profile side instance, with the same fidelity on the HTTP-authz axis (the steer decision recorded on #1369 rejected the side-instance and env-overridden-container alternatives).

The in-process tier (#3119)

An in-process suite assembles its service’s real router in the test process and runs it over a database of its own. craig_test_lib::inproc holds what is the same for every service; the crate depends on no service, so the router, the migration set and the reference data come from the suite.

  • ThrowawayDb::create(&DbTemplate) clones a database from the service’s migrated template (§ Template pre-warm) and drops it with the value, on a failing assertion too. A suite declares its template once, in a static (DbTemplate::new(base, &MIGRATOR), the base one of template_db::WARMABLE_BASES).

  • shipped_engine(jurisdiction) is the real authorization engine over the {jurisdiction}-authz-* rulesets of the pinned config layer; shipped_authz_source(jurisdiction) is its ruleset source, for a suite that boots its own engine with an admin-units source.

  • refusing_peer() is the base URL for the client of a peer service: loopback port 1, where nothing listens, so the client builds and each call through it fails to connect at once.

  • serve(router) binds 127.0.0.1:0, serves the router as given and returns its base URL, for a suite that drives it through a typed HTTP client.

  • outbox_events(&pool, event_type) returns the craig_mq::EventEnvelope`s staged in `event_outbox under a routing key, in staging order.

  • TestIssuer::devstack_realm() is the suite’s token source and its auth layer. user_token(username), role_token(Role) and service_token(client_id) mint RS256 access tokens for the test users and service clients of devstack/keycloak/craig-realm.json, read from the checkout at run time: role_token names the same worker TestHarness signs that Role in as. user_claims and service_claims return the same token unsigned, as a jwt_mutation::ClaimsBuilder, for a test that changes one claim first. auth_layer(service) is the AuthLayer a service boots: the devstack issuer, service as the required audience, the default roles path. It holds the key in memory, runs no refresh task, and verifies a minted token with no network call.

The issuer’s key is craig-auth’s bundled test key, compiled only under craig-auth’s test-fixtures feature, which cargo xtask release-artifact-gate keeps out of every release graph: no deployed service verifies a token it mints.

A minted token’s claims are held to the realm’s by the_test_issuer_mints_the_claims_the_realm_issues (crates/craig-test-lib/src/inproc/contract.rs, devstack). For each user and service client the issuer offers it obtains Keycloak’s token, by the password grant and the client_credentials grant, and compares the two decoded tokens. The values of iat, exp, jti and sid differ per token, so only their presence and the lifespan (exp minus iat) are compared. A service account’s sub is generated when Keycloak imports the realm, so it is compared as a UUID. The header is compared without kid. Arrays of strings and scope are compared without regard to order. The realm import states the principals, audiences, scopes and lifespans; which claims Keycloak’s mappers emit is written in inproc/issuer.rs, and that test is its only guard.

What the tier needs: the test-plane PostgreSQL instance (§ The test-plane Postgres instance) and the fetched config layers. PostgreSQL is part of the devstack, so a database-backed test keeps #[ignore = "requires devstack"].

What a suite on it may not use:

  • An allow-all authorization engine. The module offers none, and no_inproc_suite_uses_an_allow_all_engine (crates/craig-test-lib/tests/inproc.rs) fails on one. It reads every .rs file under each services/*/tests: a file that names inproc is in scope, and so is a file of the same service that names that file’s module in a path (crate::<module>::..). In scope, an ident spelling allowall in any case, with or without underscores, or FixedScope, is a hit. The one exemption is services/craig-cases/tests/api/keyed_harness.rs, which re-exports AllowAll for the suites built on it: it is not read, and naming it puts no file in scope.

  • The service’s shared devstack database. The router writes the throwaway database, so a pool on the shared one sees none of the suite’s rows. no_inproc_suite_opens_a_shared_service_database (same file) fails a file that names an adapter type (Inproc..) and calls postgres_test_db_url, or a free function that reaches it through any chain of helpers, in the service’s tests/ or in craig-test-lib. An unqualified call of a function the file itself defines is that function; every other call is matched by name. Methods and associated functions are outside the rule.

  • The object store. An adapter stores objects in a local scratch directory, not the devstack’s S3 store, so a test that uploads or downloads an attachment stays on TestHarness.

  • A peer’s real answer. A test that needs one stays on TestHarness. By default an adapter builds its client of every other service over refusing_peer(), so such a call fails to connect. A test of how the service handles a peer’s failure boots with boot_with(Peers { .. }) (#3160): each adapter has a Peers struct naming its outbound origins, and the test points one at a double (craig_test_lib::fault::s2s_stub, or wiremock) that answers 503, hangs, or returns an unusable body. The keyed harness takes its rules origin from ScreeningHarnessOptions, and its screening, safety and IV-E surface clients (h.screening, h.safety, h.ive) share that origin and bearer.

  • The broker. A test that asserts on a published event reads the staged envelope with outbox_events; a test that needs the delivery stays on TestHarness.

craig-cases' keyed harness (services/craig-cases/tests/api/keyed_harness.rs) takes its database, its shipped engine and its listener from the module, and holds no broker connection.

The authz witness in-process (#3160). The three services with in-process suites enable authz-witness on their craig-api and craig-bootstrap dev-dependencies, so every test build is witnessed, not only the battery’s. The adapters get the witness from build_router(..). The keyed harness assembles routes(..) itself, so it mounts the same pair: the engine a suite hands it is wrapped to count decisions, and the witness middleware sits on the routes inside a /v1 nest, the pattern the exemption ledger is keyed by. A 2xx from a keyed-harness route that asked the engine nothing and is no declared exemption is therefore the typed 500 authz-unwired, under an allow-all double too. The harness’s direct drivers (read, post, get_with_bearer, through under_v1) put a path spelled from the service root (/cases/reports) under /v1. This shows a handler asked the engine, not that policy answers correctly.

Which tier a test belongs on (#2302). A new API test of craig-cases, craig-placement or craig-financial goes in-process when all of these hold; otherwise it goes on TestHarness. A file is on one tier whole.

  • It reads only its own service’s responses and its own service’s database.

  • It builds its own rows through its own service: no case built through craig-cases for a craig-placement test, no projection waited on, no row of the devstack seed.

  • No route it drives consults the rules service (screening, conversion, safety assessment, IV-E, matching): that route answers 503 in-process.

  • It stores no object, waits on no job and no delivered event.

  • Its subject is not what the identity provider itself issues (a scope, an audience, an unauthenticated request to the deployed service).

  • No assertion of absence or emptiness is over rows the test did not key: an empty throwaway database satisfies such an assertion whatever the service did.

By those rules 30 files run in-process beside the three pilots: 20 of craig-cases, nine of craig-financial and one of craig-placement, where nearly every test first builds a real case through craig-cases. The rest stay on the deployed stack.

Cost. Each test is its own process, so it clones a database, boots the service and drops the database: about 0.45 s on the CI runner, against about 0.09 s for the same tests on the deployed stack (205 moved tests, median 89 ms before and 459 ms after; the port added about 70 s of summed test time and about 10 s of wall time to a car). What that buys is a test with a database of its own that needs only PostgreSQL. The password handshake of each PostgreSQL connection was a quarter of that until Cargo.toml built the hash crates and sqlx-postgres optimised in the dev profile; that setting also took 8 to 10 % off the summed time of the whole integration battery.

Adopting it. A service adds one adapter under its own tests/ that names craig_test_lib::inproc and builds the service’s real build_router(..). craig-cases' is services/craig-cases/tests/api/inproc_cases.rs: a throwaway database, the issuer’s auth layer for craig-cases, the shipped Georgia engine, MqRequirement::NotApplicable, and the rules service and craig-exchange pointed at refusing_peer(). It serves through ApiServer::serve_with_listener with the per-IP rate limiter off. An adapter implements craig_test_lib::harness::RoleClients, the per-role client constructors TestHarness has (caseworker_cases_client(), supervisor_cases_reports_client() and the rest), so a suite moves by replacing TestHarness::new() with InprocCases::boot() and a pool on the shared database with the adapter’s pool(); a fixture that only needs clients takes &impl RoleClients and serves both harnesses. A suite or fixture that names its own principal uses craig_test_lib::harness::Principals (endpoints(), user_token(username, password), service_token(client_id, secret)), which both harnesses also implement: the devstack harness asks the realm, an adapter mints the same principal’s token from TestIssuer and checks neither the password nor the secret. A test whose subject is what the realm itself issues (jws_replay_scope_gate.rs) stays on TestHarness. A test belongs there only if it reads nothing but that service’s responses and database; one that needs the broker, a peer’s answer or the rules service stays on TestHarness. Legs that drive routes(..) through the keyed harness with an authorization double live in their own file (cases_keyed.rs), because a file that names the adapter is under the allow-all census. craig-placement’s adapter is services/craig-placement/tests/api/inproc_placement.rs, on the same shape: its jobs runtime is built and never spawned, craig-cases and craig-security also point at refusing_peer(), and pool() lends the throwaway database to a test that counts its own rows. foster_homes.rs runs on it. craig-financial’s is services/craig-financial/tests/api/inproc_financial.rs: craig-cases and craig-placement refuse, the administrative-authority surface stays unverified, and every subsidy knob is at its default. request_claims_financial.rs runs on it, seeding its payments into the throwaway database with payment_fixtures::insert_pending_payment.

.gitlab-ci.yml — the car, scans, release

The YAML runs the developer’s commands (plan ci-dev-loop D2, #3046): a job’s script: is the cargo xtask verbs a developer types, as the xtask artifact (xtask <verb>), plus artifact plumbing; there is no cargo xtask ci. The merge train is the merge gate (ADR-086, #2923): on a train the car runs and blocks; on a plain MR it runs and blocks too (D4, #3028), so a train never admits a red car its MR pipeline could have shown. A car whose change is documentation no lane reads stops after its gates (#3101, Quality Gates § CI: the car).

workflow:rules restricts pipelines to MR pipelines (merge-train pipelines arrive as merge_request_event with CI_MERGE_REQUEST_EVENT_TYPE == "merge_train"), main, tags, schedules and measurement pipelines (below); a branch push without an MR produces no pipeline (#187). The MR rule ($CI_MERGE_REQUEST_IID, which trains match too) sets auto_cancel: {on_new_commit: interruptible, on_job_failure: all}: a job that fails cancels the pipeline and its running jobs, so a red car frees docs’ VM within seconds (plan ci-battery-ahead D3). A job allowed to fail (an advisory MR job, `docs’ exit 42) cancels nothing. The `main, tag and schedule rule has no on_job_failure; the top-level auto_cancel keeps on_new_commit: interruptible. pipeline_tests.rs pins both (only_mr_and_train_pipelines_cancel_on_a_job_failure). The measuring jobs (perf-load, perf-stress, issuer-capacity) are interruptible: false through .release-stack, so a newer commit never cancels a running measurement: its figures stay valid for its own commit, and nothing re-runs a cancelled manual job (#3171; pinned by a_newer_commit_never_cancels_a_running_measurement).

Measurement pipelines (#3178, #3185). To measure a branch’s head commit before it merges, start a pipeline on the branch with the variable MEASURE set to the job’s name: perf-load, perf-stress or issuer-capacity.

  • Starting one. In GitLab, Build → Pipelines → Run pipeline: choose the branch and fill in MEASURE, which the form lists with its description. From a shell: glab ci run --branch <branch> --variables-env MEASURE:perf-load. issuer-capacity reads its options from ISSUER_CAPACITY_ARGS in the same pipeline’s variables; its value holds spaces and commas, which --variables-env splits, so pass both variables in a JSON file:

    cat > measure.json <<'JSON'
    [{"key": "MEASURE", "value": "issuer-capacity"},
     {"key": "ISSUER_CAPACITY_ARGS", "value": "--steps gates,gates-below --r 3"}]
    JSON
    glab ci run --branch <branch> --variables-from measure.json

    Any other value of MEASURE creates no pipeline (GitLab answers "The pipeline did not run. Review the workflow:rules configuration"), so a mistyped name is refused at once instead of running nothing and passing.

  • What runs. ci-image, xtask and the named job, on the release images baked from that commit. No other job: the car, the docs build and the other two measuring jobs are absent, and the GitLab scan templates are switched off through their *_DISABLED variables.

  • Nothing cancels it. The workflow rule sets auto_cancel: {on_new_commit: none, on_job_failure: none}.

  • Why a pipeline of its own. GitLab’s on_job_failure takes all or none for a whole pipeline, and no keyword exempts one job. While issuer-capacity was a play button on the MR pipeline, a red car cancelled a measurement twenty minutes in (#3178). The measuring jobs are therefore on no MR pipeline and no train.

  • On main. Use the play buttons on main’s own pipeline, as before: it has no on_job_failure, so nothing cancels a job there. MEASURE changes nothing on main, since the main rule comes first.

  • The field key. The perf jobs write the devstack’s field keys from the encrypted store with the protected CI identity, which reaches protected refs only. On an unprotected branch xtask secrets write-field-key says so and writes nothing, and dev start mints a throwaway key, as it does for every MR car (ADR-048, the #3185 amendment).

pipeline_tests.rs pins the rule and what it admits (a_measurement_pipeline_is_started_by_hand_and_nothing_cancels_it), the jobs that run (a_measurement_pipeline_runs_the_named_job_and_only_what_it_needs), that a measuring job answers MEASURE in a branch pipeline only (a_measuring_job_answers_measure_in_a_branch_pipeline_only) and the scans' switches (a_measurement_pipeline_switches_off_every_included_scan).

CI stages: the car

A car is four jobs: ci-image → xtask → car ∥ docs. car is one job on one VM (timeout: 2h, interruptible, needs: [{job: xtask, artifacts: true}], $CI_RUNNER_TAG), whose script is validate --profile full’s car lines word for word (`validate::car_lines, xtask/src/cmd/validate/car.rs). GitLab stops at the first failing line, so a red gate stops the car before any compile. Its three steps:

Step Lines Notes

Gates

cargo fmt --check --all; xtask config fetch (the locked layers the scenario, citation and JDM audits read, #3014); one line per row of validate::GATES, in its order (Quality Gates § Precompilation gates); xtask lints dockerignore-canary; xtask gitleaks

No workspace compile. GIT_DEPTH: "0" gives gitleaks HEAD’s whole history (#2892).

Stack

xtask dev clean --any-project, then xtask dev start

The purge removes every container, volume and network carrying the checkout’s compose label (a reused VM keeps a previous job’s, #2946). dev start is the one compile in craig-tools (musl, --profile devstack, #3044), the copy-only images, the infra images, identity, health and seed.

Lanes

xtask test --unit $CRAIG_UNIT_FLAG; xtask test --clippy; xtask lints source-ownership; xtask test --doc; xtask test --integration --profile ci-integration; xtask api-docs --check; xtask e2e; xtask e2e --scenario subsidy-generator-backlog --scenario foster-home-at-capacity --grep @seed-variant (the seed scenario variant legs, § Seed Data, #2610); xtask e2e --degraded (each of the three reseeds first: the battery mutated the seeded rows the specs assert); xtask sdk-test; xtask security --skip-zap --skip-fuzz; xtask perf --profile smoke

On a train .car-rules sets CRAIG_UNIT_FLAG: "--leave-to-battery": the battery’s --run-ignored=all runs those tests (#2995). Source ownership replays the clippy units, so it runs right after test --clippy (#3043). The battery lane first runs, on CI, the every-target cargo fetch, then the contested census and the nextest filter terms over the inventory the one compile holds.

after_script

.stack-teardown: xtask dev logs --to test-results/container-logs --skip-on-success, xtask dev clean --confirm

The stack’s logs when the car failed.

GitLab keeps 4 MB of one job’s log, and the car carries what four jobs printed: it sets NEXTEST_STATUS_LEVEL and NEXTEST_FINAL_STATUS_LEVEL to fail, which craig-tools inherits (docker::CI_PASSTHROUGH), so a pass prints nothing and a failure prints in full; the JUnit reports under test-results/ keep every result. car extends .test-results and .stack-teardown, so its artifacts are developer-only (the repository is public). It pulls the LFS baselines e2e compares in its before_script (#1891). It pushes nothing.

pipeline_tests.rs (xtask/src/pipeline_tests.rs) holds the YAML to it: the car’s gate block equals GATES, one line per gate in its order (the_cars_gate_block_is_the_gate_table); the whole script equals validate::car_lines (the_car_runs_validates_car_lines_in_order); every car line is cargo fmt, cargo machete or xtask <verb>, and none runs xtask ci, docker, cargo nextest or cargo build (every_car_line_is_a_developer_command); the purge precedes dev start and source ownership follows test --clippy (the_purge_precedes_dev_start_and_source_ownership_follows_clippy); the car blocks a train and an MR whatever either changed (the_car_blocks_a_merge_train_whatever_the_car_changed, a_plain_mr_runs_the_blocking_car_whatever_it_changed, no_car_rule_is_path_filtered), and its docs-only stop sits between the last gate and the stack (the_docs_only_stop_sits_between_the_last_gate_and_the_stack); only a train leaves the unit tests to the battery (only_a_train_car_leaves_the_unit_tests_to_the_battery); the job’s shape and log bound (the_car_job_runs_on_one_vm_with_a_bounded_log); --push appears only in release-build; every job has needs:; no line names xtask ci or the old registry hand-off (no_job_runs_a_retired_ci_verb_or_hands_images_over); and the file stays under 500 lines (the_pipeline_stays_under_its_line_bound).

Job Lines Runner Needs

ci-image

cargo xtask ci-image --ensure (the one cargo xtask line: it runs before the xtask job)

$CI_RUNNER_TAG

none

xtask

cargo build -p xtask -p craig-config-fetch -p craig-seed (artifacts under target/ci/bin/), then lints mandatory-docs, plan-lint, lints doc-pointer-integrity

$CI_RUNNER_TAG (the 4xlarge)

ci-image

car

the table above

$CI_RUNNER_TAG

xtask

docs

the Antora build, the review site and the external-link check (§ Scans and policy)

$CI_RUNNER_TAG

ci-image

identity-multibackend (a leaf, not a car job)

xtask identity matrix

$CI_RUNNER_TAG

xtask

  • xtask is compiled once per pipeline (#2982, plan ci-compile-once D2). The xtask job runs one cargo build in craig-ci, copies the binaries to target/ci/bin/ and ships them (7 days: a plain MR’s manual leaf jobs may run days later). Every job that runs xtask needs the artifact with artifacts: true and extends .xtask-bin, whose before_script puts target/ci/bin first on PATH; a job with its own before_script, and .stack-teardown’s `after_script, start with !reference [.xtask-bin, before_script]. xtask config fetch starts the shipped craig-config-fetch when the checkout holds it (#2955), and e2e’s seed-manifest regen the shipped craig-seed (#3005). A verb re-executed in craig-tools re-runs the artifact itself (`docker::xtask_argv_head). The job also runs the docs' content lints, so a stub page or a broken plan status fails in minutes. pipeline_tests.rs pins the job (the_xtask_job_builds_ships_and_lints_the_docs) and refuses a job that runs xtask without the artifact or before the PATH line (every_job_that_runs_xtask_takes_the_artifact_and_finds_it_on_path).

  • Where a lane runs. A verb that dials the stack (test --integration, e2e, security, perf) re-executes in craig-tools on the project network, where every service answers by its container name: the stack publishes no host port, so nothing in the car dials the VM from the job container. test --unit runs in craig-tools from the one compile, off the network; sdk-test runs its runtimes as sibling containers from the job container; test --clippy, test --doc, api-docs --check and the gates run in the job container (main::hands_paths_to_docker, pinned by each_car_lane_runs_where_its_dialing_and_mounts_need).

  • A failed stack job keeps its container logs (#2939). Under ADR-086’s no-retries ruling a flake is diagnosed from its one job, and dev clean destroys the containers. The car, the scheduled stacks, the identity job and the release build (#3167) extend .stack-teardown, whose after_script first runs xtask dev logs --to test-results/container-logs --skip-on-success: when CI_JOB_STATUS is not success, it writes docker logs --timestamps of every container labelled with the checkout’s compose project to <container>.log, each its last 4 MiB, then dev clean runs. It runs no docker inspect, so no container environment reaches the files. pipeline_tests.rs pins the order, the upload and the access (every_stack_job_captures_its_container_logs_developer_only_before_it_cleans).

  • The identity-multibackend plane (#2641). cargo xtask identity matrix is the developer’s verb for the plane and the ADR-086 leaf job’s one line, outside the car and validate --profile full. It owns the fixed craigidp project: it removes any earlier one with its volumes (ZITADEL writes its bootstrap PAT only on a fresh database), brings it up with up --wait, runs dev zitadel-bootstrap and dev kanidm-bootstrap, then nextest’s identity-multibackend profile with --run-ignored only --no-tests=fail; on a failure it keeps the IdP containers' logs, and on every outcome it runs down -v. The bootstraps and legs dial the IdPs at localhost:<port>, the only host ZITADEL answers to, so on CI those three steps run in craig-tools on the host network (docker::tools_exec_on_host_network). It first pulls the kanidm/tools image through the proxy on the host and tags it under its docker.io name (hub_proxy::IDENTITY_HUB_IMAGES). The job runs on every schedule; on a train it runs and blocks only when identity code or the plane’s inputs change; on a plain MR with such a change it is manual and advisory. pipeline_tests.rs pins the triggers and the shape (the_identity_job_runs_only_nightly_or_on_identity_changes, the_identity_job_runs_the_leaf_stage_with_needs_and_the_stack_teardown).

  • Every job declares needs: (#2944): the jobs outside the car carry their own, so they run from t=0 beside it instead of waiting on GitLab’s stage order. pipeline_tests.rs refuses a job with no needs: of its own or a template’s (no_job_waits_on_stage_order).

  • .car-rules triggers the car on every merge train (allow_failure: false, no changes:); with ci-image, xtask and docs a train runs exactly four jobs whatever it changed, all blocking (a_train_runs_exactly_the_four_car_jobs_and_each_blocks). On a plain MR the car runs blocking when the MR changes code or an input the stack runs (manifests, xtask/**/*, the store, rulesets, migrations, devstack/**/*, the compose files, Dockerfile, .dockerignore, tools/**/*, tests/**/*, .githooks/**/*, .config/nextest.toml, this file), and docs runs advisory on every MR.

  • CI_RUNNER_TAG is dhs-aws-autoscaler-docker-4xlarge (#2923; no fallback runner, ADR-086 § D3 amended 2026-11-07), a docker+machine executor whose job containers are privileged and drive the VM’s Docker through the mounted socket: one VM per car. No job declares services: [docker:dind]: the stack and craig-tools run as sibling containers on the VM’s daemon.

  • The /builds alias. On that executor /builds is a per-job Docker volume, so a sibling container binding $CI_PROJECT_DIR would see an empty directory. Every verb that hands paths to the daemon (the dev verbs, test --unit, test --integration, e2e, security, perf, sdk-test, gitleaks, migrate, identity matrix, cluster-tests) first finds its job container (docker ps by the runner’s job.id and type=build labels), reads the volume’s VM path from its /builds mount, bind-mounts /builds onto that path and re-runs the same argv from it (xtask/src/builds_alias.rs; a bind mount, since getcwd resolves a symlink back; CRAIG_CI_BUILDS_ALIAS guards the re-run). It does nothing off GitLab, on an instance executor, under dind, or where /builds is not a volume.

  • craig-tools' environment (#2943). A verb in craig-tools inherits, by name (-e NAME, no value on the command line), every CRAIG_* variable, DOCKER_HOST and exactly docker::CI_PASSTHROUGH: GITLAB_CI (the battery’s every-target fetch runs on CI), CI_REGISTRY_IMAGE (a compose recreate there names the images dev start tagged), CARGO_PROFILE_TEST_DEBUG and the two nextest status levels. No job credential (CI_JOB_TOKEN, CI_REGISTRY_PASSWORD) is passed in. A craig-tools run never takes the /builds alias: its checkout is already at the daemon’s path.

  • Caches (#2931). Every job is a fresh VM; the car builds what the registry does not hand it, and pushes nothing.

    • Cargo. CARGO_HOME is craig-ci’s /usr/local/cargo, outside the checkout, so cargo’s caches are never tree changes dev start’s staleness check or a build context could see; there is no runner cache. The unit lane and, on CI, the battery lane first run an every-target `cargo fetch --locked (#2762, #2987), so no test’s cargo call downloads while holding cargo’s package-cache lock. The workspace compiles once per car, into craig-tools' target/craig-tools, and every lane reuses it there.

    • xtask. No cache: the xtask job’s artifact (above).

    • craig-tools is tagged $CI_REGISTRY_IMAGE/tools/craig-tools:<sha256>, the hash of its Dockerfile stage’s text (the stage copies nothing from the build context; a unit test holds it to that). With CRAIG_TOOLS_FROM_REGISTRY=1 (a pipeline variable) a craig-tools run pulls it; on a miss it builds it with the daemon’s own builder, and pushes it only on a pipeline without a merge request (main, a tag, the schedule): a car reads the registry and never writes it (tools_registry::may_push_tools, plan ci-dev-loop D5). Locally nothing changes.

    • craig-gitleaks and craig-devtools go the same way under the same variable (#3025): a CI job missing one pulls $CI_REGISTRY_IMAGE/tools/<repo>:<content tag> (devtools::named_image_ref), builds it when the registry answers not-found (pushing it only where craig-tools would), and fails naming that reference when the registry answers anything else.

    • No BuildKit container, no registry cache (#3026). dev start builds the devstack images by copy and the infra images by compose, both with the VM daemon’s own builder; ci-image --ensure builds craig-ci the same way. Only release-build runs buildx (docker buildx bake, #3045), and reads no registry cache.

    • Docker Hub through the Dependency Proxy (#2933). Docker Hub allows an anonymous IP ten pulls an hour, so every Docker Hub pull a car makes goes through the direct group’s Dependency Proxy. DOCKER_HUB is ${CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX} (the top-level group’s prefix answers 404 for this project), and the job images (ci-image’s `rust, antora) name it in the explicit library/ form where official; pipeline_tests.rs fails on an image outside it, on one that names docker.io outright, and on any other DOCKER_HUB value. The runner authenticates job images itself. For the pulls a job’s own daemon makes, the job container first runs docker login "$CI_DEPENDENCY_PROXY_SERVER" (the password on stdin): the .dockerignore canary, dev start, sdk-test, ci-image --ensure, a craig-tools or craig-devtools build, identity matrix and cluster-tests. Then every Docker Hub FROM reads ARG BASE_REGISTRY=docker.io, which the xtask builds pass as --build-arg and compose’s infra overlays take as build.args: [BASE_REGISTRY] (set only on CI). craig-tools gets neither the prefix nor the login: before main re-executes perf there, the job container pulls the k6 image it docker run`s (`hub_proxy::craig_tools_hub_images) through the proxy and tags it under the docker.io name the run uses; a unit test fails on a craig-tools run image missing from the list. Locally DOCKER_HUB is unset and everything still pulls from docker.io. One path is not routed: cluster-tests' two compose app builds, a scheduled job rather than a car.

    • The other registries through the project registry’s mirror (#3053). The Dependency Proxy fronts Docker Hub only, so the images pinned on quay.io, mcr.microsoft.com and ghcr.io (Keycloak, Playwright, Toxiproxy, Authentik, ZITADEL, ZAP) are copied into $CI_REGISTRY_IMAGE/mirror/<host>__<path>:<tag> (each / of the upstream name written __, since GitLab allows two path levels below the project; a reference pinned by digest alone is tagged sha256-<hex>). MIRRORED in xtask/src/registry_mirror.rs is the one list, and a unit test holds it equal to every non-Docker-Hub reference in the tracked Dockerfiles, compose files and xtask image constants. The mirror-sync job (every schedule, and by hand on main) runs xtask mirror sync: for each row it compares the upstream digest with the copy’s (docker buildx imagetools inspect, no pull), copies a missing or moved one registry to registry (imagetools create, every platform), reads the copy back, and prints one line with the old and the new digest; a failed row fails the job after the others ran. A digest-pinned row never asks its upstream. cargo xtask mirror check prints the same comparison anywhere and writes nothing. In a GitLab job, the verb that needs an image first pulls its copy and tags it under the upstream name (registry_mirror::stage_for: dev start, a craig-tools build, the e2e image build, the ZAP phases, identity matrix, cluster-tests), so the FROM, the compose image: or the docker run finds it in the daemon; no Dockerfile or compose file names the mirror. When the mirror lacks the copy or does not answer, the verb prints … is read from its upstream registry, not the mirror and carries on, so a car on a new pin still runs, on the upstream registry’s availability until the next sync. Locally nothing changes. To add an image or bump a pin: edit the reference where it is used, add or edit its MIRRORED row with the verb that stages it (the unit test names a missing row), and after the merge run mirror-sync by hand on main or wait for the schedule.

    • A registry’s transient failure is retried (#3053). A docker login, a docker pull and a build that resolves its FROM base from a registry each get three attempts, 5 s and then 15 s apart, through one helper (xtask/src/registry_retry.rs). An attempt is retried only when its stderr shows a registry’s HTTP 5xx (502 Bad Gateway, 504 Gateway Time-out) or a timeout or reset connection on a registry request (context deadline exceeded, i/o timeout, TLS handshake timeout, connection reset by peer), or a login the registry answered with 429 Too Many Requests (#3161: several cars logging in at once); each retry prints one line with the command, the signature, the attempt and the wait, and a final failure says how often it was retried. Everything else fails at once, as before: a 401, 403 or 404, manifest unknown, denied, a pull’s rate limit (toomanyrequests, or a 429 on anything but a login), a failing RUN step (an apk or cargo download included) and any text the helper does not recognise. A re-run build repeats nothing it finished, because BuildKit caches completed steps. A pull the registry still fails after its retries is never read as "the image is not there": craig-tools is not rebuilt from upstream on that answer. Not retried: an image push, docker compose up or docker run pulling an image it lacks (the SDK suites pull theirs first, retried), and release-build’s two shell `docker login lines and its docker buildx bake.

Scans and policy (all branches, parallel)

  • cargo-deny (the one RustSec scanner, #2658; also on every schedule), and the GitLab sast, secret_detection, dependency_scanning templates. The job runs cargo deny check twice (#3205): over the workspace for the three Linux targets deny.toml names, and over the reference partner module’s own workspace (crates/craig-partner-host/tests/modules/reference/partners/src) for wasm32-unknown-unknown, which is the graph a partner module is built from: the SDK’s guest half, wit-bindgen and its generator. That workspace commits no lock; the job first copies the workspace’s Cargo.lock beside it, as cargo xtask partners build --fixtures does, so the scan reads the versions a module is built from. Both runs read the one deny.toml. The second passes -A advisory-not-detected, because the file’s advisory ignores are the workspace graph’s and an ignore the module graph does not hold is not a stale one; an advisory in the module graph still fails it.

  • secrets-policy: xtask secrets policy (recipient parity, the secret-key needle, and with the protected CRAIG_CI_AGE_KEY the keyed decrypt proof) on store changes, main, tags and schedules.

  • The xtask job’s content lints (#2091, #2982) and docs: the docs gates that answer in minutes. A docs-only car also runs every gate before it stops (#3101).

  • The docs checks (docs, in the Antora image, with CRAIG_LINK_CHECK=1; #2981, #2984). One Antora build serves the xref gate, the review environment (review/<branch>, its site uploaded even on exit 42) and the link check. In order:

    • node docs/extensions/mermaid-render.test.js and node docs/extensions/link-check.test.js, the docs extensions' tests. The link-check tests serve their own links from a throwaway HTTP server on 127.0.0.1 and run the real antora CLI over a fixture component.

    • antora antora-playbook.yml --log-failure-level=warn --to-dir public (then cp -r mock public/mock, the review site): a broken internal xref, or any Asciidoctor warning, fails the job (blocking). The same build runs the link-check extension (docs/extensions/link-check.js). It turns on Asciidoctor’s catalog_assets and checks every external http(s) link and remote image each page catalogues, with the page, component and playbook attributes substituted. A link inside a code sample is not checked. The extension writes the antora section of build/link-check.json and prints one link-check: DEAD <page> <url> line per dead link. It never logs through Antora’s logger, so a dead external link cannot trip the xref gate.

    • node docs/extensions/link-check-prose.js checks the repo-root prose outside Antora (README, CONTRIBUTING, CHANGELOG, SECURITY, and the *.adoc files in changelog/ and changelog.d/) the same way, into the report’s prose section.

    • node docs/extensions/link-check-verdict.js --expect antora,prose exits 42 when the report holds a dead link. The job allows exactly that exit (allow_failure: {exit_codes: [42]}), on a train too, where its rule sets no allow_failure that would replace it: a site’s outage is no car’s fault (ADR-086 D6). A missing report or section exits 1 and fails the job.

      The checker sends HEAD, then GET when HEAD is not accepted, with a browser Accept header, up to 8 requests at once, a 30 s timeout and 3 retries with backoff on a network error or a 5xx. 2xx, 403, 405, 406 and 429 count as live. Fragments are never checked. Not checked at all: loopback, private and link-local hosts, single-label hosts, hosts that are placeholders (<host>, craig-*), the placeholder domains, and the listed URL patterns with their reasons (EXCLUDES in docs/extensions/link-check-core.js, ported from the retired .lychee.toml). pipeline_tests.rs pins the job’s script lines, the switch and the allowed exit. local-dev § Docs link check shows the local run.

  • feature-matrix (on main and the schedule, never on a car; plan ci-compile-once decision 2) on $CI_RUNNER_TAG.

  • Scheduled stacks (pentest, perf-load, perf-stress) bring their own stack up, the field key from the encrypted store via cargo xtask secrets write-field-key, then run their verb: pentest with xtask dev start (the devstack build of the job’s commit); the perf jobs with xtask dev start --release --bake, which bakes the job’s commit’s release images as release-build does, tagged with its short SHA, and starts the stack on them (#3157). Each bake adds about 16 minutes. cluster-tests and policy-drift call theirs.

  • fuzz-smoke (#3207): xtask fuzz --install --seconds 60, the three fuzz targets for a minute each (§ Fuzz targets). It is started by hand, on a merge request that changes tools/craig-fuzz/, the crates the targets read or the module contract, and it is advisory: a minute a target shows that the harness still builds and runs, and finding something takes the longer runs a developer makes.

  • xtask/src/pipeline_tests.rs fails on a script: line that is neither an xtask verb nor on its allow-list or its job’s own lines, and on any line running docker compose, cargo nextest, cargo build or docker build outside them (the car’s contracts: § CI stages).

  • Every rules: changes: directory entry is dir/**/*: GitLab matches with Ruby File.fnmatch?, where dir/** is one level only (#2219). The test-only ci_changes module fails on any glob ending in /** and pins a file two levels below each directory .car-rules, feature-matrix and secrets-policy watch to that filter.

Stage 2: promote (tags, the schedule, by hand on main)

  • release-build (plan ci-dev-loop D3, #3045): docker buildx bake --file docker-bake.hcl release --load builds the 12 deployable service images (the bake file’s release group, bake::RELEASE_TARGETS) into the VM’s daemon; the local release-stack group builds craig-seed, craig-mock-server and the TLS intake for the smoke, never pushed. xtask dev start --release brings the stack up on those images, then xtask perf --profile smoke and xtask security --phase public-api; only then does … release --push push the same images as :<sha8>, plus :<tag> and :latest on a tag, so a red smoke pushes nothing. No job but release-build pushes, its push comes after the smoke lines (pipeline_tests.rs), and it runs on no merge request or train. It is a stack job: a failed run keeps its containers' logs, developer-only (#3167); deployment-guide § Release images has the schedule, the manual run and where the logs land

  • release-sbom (tags and the schedule, #3167): xtask sbom, the workspace’s CycloneDX SBOM, as a public artifact that never expires. It is apart from release-build because a job’s artifacts have one access level and that job’s are developer-only; release-build waits for it (an optional need, since main has no release-sbom), so nothing is pushed without an SBOM

  • release-notes (tags): the tag’s changelog section, which release publishes with the SBOM

  • The test-only ci_changes module pins the release group to every FROM runtime stage but the two devstack/test images and devstack-runtime

  • Runs on the pipeline default, $CI_RUNNER_TAG (the 4xlarge)

Stage 3: deploy

  • docs (beside the car, above) starts the review app, Antora docs + mock UI

    • stop_review: manual, allow_failure: true

  • pages: Antora docs + mock UI to GitLab Pages (main branch)

  • Every job runs on the 4xlarge: default: tags: [$CI_RUNNER_TAG], and no job or template names another tag (pipeline_tests.rs). No job uses a smaller runner: wall time beats queue savings.

Security Scanning (OWASP ZAP + ffuf)

Setup

  • No local install required — runs via Docker (ZAP 2.17.0 pinned by digest, The pinned ZAP image (#2812); ghcr.io/ffuf/ffuf)

  • Configs: tests/security/zap-*.yaml (ZAP Automation Framework), tests/security/ffuf-wordlist.txt

  • Auth hook: tests/security/zap-auth-hook.js (injects a Bearer token, minted via ROPC, into phase 1c’s /v1/ requests, and re-checks the bearer when a service answers 401; it fails closed, see below)

  • Submission hook: tests/security/zap-public-submission-hook.js (gives each phase 1a attack on POST /public/v1/reports a fresh client_request_id, an empty honeypot, the devstack’s admin unit and empty arrays wherever ZAP’s generated value still stands; it fails closed, craig-intake’s DAST scope (#2781, #2789))

Running

  • Full scan (all 7 phases): cargo xtask security

  • Skip ZAP: cargo xtask security --skip-zap

  • Skip ffuf: cargo xtask security --skip-fuzz

  • Regression only (pre-push): cargo xtask security --skip-zap --skip-fuzz

  • One or more phases: cargo xtask security --phase <name> (repeat the flag to subset; omit to run all 7). Phases: public-api|public-web|authenticated-api|auth|injection|infra|fuzz

  • Phases: 1a public-api (ZAP), 1b public-web (ZAP), 1c authenticated-api (ZAP), 2 auth boundary (reqwest), 3 injection (reqwest), 4 infrastructure (reqwest), 5 path fuzzing (ffuf)

  • Targets (#2673): every craig-* service the devstack publishes (docker::craig_service_container_ports, the port registry) is a target unless xtask/src/cmd/security.rs names it with a reason. NOT_SCANNED holds the craig-intake profile variants, which run the craig-intake image; phase 5 fuzzes every other target, craig-composition, craig-portal and craig-intake-keyring included. NOT_BEARER_API keeps the two BFFs and the keyring out of the 401 smoke and the CORS check, and the ledger xtask/baselines/cors-exempt.toml keeps craig-intake (wildcard CORS by design) out of the CORS check. Each bearer API’s unauthenticated probe route is in UNAUTH_PROBE_PATHS, which a test holds to the targets.

  • Where they run: phases 1a–1c and 5 (fuzz) run automatically only in the pentest CI job (scheduled pipelines, or by hand on a main pipeline, allow_failure: true; § CI below), and locally when invoked as above. They never run in the pre-push battery, which runs phases 2–4.

  • A ZAP run that stalls after its plan (#3158): ZAP can print Automation plan succeeded! and then never exit, which held the pentest job until its two-hour limit and kept the later phases from running. cargo xtask security names each scan’s container, and stops it when it is still running five minutes after that line; the phase then passes on the plan’s own verdict and says so in its output. A run that never prints the line is not bounded.

The pinned ZAP image (#2812)

ZAP_IMAGE in xtask/src/cmd/security.rs is ghcr.io/zaproxy/zaproxy:2.17.0@sha256:030d3df57735dacbb83464854758e674dd9ad01d79d12a129a8e58b1fd384238: ZAP 2.17.0, pinned to its multi-arch OCI image index (linux/amd64 and linux/arm64). Given a tag and a digest, Docker pulls by the digest, so every scan runs the same image until the pin is bumped. A tag alone would not hold it: ZAP’s release-main-docker.yml pushes each stable rebuild as <date>-stable, the release’s own version tag, stable and latest, and each rebuild refreshes the bundled add-ons (Dockerfile-stable runs zap.sh -cmd -addonupdate in its builder). On 2026-10-29 stable, latest, 2.17.0 and 20261026-stable all named this digest (built 2026-10-26, ten months after the 2.17.0 release); 20261016-stable names an older one. The unit test zap_image_is_pinned_to_an_exact_version_and_digest refuses a ZAP_IMAGE without a @sha256: digest, or whose tag is not an exact x.y.z version (stable, latest, a dated build).

What the digest carries, read through the registry API without Docker: ZAP core zap-2.17.0.jar, and in /zap/plugin both the release’s own openapi-beta-48.zap and the rebuild’s openapi-beta-58.zap (both architectures share that layer). ZAP 2.17.0 loads the newest version of an add-on it finds in a plugin directory (AddOnCollection), and add-on 58’s not-before-version is 2.17.0, so the scan runs OpenAPI add-on 58. The file’s SHA-256 (42356d81…) is the one ZapVersions-2.17.xml lists for the zap-extensions openapi-v58 release. cargo xtask security starts ZAP with -cmd -autorun and no -addonupdate, and ZAP’s command-line bootstrap runs no update check, so a scan never replaces these add-ons. The #2789 hooks' and model’s source-derived claims hold at these revisions:

  • zap-extensions openapi-v58: DataGenerator and BodyGenerator, the generator precedence that tests/security/zap-public-submission-hook.js and services/craig-intake/src/api/zap_generated_body_tests.rs model, and the import’s request under MANUAL_REQUEST_INITIATOR. Each generated value also passes through ZAP’s value provider (Form Handler 6.9.0 in this image), whose default field names match no SubmitReportRequest property (no_served_property_is_named_like_a_form_handler_default_field in that model pins it, #2814).

  • zaproxy v2.17.0: HttpSender.ACTIVE_SCANNER_INITIATOR (2) and MANUAL_REQUEST_INITIATOR (6), which the hook tests; ExtensionScript.getScript and handleScriptException and ScriptWrapper.isError, isEnabled and getLastErrorDetails, which the post-scan check calls.

To bump the pin:

  1. Take an anonymous pull token: curl -s 'https://ghcr.io/token?scope=repository:zaproxy/zaproxy:pull' (the JSON’s token).

  2. Read the index digest: curl -sI -H "Authorization: Bearer <token>" -H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json' https://ghcr.io/v2/zaproxy/zaproxy/manifests/stable. Require 200 and Content-Type: application/vnd.oci.image.index.v1+json, and take Docker-Content-Digest, the top-level index’s digest (never one platform’s manifest). Find the newest numbered tag (/v2/zaproxy/zaproxy/tags/list?n=1000, paged with &last=<tag>), read its digest the same way, and pin <version>@sha256:<digest> only when the two match.

  3. Identify the add-ons: GET the index, then its linux/amd64 manifest, and list the ZAP install layer (the COPY /zap . layer: find it through the image config’s history; the apt layer is larger) with curl -sL -H "Authorization: Bearer <token>" https://ghcr.io/v2/zaproxy/zaproxy/blobs/<layer digest> | tar -tz. The highest zap/plugin/openapi-*.zap version loads; check its SHA-256 against the ZapVersions-<major.minor>.xml entry.

  4. Re-check DataGenerator and BodyGenerator at openapi-v<N> against the model and the hook’s header, and the core APIs above at v<version>. Then update ZAP_IMAGE, this section, the hook and check headers, the model’s doc and security.adoc § DAST, with a CHANGELOG.adoc entry.

craig-intake’s DAST scope (#2781, #2789)

craig-intake serves three API nests. Only the anonymous one is in DAST scope:

  • /public/v1 is scanned in phase 1a. It needs no credential, so it belongs to the unauthenticated plan, tests/security/zap-public-api.yaml, which loads no auth hook. Its context URL, http://craig-intake:8008, puts everything under intake in scope; its include paths name /public/v1/. and /healthz, and its exclude paths keep /partner/v1/. and /signed/v1/. out. The openapi job imports intake’s document, and activeScan attacks the four public routes the devstack’s integrated instance mounts: the intake schema, report submission, the status lookup and the attachment upload. Phase 1c names no craig-intake host. It used to list http://craig-intake:8008 among its context URLs and import intake’s document (its /v1/. include matched no route), so its active scan sent the auth hook’s bearer to intake’s public and partner nests.

  • What phase 1a reaches on submission (#2789). The devstack leaves the bot-protection seam at its default none posture, so the CAPTCHA never refuses a scanner request. The public rate limit is 100000 requests per client IP per hour, a burst of 100000 that refills at about 28 a second. The scanner’s container is not a trusted proxy, so the X-Forwarded-For headers ZAP injects do not move it to another bucket. ZAP’s OpenAPI import builds the submission body from intake’s document (DataGenerator and BodyGenerator of the OpenAPI add-on 58, the one the pinned image runs, The pinned ZAP image (#2812)): each field’s non-empty default, else its first enum value (no SubmitReportRequest field has a default or an enum), else its example whenever it has one, a non-empty example as written and an empty one the type placeholder, never a date; a field with no example gets a 1970 date when it is a dated string, otherwise the type placeholder, "John Doe" for a string or an untyped field and true for a boolean. SubmitReportRequest carries jurisdiction-neutral examples (the api-docs gate refuses a served jurisdiction name), each a value the edge accepts: concerned_citizen, friends_neighbors, neglect, a 52-character concern_description, and valid tokens for mandated_reporter_category, reporter_relation (which craig-cases types as a RelationshipToChild) and the three relationship fields. reporter_type must be concerned_citizen, because the generator sends true for every boolean, anonymous included, which the edge refuses with any other reporter type. Five fields an example cannot fix: a static client_request_id makes every attack after the first accepted one a replay at craig-cases, or a 409 identity mismatch when its body differs; the generator drops website’s empty example and sends `"John Doe", which trips the honeypot’s silent 200; admin_unit’s example, `Example County, is a unit of no state, so the devstack’s state table refuses it; and children and adults are untyped, so they arrive as the "John Doe" string, not arrays (an example would arrive as a quoted string too). Phase 1a therefore loads two scripts: the submission hook tests/security/zap-public-submission-hook.js, before its openapi job, and its post-scan check (next bullet). On every active-scanner request (ZAP 2.17.0’s ACTIVE_SCANNER_INITIATOR, 2) that POSTs a JSON object to /public/v1/reports, it replaces a top-level member’s value only while it still holds the generator’s value: client_request_id (the example or "John Doe") with a fresh random UUID, website ("John Doe") with "", admin_unit (the example or "John Doe") with ZAP_PUBLIC_ADMIN_UNIT, which xtask passes as the devstack’s unit (DEVSTACK_ADMIN_UNIT, also phase 3’s), and children and adults ("John Doe") with []. A field holding anything else is the active scan’s payload and is sent as is. The edit is made in place: the hook scans the body only far enough to find those five members' value spans at the top level and splices each replacement into the sent bytes, so every other byte reaches the edge as the attack wrote it (a duplicate member, a 25-digit integer, 1e400, odd whitespace or key order, bytes that are not valid UTF-8; it reads and writes the body one byte per character, as ISO-8859-1). It leaves a body wholly unchanged when it is not one cleanly scanning object (not an object at all, an unterminated string, unbalanced brackets, trailing text), when one of the five members appears twice or a key cannot be decoded, or when nothing needs reseeding; a same-named key inside a nested value is never touched. It leaves the import’s own request alone, because ZAP stores that request, as the script saw it, as the message its active scan attacks from; rewriting it would plant one id in every attack. So an attack on one field leaves every other field valid. It meets that field’s own refusal (the body parse for client_request_id, the silent drop for website, validation for the rest), and one the edge accepts is forwarded and persisted at craig-cases as a new report. An attack that keeps the generated id is never a replay; one whose payload is itself a UUID keeps it, and may replay or conflict. Each accepted attack leaves a report in the devstack’s database. Child and adult entries are attacked only as a whole array, never entry by entry; the evil corpus (evil_corpus.rs and evil_corpus_breadth.rs, below) covers the entries.

  • The submission hook fails closed. An exception while the hook loads (reading ZAP_PUBLIC_ADMIN_UNIT, say) or an absent or blank ZAP_PUBLIC_ADMIN_UNIT stops the scan at the first request the hook sees, whatever its initiator (a hook that cannot even reach System.exit, or that ZAP never evaluates, is the next bullet’s check’s to catch); an exception while it reads or rewrites a scanner submission (ZAP disables a script that throws, and the scan would carry on against the parse refusal and the honeypot) stops it before that request leaves. Each prints one line, ZAP public submission hook: FATAL: <cause>; stopping the scan (exit 5), and exits ZAP with 5; xtask reports exit 5 on phase 1a as that refusal. A changed body’s Content-Length is set to match.

  • Phase 1a checks the hook ran and stayed in force. A hook ZAP cannot evaluate, or disables for throwing, is gone, and the scan can run on without it and still exit 0; ZAP writes the unwrapped cause’s toString() for such a failure, which need not name a script exception. So the hook writes ZAP public submission hook: reseeded a scanner submission the first time it reseeds a scanner submission. After the active scan (and the report, so a refusal still leaves it) the plan adds and runs a standalone check, tests/security/zap-public-submission-hook-check.js, which looks the hook up through ZAP’s ExtensionScript.getScript and writes ZAP public submission hook: still enabled after the scan only when the hook is loaded, has no recorded error (ScriptWrapper.isError) and is enabled (isEnabled); otherwise, or on any exception while checking (one try), it prints ZAP public submission hook check: FATAL: <cause>; stopping the scan (exit 5) and exits ZAP with 5. Both scripts write these lines straight to the JVM’s stdout and flush them, since headless ZAP writes print through a PrintWriter it does not flush per line. cargo xtask security echoes phase 1a’s ZAP output as it captures it and fails the phase when a run that exited 0 lacks either line, or shows a line naming ScriptException or PolyglotException (a supplemental refusal; the check is what establishes the hook stayed in force). The check’s ZAP API calls were read from the zaproxy sources and exercised only against stubs; the real engine first runs it in the scheduled pentest job. A call that does not match the running ZAP fails the phase (a false failure, never a false pass); the calls were checked against ZAP 2.17.0, the core in the pinned image (The pinned ZAP image (#2812)).

  • /partner/v1 and /signed/v1 are out of DAST scope. /partner/v1 takes an X-Api-Key and, integrated, a JWS signature; /signed/v1 takes a JWS signature alone. Without a fixture API key and a signer, a scan meets only their auth refusal, so phase 1a excludes both nests. These suites compensate:

    • The evil corpus, in the categories String, Unicode, Path, Html, Uuid, Date, EnumValue and Json. Behind valid credentials, they are partner_path_handles_evil_corpus_cleanly in services/craig-intake/tests/api/partner.rs (API key and JWS) and signed_path_handles_evil_corpus_cleanly in services/craig-intake/tests/api/signed_submit.rs (JWS). POST /public/v1/reports has its own, evil_corpus.rs and evil_corpus_breadth.rs, in the same directory.

    • The JWS suites in services/craig-intake/tests/api/: jws.rs (verification against the real signer-key registry), jws_error_uniformity.rs (one uniform 401 for every verification failure), jws_partner_binding.rs (the signer key must belong to the API key’s partner), jws_replay.rs (the jti and iat replay defense), signer_key_expiry.rs (an expired key stops verifying) and signed_submit.rs (the signature-only SHINES nest).

    • The API-key boundary: auth.rs and cross_partner_bola.rs in the same directory.

A ZAP hook that signs requests, which would bring both nests into DAST scope, is #2784.

Unit tests in xtask/src/cmd/security.rs pin this in the committed plans. Phase 1a’s one context has exactly the include paths /public/v1/. and /healthz, excludes both nests, imports intake’s document, and is actively scanned. Its script jobs are exactly the submission hook, added before every openapi and activeScan job, and its check, added and then run after the last activeScan; never the auth hook (#2789 replaced #2781’s "no script job" pin deliberately; ZAP’s run action needs the script already added, hence three jobs). Phase 1c’s plan names exactly the AUTH_PROBES hosts, in its context URLs, its include paths and its openapi jobs. submission_hook_tests, in the same file, pins the hook’s code with its comment lines blanked: its exit equals xtask’s SUBMISSION_HOOK_EXIT, its one exit, its guarded load stopping the first request, its one try, the initiator and route guard, the whole splice and replacement rule, the refusal of a duplicated member, its marker equal to the line the runner looks for, no setHeader( and no java.net (so it carries no credential), and its two seeds equal to the client_request_id and admin_unit examples in crates/craig-intake-contracts/src/report.rs. It pins the check too: its exit equals the hook’s, one try spans the lookup through the success line, the lookup is getScript of the name the plan adds the hook under, a recorded error and then a disabled hook are refused, and its success line equals the line the runner looks for. Unit tests hold the runner’s output check to its verdicts (both lines pass; either missing, or a script-failure line, refuses) and run_zap_scan to applying it after the exit check. It also holds DEVSTACK_ADMIN_UNIT to a unit of the jurisdiction docker-compose.yml anchors, and Example County to a unit of no state. zap_generated_body_tests in craig-intake builds the body ZAP generates from the served document, reseeds it with the hook’s table, and requires it to pass the public handler’s checks under every state and territory jurisdiction, and the unreseeded body to fail them. tests/security/zap-public-submission-hook.test.mjs runs the hook itself on raw request bytes, in a node:vm context with stubbed java., as the auth hook’s suite does (below), and runs where that suite runs. It holds every body the hook rewrites to byte equality outside the replaced spans, attack payloads included, and every body it leaves to byte equality whole. tests/security/zap-public-submission-hook-check.test.mjs runs the check against a stubbed ExtensionScript: a loaded, enabled, error-free hook passes, and a disabled hook, one with a recorded error, a missing hook or extension, and an exception while checking each exit 5. Locally: node --test tests/security/zap-public-submission-hook.test.mjs tests/security/zap-public-submission-hook-check.test.mjs.

The authenticated scan fails closed (#2759, #2767)

Phase 1c (tests/security/zap-authenticated-api.yaml) exists to probe the post-login surface, so it refuses to run unauthenticated:

  • Host-side preflight. Before it launches ZAP for phase 1c, cargo xtask security mints one token from the host with the hook’s password grant, client (craig-api) and user (admin) against the devstack’s Keycloak. It then GETs one probe route on every service the plan scans, with that token as the bearer, requiring exactly 200 from each. The probes are AUTH_PROBES in xtask/src/cmd/security.rs: a paginated list read one row deep on seven services, and the composition dashboard. A refusal names its cause: the URL it could not reach, the token endpoint’s status, a 200 whose body is not a token response or has no access_token, or the service, URL and status of the first probe that did not answer 200. Phase 1c then fails without launching ZAP. A pass prints how many services answered. The credentials, client and probes are one set of consts, and the same consts reach the hook as its ZAP_AUTH_* env; ZAP_AUTH_PROBES carries the probes as host:port=route entries joined by |.

  • No craig-intake in this plan. It serves no bearer-authenticated route: /public/v1 is anonymous, /partner/v1 takes an API key (and, in integrated mode, a JWS signature), and /signed/v1 a JWS signature alone. So it has no probe, and phase 1c sends it nothing; its public surface is phase 1a’s (craig-intake’s DAST scope (#2781, #2789)).

  • Requestor check. The plan’s requestor job runs after the hook’s script job and before every openapi and activeScan job. It GETs every probe route through the hook and expects 200 from each, which proves the bearer is injected and accepted on each probed host inside ZAP. A mismatch is a ZAP warning. The plan sets failOnWarning: true, so it stops there, and ZAP exits 2, which xtask reports as warnings that include this check. A 401 there reaches the hook’s re-verify first, which stops ZAP with 4 (below).

  • Hook exit 3. zap-auth-hook.js has no unauthenticated fallback and no retry. A failed mint is a transport error, a non-200 answer, a body that is not JSON, no access_token, no positive expires_in, or an unset ZAP_AUTH_CLIENT_ID; an absent or malformed ZAP_AUTH_PROBES stops the scan the same way, before the first mint. Each prints one line, ZAP auth hook: FATAL: <cause>; stopping the scan (exit 3), and exits ZAP with 3, which xtask reports as the hook’s refusal. So no /v1/ request leaves without a bearer.

  • Hook exit 4. A service that rejects every bearer (a broken JWKS fetch, an issuer or audience mismatch, a revoked client) answers each request 401, and ZAP’s activeScan counts no status as a failure. So a 401 to a /v1/ request from a probed host makes the hook re-verify that host, at most once per REVERIFY_MS (60 s). The window counts from the host’s last attempt or pass (an attempt stamps the host when it starts, a pass stamps it again), so the 401s ZAP’s own attack payloads provoke cost at most one probe per host a minute. The hook mints fresh and GETs the host’s probe route with the fresh bearer. A probe 401 means the service rejected the fresh bearer: the hook prints ZAP auth hook: FATAL: <service> rejected a freshly minted bearer: GET <route> answered HTTP 401; stopping the scan (exit 4) and exits ZAP with 4, which xtask reports as that rejection. Any other error in the re-verify, before or after the mint (a probe transport error, a probe answer that is not HTTP, a host that cannot be read), also exits 4, worded could not confirm the bearer on <service>, naming the URI instead when the host cannot be read. Only a failed fresh mint exits 3. Any other status means authentication passed: the services' auth middleware answers a rejected bearer 401 before any handler runs, and the scan’s own writes can leave a probe 403, 404 or 5xx. A 401 inside the window, or from a host with no probe, only makes the next /v1/ request mint again.

Unit tests in xtask/src/cmd/security.rs (auth_scan_tests) run the preflight against a local stub for each refusal and for a pass (the transport refusal against an unbound port). A pass sends each service’s probe exactly once; a service mid-list that answers 401 is named, and no probe after it is sent. They also pin the requestor job’s position and URLs (exactly AUTH_PROBES) in the committed plan, the ZAP_AUTH_PROBES round trip, and, in the hook’s code with its comment lines blanked, its one exit (a failed mint calls it with 3, the re-verify with 4), the re-verify trigger and its REVERIFY_MS. A regression there fails the pre-push battery’s nextest stage before it can reach the pentest job.

tests/security/zap-auth-hook.test.mjs runs the hook itself. It loads zap-auth-hook.js into a node:vm context with stubbed java.* (env, clock, HttpURLConnection, a ConcurrentHashMap) and drives sendingRequest and responseReceived as ZAP does: the exit-3 paths, a probed host’s 401 firing one probe with the fresh bearer, each host’s own window, each probe verdict and its exit code and FATAL line, unprobed hosts, and two scanner threads racing on the claim, of which exactly one probes. It uses node:test and node:assert only, and runs in Docker on the TypeScript SDK suite’s pinned Node image, with no network, wherever the SDK suites run: cargo xtask sdk-test, its pre-push stage and validate’s Docker phase. Locally: node --test tests/security/zap-auth-hook.test.mjs.

Pre-push Integration

Security regression tests (phases 2-4) run automatically in the merge train’s car (xtask security --skip-zap --skip-fuzz; about 1 s), not in the pre-push hook. Catches regressions in auth boundaries, injection handling, and security headers/CORS.

CSP value-assertion tests (#248)

The xtask security probe verifies CSP presence. Value-assertion tests live in each service’s integration suite and pin the exact Content-Security-Policy value to the documented spec in Security:

  • 7 backend services (craig-{rules,cases,placement,exchange,financial,reporting,security}/tests/api/health.rs::healthz_carries_documented_csp) — assert BACKEND_API_CSP

  • craig-intake/tests/api/health.rs — two tests, one per mode (API + standalone embedded UI)

  • craig-web/tests/csp.rs::login_carries_documented_csp — asserts WEB_BFF_CSP

All 11 call helpers in crates/craig-test-lib/src/csp.rs, which holds the single-source-of-truth pub const`s + `assert_*_csp panicking helpers + a self-test verifying strict-mode values stay free of 'unsafe-inline'/'unsafe-eval'. Drift between code, helper constants, or Security § Content-Security-Policy fails CI on the spot — the panic message points at the offending directive and tells the contributor which three places to update.

Alpine CSP-build expression scan (#2254, #2271)

craig-intake and craig-web ship Alpine’s CSP build, whose parser refuses arrow functions, template literals, new, typeof and location / window / document / globalThis reads; a refused expression leaves its component uninitialised with only a console warning. crates/craig-test-lib/src/alpine_csp.rs scans template source for them (every double-quoted x-… / @… / :… attribute, every {% if %} branch, every subdirectory). Its consumers:

  • craig-intake/src/ui.rs::intake_templates_carry_no_expression_the_alpine_csp_build_refuses

  • craig-web/tests/csp.rs::web_templates_carry_no_expression_the_alpine_csp_build_refuses

  • craig-bff/src/csp.rs::bff_templates_carry_no_expression_the_alpine_csp_build_refuses

  • cargo xtask validate-template-safety (#2643), over every plugin template root its walk reads (plugin fragments render inside craig-web): each refused expression is a finding at its directive’s line

Each refuses a root with no .html template; the two host roots also need an x-data. A new crate that renders Alpine templates adds one such call.

Hand-built modal census (#3112)

A modal is a native <dialog> opened with showModal(): the browser then traps keyboard focus inside it, closes it on Escape and makes the page behind it inert, with no script of ours. crates/craig-test-lib/src/modal_census.rs scans template source (every {% if %} branch, every subdirectory) and refuses a dialog role or aria-modal on an element that is not <dialog>, and a <dialog> in a template that never calls showModal(). Its consumers:

  • craig-web/tests/csp.rs::web_templates_hold_no_hand_built_modal, which also pins the one dialog the scan finds

  • craig-portal/tests/csp.rs::portal_templates_hold_no_hand_built_modal

  • craig-bff/src/csp.rs::bff_templates_hold_no_hand_built_modal

It scans by marker: an overlay built from styling alone, with none of those markers, is not seen. The behaviour is pinned in the browser by tests/e2e/specs/rules.spec.ts ("the create dialog traps focus, closes on Escape and returns focus to its opener").

Template inline-construct and plugin-fragment scan (#2558)

cargo xtask validate-template-safety (a blocking validate step) also reads each template’s literal text, askama’s Lit and raw nodes, never comments (xtask/src/cmd/validate_template_safety.rs::text_hits):

  • Every root (the four hosts and every discovered plugins/*/templates/): an inline <script> with no src=, a <style> element, a style= attribute, an on…= handler, an htmx eval attribute (hx-on…, hx-vars, a js: / javascript: hx-vals / hx-headers value, an hx-trigger [filter]; data- spelled too) and a javascript: URL in href / src / action / formaction / xlink:href. Every host serves the same strict CSP (no 'unsafe-inline', no 'unsafe-eval'), so each is a construct the browser would refuse.

  • Plugin fragment roots only (a default run; a --roots override names directories, not crates): a <form> tag, a mutating hx-post / -put / -patch / -delete (ADR-033: action forms are host chrome) and a t filter.

It is a text heuristic over each literal run. Not read: an attribute name built from an expression (on{{ e }}=; {{ attrs|safe }} is already refused as | safe), and a javascript: URL hidden behind an entity or a tab.

Dispositions for the other host template gates:

  • CSRF (templates_csrf.rs): met in the stronger form. A plugin fragment may carry no form and no mutating hx-*, so nothing in a plugin template can issue the POST verify_csrf guards; a token-presence scan there would be vacuous.

  • i18n (i18n_coverage.rs): not extended. No plugin carries a | t or a catalog today, and ADR-033 defers plugin i18n to the manifest [i18n] seam; a plugin that defined its own filters::t would compile, so the scan refuses a t filter in a plugin fragment as a tripwire until that seam lands.

  • Alpine CSP build: no alpine_csp scan reaches plugin templates yet, although fragments render under craig-web’s Alpine CSP build (#2643).

Each plugin also pins its rendered states: plugins/example/src/lib.rs::every_state_renders_csp_clean_and_form_free and plugins/ssa-screening/src/lib.rs::fragment_is_csp_clean_and_form_free.

Results

  • HTML reports: test-results/security/zap-*.html

  • JSON reports: test-results/security/ffuf-*.json

  • Summary: test-results/security/ffuf-summary.txt

CI

  • pentest job in scan stage (allow_failure: true) — runs ZAP (phases 1a/1b/1c) + ffuf (phase 5) against a devstack its job brings up with xtask dev start (plan ci-dev-loop D3).

  • Triggers: scheduled runs ($CI_PIPELINE_SOURCE == "schedule"), and by hand on a main pipeline (when: manual, plan ci-compile-once decision 1: scheduled, not per merge; the schedule is weekly, #2651). MR pipelines deliberately do not trigger pentest — DAST stays out of per-MR cycle time while velocity is the gate. This is temporary; flip to add MR triggers once the velocity constraint lifts.

  • Schedule: configure via CI/CD > Schedules with a cron that fits your cadence (e.g. 0 7 * * * for daily 07:00 UTC).

  • Image source: each promoted CRAIG service in docker-compose.yml carries an image: ${CI_REGISTRY_IMAGE:-craig}/<service>:${CRAIG_IMAGE_TAG:-local} line alongside its build: block. CI sets the env vars to pull pre-built images; local dev uses the defaults so build behavior is unchanged.

  • Artifacts: test-results/security/ (HTML + JSON) retained for 30 days.

Performance Testing

Profiles (4)

  • smoke — 1 VU, 21 shared iterations (611 requests in the 2026-10-09 battery), about 7 s with the fence below. Pre-push gate runs this on every push. Quiescence fence (#1315): because the smoke asserts p95 thresholds and runs immediately after the Playwright e2e stage in the battery, cargo xtask perf first establishes quiescence for smoke-profile runs — (1) a bounded drain fence polling every stateful DB whose own migrations create event_outbox or event_inbox (derived from the registry’s migration dirs, #2239; a DB without the tables could never read as drained) until unpublished event_outbox + pending event_inbox rows reach zero, a polled DB that cannot be read holding the fence (90 s cap; a timeout WARNS and proceeds — the fence protects the measurement, it is not a gate), (2) ONE cluster-wide CHECKPOINT so the e2e write burst flushes inside the fence instead of under the smoke’s own writes (the #1319 checkpoint-fsync storm class produced 60× write-path transients pre-fence), (3) a 2 s settle. Root cause recorded on #1319; the fence is the accepted-devstack-behavior guard. Host pressure (#1803): the smoke’s p95 budgets are absolute, so they hold only on a host that gives the stack its CPUs. After k6, every smoke run prints a host-pressure block: PSI cpu some avg10 / avg60 and the 1-min load per CPU before, during (one sample a second) and after the run — printed, never judged, since both are exponential 10 s / 60 s histories that mostly describe the seconds before a run of a few seconds (the calibration’s quiet windows were 4.3 s) — and the judged window line, the PSI some total= stall counter’s delta over the run’s wall time: the share of the run in which a runnable task waited for a CPU (xtask/src/perf_verdict.rs). Outcomes: k6 passed → pass, on any host (budgets that held under pressure are not a failure); k6 failed with only http_req_duration budgets crossed (read from the run’s --summary-export, tests/k6/test-results/k6-summary.json, removed before each run) on a window at or over the line → HOST_SATURATED, which lists the window’s top CPU consumers (ranked by CPU used in the window, with PPID: an orphaned busy loop shows PPID 1) and the remedy, then exits 5; anything else — a functional crossing (http_req_failed, missing_seed_entity), a script error, an unreadable summary, a quiet host, or an unmeasured one (no PSI, a counter that went backwards) — stays the plain failure (exit 1). Exit 5 still blocks the push; the hook’s generic ERROR: perf smoke regression (exit 5) line follows the block. Calibration (2026-10-13, kernel 7.2.9, 32 CPUs, host otherwise idle): three quiet smokes stalled 0.6% of their window (about 29 ms of 4.3 s); the smoke under 32 pinned while :; do :; done loops stalled 50.1% (9.3 s of 18.5 s) and still passed. The line is half the pinned reading, rounded down to a multiple of 5%: 25.0%. No threshold moves; the standing baseline is untouched. In CI the stack runs as sibling containers on the VM’s daemon, so the consumer list there covers only the job container’s processes. --save-baseline moves the same export to test-results/k6/<date>.json and errors when a passing run exported nothing.

  • load — 17 minutes at a stated arrival rate (What the list limits are measured against (#3170)): 200 iterations a second in each read scenario, ramped over five minutes and held for ten. Codified SLO thresholds in tests/k6/helpers/thresholds.js (READ p95 < 50ms, LIST p95 < 100ms, WRITE p95 < 200ms, error < 1%). CI runs this on schedules and by hand on main.

  • stress — 8 minutes at twice the load profile’s rate, with each limit doubled and a 5% error budget. Manual / scheduled invocation only.

  • soak — 30 minutes at a fifth of the load profile’s rate, for memory-leak / connection-pool drift detection. Manual invocation only.

What the list limits are measured against (#3170)

A list’s cost depends on how many rows it lists, so the load, stress and soak profiles, which hold each list endpoint to a p95 limit, run against a stack of a stated size. Two things keep it there.

The stack is seeded with CRAIG_FAMILIES=45000 (perf_data::PERF_FAMILIES in xtask; CI’s perf-load and perf-stress jobs set it through .perf-stack, and a pipeline test holds the two equal). The default seed of 12 families holds seven cases, at which every list passes whatever it does. The larger seed is sized against the larger of the two shipped jurisdictions:

Table Rows seeded Sized against

placements

20,161, of which 16,775 active

Texas had 17,520 children in foster care on 30 September 2025 (AFCARS) and 16,866 by its own count (DFPS Data Book, FY2025). Georgia has about 11,000.

foster_homes

9,179

Texas has 6,911 licensed foster homes and Georgia 4,495 (2025, from secondary sources citing The Imprint’s national count).

cases

27,713, from 45,000 reports

Georgia screened in 55,447 reports in FFY2024 and Texas 178,221 (NCANDS, Child Maltreatment 2024). The seed is on Georgia’s order and low for Texas; it ties cases to families, so this cannot be raised alone.

exchange_partners, data_sharing_agreements, rule_sets

15, 23 and 147

Small at any family count, as they are for a jurisdiction: a state exchanges with tens of systems.

cargo xtask perf --profile load (and stress, soak) prints the cases, foster_homes and placements row counts and refuses a stack with any of them under its floor (25,000, 8,000 and 18,000, about nine tenths of the seed), naming the command that seeds one. The smoke is exempt: it runs a few iterations on the default seed.

The load is offered at a stated rate. Each of the four read scenarios (cases_read, rules_read, placement_read, exchange_read) starts a fixed number of iterations a second whatever the response time: k6’s arrival-rate executors, not a loop of virtual users.

Profile Each read scenario Read requests a second, per service Failure budget

load

200 iterations a second, ramped over 5 minutes and held for 10

about 400

1%

stress

400 a second, ramped over 2 minutes and held for 5

about 800

5%

soak

40 a second for 30 minutes

about 80

1%

The devstack limits one client address to 100,000 requests a minute per service (1,667 a second), and k6 is one address, so every profile sits under half of that. An iteration k6 cannot start, because every virtual user is still waiting on the stack, is load that was never offered: dropped_iterations counts against the same budget as a failed request.

A run adds rows at a fixed, slow rate. The read scenarios create nothing. The writes run in their own scenarios: one referral chain a second (cases_write: report, decision, convert), one home a second (placement_create) and one partner every ten seconds (exchange_create), so their limits are still measured. A load run adds about 1,000 homes and 100 partners.

Before #3170 the profiles looped 50 or 100 virtual users per scenario with no think time, and each list iteration created a home and a partner. A run grew both tables to about 342,000 rows, faster the faster the service answered, and measured the lists against that. With the tables at their seeded size the same loops sent 26,000 requests a second and the rate limit refused four in five.

Tokens renew per VU (#2760)

The realm’s access tokens live 1800 s and the soak runs 30 minutes. A token handed through setup() data is never renewed, so no k6 script does that:

  • Every VU function reads its bearer from getToken(user, password) (tests/k6/helpers/auth.js) on each iteration.

  • Each VU holds its own cache (tests/k6/helpers/token_cache.js). The cache records each token’s expiry from its expires_in, timed from before the mint, and mints again from 60 s before that expiry (TOKEN_RENEW_MARGIN_MS). It refuses, rather than caches, a token response without a positive expires_in or an access_token.

  • A mint that still fails after the #904 retries, or a refused response, aborts the whole run through exec.test.abort (k6 exits non-zero). So an auth failure never passes as a run with no endpoint samples.

  • A setup() may call getToken for its own requests (the benches create data there), but it returns no token.

  • A unit pin in xtask/src/cmd/perf.rs (k6_token_pin) scans every script outside helpers/ for a token carried through setup data, a token-named parameter, or a bearer not read from getToken.

The smoke runs a second scenario, auth_selftest: 1 VU, 1 iteration, no HTTP request. It drives the cache factory getToken uses (createVuTokenCache) with a fake clock and a stub minter (expires_in: 1800), and checks four things:

  • the token is reused until 60 s before its expiry;

  • a new mint happens at exactly that point and after it;

  • users are cached apart;

  • a response without expires_in is refused.

Its threshold, checks{scenario:auth_selftest}: rate==1, runs on every battery. A crossing is a functional failure (exit 1), never HOST_SATURATED.

Running locally

  • Smoke (~7 s): cargo xtask perf --profile smoke

  • Load (17 min): cargo xtask perf --profile load --save-baseline (writes JSON to test-results/k6/). It needs a stack seeded at the perf size (CRAIG_FAMILIES=45000 cargo xtask dev reseed, about five minutes) and refuses a smaller one (What the list limits are measured against (#3170)).

  • Single service: cargo xtask perf --service craig-rules

  • Named scenario: cargo xtask perf --scenario person-suggestions-bench

  • k6 image (#2355): every run, local and CI, uses grafana/k6:2.3.0, pinned by the K6_IMAGE constant in xtask/src/cmd/perf.rs, never :latest, so the smoke’s verdict depends on the commit, not on the day it ran. A bump is that one line, landed on its own with a passing smoke; a unit test rejects a moving tag.

CI (#258)

  • perf-load job in scan stage (allow_failure: true initially) — runs cargo xtask perf --profile load --save-baseline against a stack on the release images of the job’s own commit (xtask dev start --release --bake, #3157). k6 exits non-zero on threshold breach, so failed thresholds = failed job.

  • Triggers: the schedule, and by hand on a main pipeline. No MR pipeline runs it: half an hour of load does not belong on every push. To measure a branch before it merges, start a measurement pipeline ([measurement-pipelines], #3185).

  • perf-stress job — same wiring with --profile stress, on the same triggers.

  • Artifacts: test-results/k6/ JSON retained for 30 days for trend tracking.

What runs automatically

Only the smoke profile runs automatically: the merge train’s car runs xtask perf --profile smoke (~7 s). The pre-push hook runs no perf stage. Load/stress/soak stay manual because they need minutes of runtime.

Runner Tags

Every CI job runs on one runner, dhs-aws-autoscaler-docker-4xlarge, through the pipeline default tags: [$CI_RUNNER_TAG] (#2935); no GitLab shared runners, and no job or template names another tag (every_job_runs_on_the_4xlarge in pipeline_tests.rs). It is a docker executor, so every job runs in the image it names (craig-ci for the Rust jobs), and its 1 TB disk per job VM holds a full test build, which the shared .2xlarge did not (ld: final link failed: No space left on device; see Known Issues & Lessons Learned).

There is no fallback runner (ADR-086 § D3, amended 2026-11-07): cma-runner-craig (#1645), the instance executor the stack jobs once fell back to, ignores image: and cannot run craig-ci. A 4xlarge outage stops the train. A future fallback must be a docker-executor runner able to pull craig-ci.

Diagnostics: the battery’s slow-statement summary (#2360)

Every devstack battery run, whole or scoped, prints a block after its nextest step, green or red:

=== slow statements per service database (#2360; report-only) ===
  craig_reporting: 141 statement(s), 223 ms in total
    [total]        57 ms total      16.7 ms max       23 calls  SELECT p.dictionary_rule_set_id, …
    [  max]         4 ms total       3.6 ms max        4 calls  SELECT COUNT(*) FROM data_quality_issues …

How to read it:

  • Per database: how many distinct statements ran since the battery’s preamble reset the counters, and their summed execution time. A database far above the others is where the run’s database time went.

  • [total] rows: the three statements with the most summed time. Many calls of a cheap statement land here.

  • [max] rows: up to three more, the longest single executions not already listed. One slow execution, such as a statement that waited on a lock, lands here: that is the row to look at when another suite starved.

  • Statement text is pg_stat_statements’ own: constants replaced by `$n, cut to 100 characters on one line. Utility statements are not tracked.

It is report-only and cannot fail a run. If the server lacks the library or a read fails, the block is one unavailable line. The counters come from the main devstack Postgres, which preloads pg_stat_statements (docker-compose.yml, devstack and CI only); the scratch-database instance (postgres-test) is not covered. Times are execution time as Postgres measures it, lock waits included, not time in the client.

Diagnostics: inbox latency probe (#2699)

cargo xtask diag inbox-latency [--envelopes N] [--phase a|b|both] [--sample-ms MS] [--prefill N] [--keep] [--sweep-stale] [--path single|batched] [--batch-max K] reproduces inbox commit latency on demand. It checks that the devstack’s postgres and rabbitmq are healthy, then runs craig-security’s inbox_latency_probe example (services/craig-security/examples/inbox_latency_probe/) in the dev profile on the project network (the verb re-executes in craig-tools), the HEAD SHA (plus --dirty when git status --porcelain lists any change outside test-results/; the header then reads <sha> (with uncommitted changes)) and the report directory.

Database attempts only. The probe calls craig_mq::handle_idempotently directly, so broker delivery, consumer.next and the ack are outside it; its broker connection only backs the dead-letter publisher the call takes. The production histograms craig_mq_consumer_receive_seconds and craig_mq_consumer_settle_seconds (shared-crates § craig-mq, "Delivery timings") cover those legs in an instrumented battery.

Subscriber paths (#2765). --path single|batched replaces the direct attempts with a published burst through craig-security’s real audit subscription, craig_security::subscribe_audit, on a scratch vhost: single at K = 1 (subscribe_idempotent), batched at K = --batch-max (1 to 16, default 16; subscribe_idempotent_batched from K = 2). --batch-max is refused without --path batched, by xtask before any build and by the probe. Per phase the subscription subscribes once and stops, which declares its queue; once a passive declare shows the queue without a consumer, the burst of --envelopes is published, every confirm awaited, and only then does the subscription start, so broker delivery and the attempts are inside the measurement. A poller on its own connection reads which audit rows are visible every 10 ms. Drain is an audit/claim visibility drain: it runs from the subscribe call to the last row’s visibility (each claim commits with its row), so the last acknowledgements may land after it; throughput is envelopes over the drain. Audit lag is the start of the first poll that saw an envelope’s row minus the return of its publish confirm, so it includes the backlog’s wait. The phase also reads back the claims (processed count, highest error_count) and, through the probe’s own OTel → Prometheus bridge, the phase delta of craig-mq’s batched-inbox series: transactions by mode, batches by outcome (arbitrated counts arbitrations), occupancy (craig_mq_inbox_batch_envelopes), flushes and deferrals by reason. The batched path’s commit p50/p99 are the bucket bounds of craig_mq_inbox_batch_seconds{stage="commit"}; the single path’s are its exact stage timings. In the report’s latency table the first row is the lag instead of the probe-side wall time, and a "Subscriber drain" table carries the rest. The sampler’s PID correlation does not hold on these paths.

What it measures. The probe drives synthetic audit envelopes serially, one attempt in flight, through the real attempt machine (craig_mq::handle_idempotently over craig_security::handle_inbound_event), 2000 per phase by default. Phase A is the baseline. Phase B starts a background task that writes WAL in a loop in a second scratch database, waits (at most 30 s) until its first insert has committed, and only then delivers; the report gives the load start, ready, delivery start and end and load stop instants, the load iterations completed during delivery, and whether the delivery window lay inside the load window. For each envelope it records the wall time and the stage timings of craig-mq’s inbox attempt timings debug event. Throughout, it samples pg_stat_activity every --sample-ms (default 20 ms), keyed backend_type:state:wait_event_type:wait_event; Client:ClientRead under idle in transaction is the client-gap signal. At each phase start it reads the probe pool’s backend PIDs (application_name craig-probe-inbox); since one attempt is in flight at a time, a sampler row of those PIDs at time t belongs to the envelope in flight at t. It reads /proc/pressure/{io,cpu,memory} once a second. Per phase it reports the pg_stat_io WAL rows (object = 'wal', per backend type), pg_stat_wal and pg_stat_checkpointer deltas, each taken after a quiescence poll (two equal reads 1 s apart, bounded at 15 s; the report says if the bound hit). Every snapshot carries each view’s stats_reset: a delta whose reset epoch moved, or that would be negative, reads invalid (statistics reset during the phase) with no numbers.

Durable instance. It runs on the MAIN devstack Postgres, where synchronous_commit and fsync are on. The test plane (postgres-test) runs on tmpfs with fsync off and cannot show commit latency. The probe creates craig_probe_inbox_<uuid> and craig_probe_load_<uuid> with track_wal_io_timing and track_io_timing on, applies craig-security’s migrations to the first, and drops both at the end, also on error (--keep keeps them). At start it lists any other craig_probe_% database (another run’s, or one a killed run leaked) with its connected-backend count and touches none. --sweep-stale drops those with no connected backend, with a plain DROP DATABASE (no FORCE); one that refuses because someone connected meanwhile is reported and skipped. A run that has created its databases but not yet connected also looks idle, so do not sweep while another probe is starting.

Not in the battery. nextest runs only the example’s unit tests, never its main. Do not run the probe during a battery: creating and dropping databases checkpoints the shared instance.

Report. test-results/diag/inbox-latency-<YYYYMMDDTHHMMSSZ>.md and .json. Per phase: envelopes/s, p50/p90/p99/max of the wall time and of each stage, outcomes, the pool PIDs, the delivery (and load) window, the wait-event histogram, the statistics deltas and the host load before and after. Both files carry a per-second series, so a checkpoint inside phase B shows as its own window. Its row k is the interval [k s, (k+1) s) from the phase start for every signal: completions, stage percentiles and wait samples by their offsets, and pressure as the cumulative PSI counter read at or just after the interval’s end minus the one read at or just after its start. The last interval, cut at the end of the observation window, is marked partial; a closing PSI read bounds it. The header names the instance and its commit/WAL settings, the build profile and the commit.

Caveats, stated in the report. A reproduction shows susceptibility, not that an incident had this cause. It times database attempts only (above). The envelopes run serially through one consumer, so the probe cannot show pool contention. The probe’s audit_log holds only the --prefill rows (the live table’s size is reported beside it). The statistics views are cluster-wide, so the deltas include every devstack service’s writes during the phase.

Diagnostics: durable Postgres sampler (#2699)

cargo xtask diag pg-sample [--interval-ms MS] [--duration-secs SECS] [--out PATH] [--io-mount PATH] [--io-every TICKS] samples the durable devstack Postgres (postgres, not the tmpfs postgres-test) and the host’s I/O by source while a battery runs beside it. It is never part of the battery, but unlike diag inbox-latency it is built to run during one: it creates nothing, writes nothing on the server and never takes the devstack lock.

Connection. It refuses to start unless the devstack’s postgres is healthy, the port resolves (the shared Postgres at postgres:5432 on the project network, or CRAIG_TEST__POSTGRES_ADDR; the verb re-executes in craig-tools) and the server is PostgreSQL 18 or later. It opens one session to the postgres database (never a craig_<svc> one) as the devstack admin role, with application_name craig-pg-sample and default_transaction_read_only=on. Each statement is its own autocommit transaction, and its own backend is left out of the reads. A failed read writes an error line (the stage, the class and any SQLSTATE, never a value, and the host io when due) and drops the session. The next tick reopens it, backing off from one tick up to 5 s, and a reopened session writes a fresh header line. A devstack refresh that restarts Postgres mid-battery therefore leaves a gap in the Postgres reads (not in the host I/O) and the sampler keeps running.

What a tick reads. Every --interval-ms (default 250, minimum 50). A slow tick delays the next one, and each tick’s reads are bounded at 5 s.

  • wal_insert_lsn and wal_flush_lsn: pg_current_wal_insert_lsn() and pg_current_wal_flush_lsn() as byte offsets. They give WAL volume and flush backlog in real time, independent of statistics lag and timing settings.

  • activity: every non-idle client backend (pid, datname, application_name, state, the wait event, the transaction and statement ages from clock_timestamp(), the elided query). Also the checkpointer, walwriter, background writer and autovacuum workers: their wait events (CheckpointWriteDelay, DataFileSync, …) are the only real-time sign that a checkpoint is running.

  • wal: pg_stat_wal, plus the pg_stat_io WAL rows (per backend type and context) that have written or fsynced: writes, bytes, write_time, fsyncs and fsync_time. Each view’s stats_reset comes with it.

  • checkpointer: pg_stat_checkpointer (num_timed, num_requested, num_done, write and sync time, buffers).

  • databases: pg_stat_database per database (<shared> for the shared catalogs): commits, tuples inserted, updated and deleted, and temp_bytes.

  • host_psi: /proc/pressure/io and /proc/pressure/cpu, both some and full (the 10 s average and the cumulative µs); null off Linux.

  • io: the host’s I/O by source (below), read after the rest at most once per --io-every ticks' worth of time, less half a tick (1 to 240; at the default 4 a regular tick reads every 4th, once a second at 250 ms). The cadence is time-based and counts error lines too: the first tick-or-error line reads, then the first line once io_every × interval_ms less half a tick has passed since the last read (the half tick absorbs scheduling jitter). So a regular tick reads every Nth, and while Postgres is unreachable each backoff error line reads when due, so an outage keeps its I/O. The lines between read nothing and carry null, as does every line off Linux. Its own read_ms times only these file reads; the tick’s read_ms keeps timing the Postgres and PSI reads.

The cumulative views lag: a backend publishes its counters about once a second while busy, and up to ~10 s after it goes idle. The LSNs, wait events and I/O counters do not lag.

Host I/O by source (format 2). The sampler resolves what to read once, at start, and records it in every header, with io_every:

  • io_layout (cgroup, containers, note): cgroup is v2 when /sys/fs/cgroup/cgroup.controllers lists io, else unavailable. containers is systemd (system.slice/docker-<64 hex>.scope), cgroupfs (docker/<64 hex>) or none (rootless Docker, podman, a custom cgroup parent or a cgroup namespace); only those two directories are probed. note says what resolution could not do or had to approximate, or is null.

  • io_devices (role, name, dev): the mount exactly at --io-mount (default /data; the last such mountinfo entry), else the longest mount holding the workspace root (the note says so). Its source is canonicalised (/dev/mapper/data → dm-1), never read from mountinfo’s MAJ:MIN, which btrfs reports as 0:NN. That device is data; its slaves/ are walked to the leaves, each a partition followed by its disk, or itself a disk. A bare partition is listed as both data and partition. When the device does not resolve, every /sys/block entry with a device link is a disk, and the note says so. Beside a resolved stack, each sibling: every other partition of each disk (an entry of its /sys/block/<disk>/ directory with a partition file, nvme0n1p1), then every other /sys/block device whose slaves/ chain ends on one of them (dm-0 on nvme0n1p2), each in name order. A device stacked on the data device’s own partition is no sibling; the fallback lists none.

  • io_services (id, service): one docker compose ps --all at start, each id cut to 12 hex characters. It tells the durable postgres from postgres-test and other projects' Postgres containers. Docker is never called per tick.

Each tick’s io then holds:

  • devices: each resolved device’s /proc/diskstats row (14, 18 or 20 columns), the siblings' included: reads, sectors read and written (512 B), writes, read and write ms, in flight, io ms, weighted ms, and discards, flushes and flush ms where present.

  • totals: the io.stat counters of system.slice, user.slice and init.scope (and docker/ under cgroupfs).

  • sources: every direct child of system.slice (and of docker/ under cgroupfs) whose data counters are not all zero or that carries disk (so a unit that wrote only to another partition is kept for its disk), each in full on every io. A container is kind: container with its id12 and a label from at most 4 KiB of its first process’s cmdline (an init wrapper’s next process is read instead). A first field holding whitespace is a process title: its first token, a trailing : dropped, or ? when that token holds a / (a path with a space never yields a directory). Any other first field is a path, and its basename is the program. Either is kept only as 1 to 32 of [A-Za-z0-9._+-], else ?. So a title’s arguments never reach the file. Any other child is kind: unit, its id the unit name with a template instance dropped (systemd-cryptsetup@luks….service → systemd-cryptsetup.service). Units whose names are systemd-escaped paths are one source per type, .mount, .automount, .swap and .device, so no path or user name reaches the file. BuildKit’s per-step cgroups (system.slice:docker:<random id>) are one source, docker build steps. The cgroups sharing an id fold into one source. A member that goes away, or is recreated in place (any counter falls), keeps its last counters in the source, and a member whose io.stat does not read keeps its last counters too, so a source’s counters never fall.

  • Each total and source carries data (rbytes, wbytes, rios, wios, dbytes): the io.stat line of the data device, or of its disk for a bare partition, which io.stat never lists. A total also carries disk, the first disk device’s own io.stat line, whenever a disk resolved. It counts every partition of the disk, the data device’s included. A source carries disk only when its written bytes exceed its data line’s (it wrote to another partition; reads do not count) and omits it otherwise. The two lines are never summed, and no other line is kept: stacked devices repeat the same bytes. disk folds with data, so a member that goes away or restarts in place keeps its last disk line too.

A scope that goes away or a file that does not read is skipped; reading I/O never fails a tick. On this host (about 80 sources, 6 of them carrying disk) an io is about 13 KB, so at the defaults (250 ms, io every 4th tick) a tick averages about 8.0 KB, against 7.6 KB without the sibling rows and the disk lines at the same moment: about 115 MB an hour, written to the page cache.

user.slice is read only as a total: the sampler never lists, labels or attributes the cgroups or processes of a user session.

Query elision. A query is elided on its full text and then cut to 120 characters. '…', E'…' and ''-escaped strings become '?', a dollar-quoted string becomes $?$, and a number not attached to $ or an identifier becomes ?. A quote the server cut off (track_activity_query_size) is elided to the end of the text. Comments (-- to the end of the line, /* … */ with nesting) are dropped whole, so a quote inside one cannot open a string. Identifiers, $n placeholders and keywords stay. Parameter values are never read.

Output. test-results/diag/pg-sample-<YYYYMMDDTHHMMSSZ>.jsonl, or --out (an existing file is refused). Each line is one JSON object with a record field: header, tick or error. Timestamps are RFC 3339 UTC to the millisecond. A header carries format_version (2), the HEAD SHA and a dirty flag, the interval, server_version_num, the commit, WAL and checkpoint settings, track_wal_io_timing among them, and io_every, io_layout, io_devices and io_services. The sibling rows and the disk lines are additions within format 2: a format-2 file written before them has neither, and reports as such. Only that direction is guaranteed: an older report binary refuses a file carrying "role":"sibling" loudly, as a line that does not decode, and never misreports it. Each line is written and flushed to the page cache, so it survives a SIGKILL. It is never fsynced: an fsync every tick would disturb the WAL fsyncs being measured. The sampler stops and exits 0 at SIGINT or SIGTERM, after --duration-secs, or after 6 h.

Orchestration. Start the sampler in the background and wait for its header line (the file’s first line; it also prints header written) before git push. By then cargo xtask has finished building, so its build cannot race the battery’s. After the battery, stop it with SIGINT or SIGTERM and run the report:

cargo xtask diag pg-sample --out test-results/diag/pg-sample-run.jsonl &
# once the file's first line (the header) is there:
git push
kill -TERM %1   # after the battery
cargo xtask diag pg-sample-report test-results/diag/pg-sample-run.jsonl

The battery rebuilds target/debug/xtask while the sampler runs from it. Linux allows that; on Windows, run the sampler from a copy of the binary.

The report. cargo xtask diag pg-sample-report <file> [--junit <path>] prints the report and writes the same text beside the file, its .jsonl replaced by .report.txt. --junit defaults to the battery’s nextest report (test-results/integration/integration/results.xml); its timestamps carry the battery host’s offset and are normalised to UTC. It reads format_version 1 and 2 and refuses any other; a format-1 file reports as before and says io sources not recorded (format_version 1), and a format-2 file without disk lines says no other-partition data recorded in place of the second I/O table.

  • Stall candidates. A tick is a candidate when any threshold fires: at least 3 client backends in a WAL wait (IO:WalSync, IO:WalWrite, IO:WalInitSync, LWLock:WALWrite, LWLock:WALInsert), an active COMMIT running 250 ms or more, at least 50 ms of host io PSI some stall per interval (a step across a longer gap is scaled down to one interval first), or at least 4 MiB of unflushed WAL. No threshold needs track_wal_io_timing. The constants are in xtask/src/cmd/diag/pg_report.rs. Candidate spans within 1 s of each other merge into one window.

  • Per window. The database / application pairs whose client backends sat in WAL waits (samples and events) and the background processes' wait events. Then the checkpoint counters and per-database commit and tuple deltas over an asymmetric stats window, 5 s before to 12 s after, because the cumulative counters lag (the report says so). Last, the JUnit testcases whose run overlaps the window, grouped by testsuite with counts, and the ten longest.

  • WAL flush per window, from what every tick already carries (no extra read). The longest WAL-fsync run: the most consecutive samples in which the same pid is in IO:WalSync (a sample more than 1.5 intervals after the last ends the run). Its bounds come from the samples' own timestamps, since ticks can run late: the flush lasted at least from the run’s first sample to its last, and at most from the sample before it to the sample after it. The upper bound is open (⇐ - ms) when the run meets the span’s first or last tick or a sampling gap. The line names that backend’s application_name and pid, the peak number of backends of any type in LWLock:WALWrite during the run, and the fsyncs published between the run’s first and last samples, in all and tick by tick; pg_stat_io lags by up to about a second, so for a sub-second run that count is weak corroboration. Then the fsyncs over the window, from the last tick at or before its start: Δfsyncs and Δfsync_time of pg_stat_io’s WAL rows, every backend type summed, the mean ms per fsync (-` with track_wal_io_timing off), and the ticks in which no fsync completed while at least 3 backends of any type waited on LWLock:WALWrite. A step across a reset (a counter that fell, a stats_reset that moved) is left out and counted; a tick with no WAL row (the view drops all-zero rows, as right after a reset) is the zero the next tick’s counters count from. On the !2087 battery’s sample file, the report’s window 14 reads 3 samples (>= 500 ms, ⇐ 1000 ms), pid 197 (craig-security-events), peak 12 LWLock:WALWrite waiters and fsyncs +990, fsync_time +3120.62 ms, mean 3.15 ms per fsync.

  • Host I/O per window, between the io-carrying lines (ticks and error lines) that bracket it: the last at or before its start to the first at or after its end, so a window shorter than the cadence still reads the I/O around it (the counters are real-time; the report names the two instants). A bracket longer than the window plus two io cadences spans a sampling gap, and the window says the io reads bracketing this window span a sampling gap of N s; rates are averaged over it. One ranking table: the top ten sources by Δ`data.wbytes`, with MB/s, Δwios and the share of the data device’s Δ(sectors written × 512). Then the totals, unranked, and a residual line: the data device’s Δ less the totals', so what was not charged to the recorded totals (the root cgroup: journal and unattributed writeback; any other top-level cgroup). Then a second table, Top sources by writes to the disk’s other partitions: the top ten sources by Δ`disk.wbytes` − Δ`data.wbytes`, with MB/s, Δ`disk.wios` − Δ`data.wios` and the share of the disk’s Δ(sectors written × 512) less the data device’s. Each line is grown on its own over the span, with the restart rule above, and the difference taken after. At a read without disk the data line stands in for it (the sampler records disk only beyond data), so a source that never wrote another partition counts 0. Both lines only grow, but the disk line can trail the data line at a read (a write submitted to dm-crypt and not yet below it), so the difference can shrink without a restart: a negative one is that transient lag and counts 0, and the next span counts what the difference regains. The totals' other-partition writes follow, unranked, with their own residual: the disk’s Δ less the data device’s, less the totals' other-partition Δ. Then each device’s write MB/s, busy % (Δio_ms over the wall), aqu-sz (Δweighted_ms over the wall), w_await (Δwrite_ms per write) and, for the disk, its flushes with their rate (Δflushes over the wall, per second). The sibling rows are listed like the rest, each on its own line.

  • Battery-wide. The checkpoint cadence (timed and requested starts and completions, each at the tick that first showed it), the top databases by commits and by tuples written, and a banner when track_wal_io_timing was off. The postgres database’s commits include the sampler’s own read-only statements. Then the same WAL-flush lines over the whole file, and their caveats, once: a run of one pid can also be back-to-back short fsyncs by one busy backend, so corroborate it with the fsyncs published between its first and last samples and the ticks with none completed (a stalled flush completes ~0 fsyncs during its run, but for a sub-second run the published count is weak, as pg_stat_io lags by up to about a second); and pg_stat_io lags, so a tick’s fsync step is lumpy and a tick with none completed can be that lag. Then the same two I/O ranking tables over the whole file (the second with its totals and residual), and the ten busiest 10 s intervals (fixed from the first io read), each with its top source by Δ`data.wbytes`. Every I/O delta runs between io-carrying lines only, error lines included; an interval runs from the last one before it to its last one, and ranks by the disk’s busy % over that bracket (Δio_ms over its wall; the data device’s without a disk row). An interval whose bracket is longer than the larger of 20 s (twice its width) and its width plus two io cadences spans a sampling gap and is skipped, counted in one line: N intervals skipped: their io reads bracket a sampling gap.

  • I/O series. A source is keyed by its kind and id. A restarted container keeps its id, but its scope comes back with zeroed counters; a recreated one gets a new id, a new source. This sampler folds a restart in (above), so its sources never fall. In a file from an earlier sampler, which recorded raw counters, a counter that decreases under the same key is a restart: the new value counts from zero and the row says restarted N×. A source first seen after the file’s first tick counts from zero, one present there is the baseline, and one that vanishes keeps its growth.

  • I/O caveats, printed once. io.stat counts block I/O at submission: a buffered write is charged to the cgroup that dirtied the page, but only at writeback: after dirty_expire_centisecs plus up to one dirty_writeback_centisecs flusher interval, sooner past dirty_background_bytes, at once on fsync/sync. So a window’s ranking names what loaded the device during the window, not who called write() then. Container log writes are charged to dockerd and image unpacks to containerd. Stacked devices are never added together. dm-crypt’s busy % includes kcryptd queueing. On NVMe, 100 % busy is not saturation: read aqu-sz and w_await. The sampler’s own output is charged to the sampler’s cgroup when it lands on the counted device. A source whose member goes away or restarts in place keeps that member’s last counters, but what the member wrote after its last read is not counted; and a member that restarts and outgrows its old counters in every field before the next read reads as continuing, so the source undercounts it. A report on an older file that recorded build steps one by one folds them into the same row, each grown on its own series. A disk line counts every partition, the data device’s included, so a span’s other-partition writes are the disk line’s growth less the data line’s: a source that wrote only the data device has none. The difference can shrink without a restart, while the disk line trails the data line: a span where it shrinks counts none, and the next counts what it regains.

  • Robustness. A counter that decreases, or whose stats_reset moved, breaks its series: that step counts as a break and is never subtracted. Headers, ticks and error lines may interleave. A truncated last line (a killed sampler) is ignored; any other line that does not decode refuses. A JUnit report with no testcase inside the sample’s span is flagged as stale or another run’s.

Tests. The elision, PSI parsing, header, reconnect backoff and report logic have unit tests, as do the I/O parsers (io.stat, diskstats, the label rule, with property tests), device resolution over a fixture /sys tree (siblings included: a disk of three partitions, /data on one and a dm device on another), a tick over a fixture cgroup tree under each Docker cgroup driver, the disk lines (on every total, on a source only beyond data, folded across a restart in place), the time-based I/O cadence (jittered ticks, then backoff error lines), the I/O series and both I/O report sections, with io on every tick, on every 4th, on error lines through an outage, and across sampling gaps, the other-partition table with its residual (a difference that shrinks counting none), the disk’s flush rate, a format-2 file without disk lines, a user.slice session that wrote but records no source and names nothing, and the WAL-flush lines: over a fixture modelled on window 14 (the run, its waiters and published fsyncs, the window’s mean, the tick with none completed), a missed tick ending a run, a run’s bounds from late ticks' timestamps, a step across a reset left out, and a tick with no WAL row counting as the zero after a reset. The devstack smoke cmd::diag::pg_sample::tests::a_live_sample_writes_a_header_then_its_ticks runs in every battery and stops after three ticks, so its duration does not depend on the host. Its I/O checks, by timestamp rather than by position so a slow host cannot fail them: the first tick-or-error line carries io (under cgroup v2), its totals each with disk when a disk resolved, and each later line carrying io lies at least 3 ticks after the last one (normally only the first of the three); with a data device the devices read; and every container source present has a 12-hex id and a plain or ? label. No container is required, since the counted device need not hold Docker’s storage.

.githooks/pre-push

The pre-push hook is the fast local gate; the merge gate is the merge train’s car job (Quality Gates § CI: the car, ADR-086). The hook runs three stages in order under set -euo pipefail, and the first that fails rejects the push. A push that only deletes branches skips every stage, and the hook warns when core.hooksPath is not .githooks. Its published text is devstack/hooks/pre-push (local-dev § CI vs Local Differences has the install line).

  1. Commit signatures. Each pushed commit not yet on origin must be signed: an unsigned one (%G? is N) is named and the push fails. Key trust is left to the server.

  2. cargo xtask validate --profile fast. fmt, the static lints and gates, cargo machete, clippy and the ci unit nextest (--lib --bins); no Docker and no devstack. It ends with its own === validate timing === breakdown, printed on a red run too (local-dev § Battery timing). Two warm runs on 2026-11-21 on the reference host (32 CPUs) took 100 s and 204 s (in the longer one the unit nextest was 109 s and clippy 64 s); it varies with the host and with how much must recompile.

  3. git lfs pre-push. Replays the push’s ref lines to git-lfs, because a custom core.hooksPath replaces git’s built-in LFS hook; runs only when git-lfs is installed.

The hook has no opt-out variable; never git push --no-verify. Everything else the hook once ran now runs only in the car: the devstack battery (the integration nextest, the C24 program gate, the invariants), cargo xtask e2e and its degraded stage, the SDK suites, the security regression and the k6 smoke. cargo deny check runs in its own cargo-deny job. The whole battery is still runnable locally as cargo xtask validate.

git’s local variables (#2964). git runs the hook with GIT_DIR and the rest of git rev-parse --local-env-vars set, absolute from a worktree, and a git spawned under it acts on the pushing repository whatever its working directory. A test that builds a temporary repository, and any code that runs git outside this checkout (craig-policy’s policy-cache sync), spawns it through craig_policy::git_env::hermetic_git (in xtask, workspace::hermetic_git), which removes those variables. workspace::cargo_command removes them too, so no cargo or nextest child of cargo xtask validate inherits them. The regression tests point GIT_DIR at a sentinel repository in a temp dir and assert it keeps every byte.

The hook’s last line is === pre-push: OK ===: a silent exit after it belongs to git’s transport, not the hook.

E2E Tests (Playwright)

Running the suite

cargo xtask e2e runs in the car after the integration battery, and locally on demand:

  • Reseeds the devstack first (since 2026-06-18): the integration battery leaves the DB polluted (it mutates and deletes seeded rows), so e2e runs cargo xtask dev reseed to restore a clean, deterministic state before asserting. dev reseed waits for service health + verifies the seed before returning, so there is no post-restart bring-up race, and .ports.env is reconciled after the reseed (the reseed re-reserves the host ports — normally the same ones, but the file is re-verified regardless).

  • Then regenerates tests/e2e/lib/seed.ts from CRAIG_SEED/CRAIG_FAMILIES (defaults: 42/12) and runs the full Playwright suite against the devstack.

  • --no-refresh skips the reseed + manifest regen — pass it for an iterative spec-debugging loop, or when you have already reseeded, to run against the current data without wiping it (NOTE: plain cargo xtask e2e now wipes local DB state by default).

  • County specs consume single-owner fixtures (#1151): the three county-project specs mutate their seed fixtures irreversibly — subsidies-county consumes fixture D (its ERR create refuses on rerun), subsidies-guardianship fixture E, and subsidies-onestep fixture G. Every manual rerun of any of them needs cargo xtask dev reseed first, and the guardianship serial arc reproduces only as a whole file (each step’s precondition is the prior step’s postcondition — a line-filtered run of a later step fails from stale state by construction). Each spec’s header carries the local pointer.

  • Custom seeds: CRAIG_SEED=99 CRAIG_FAMILIES=15 cargo xtask e2e — both the container reseed (compose passes CRAIG_SEED/CRAIG_FAMILIES through) and the manifest regen read the same env, so they stay consistent in one command.

  • Minimum families: 8 (pagination tests need ≥10 referrals)

Runner protocol (#937) — specs observe, the runner acts

The e2e specs speak HTTP to the stack and nothing else: no spec may reach the container orchestrator (the Docker daemon socket is not mounted into craig-e2e; it never was a legitimate dependency). Where a proof needs the runner to ACT on the stack — today the ADR-013 leg "a session cookie survives a craig-web restart" — the suite is run in two Playwright phases with the action in between, using plain Playwright flags so ANY runner can implement it:

  1. Phase 1: playwright test --grep-invert @restart-phase — the whole suite; its setup project mints the storage states under the results mount (results/auth/<user>.json), so they persist across container invocations.

  2. The runner restarts the web tier by whatever means it owns — locally cargo xtask e2e calls dev restart-service craig-web and waits for health; the CI job on the Helm chart performs kubectl rollout restart deployment/craig-web and waits for the rollout.

  3. Phase 2: playwright test --grep @restart-phase --no-deps — ONLY the tagged leg, with the dependency chain skipped, so the cookie it loads demonstrably predates the restart.

cargo xtask e2e is the local implementation of this protocol, not its definition: xtask is developer tooling and disappears when the battery runs on real infrastructure; the contract that survives is the tag, the two invocations and the "runner restarts the web tier" step. A targeted local invocation (--grep, --project, --no-deps, …) runs as given in a single phase — the restart phase is then the caller’s to ask for explicitly.

The e2e image runs as the vendor’s non-root pwuser; every path a run writes is a mount (results, the auth states, the screenshot baselines) or the tmpfs HOME. Locally, compose maps the runtime uid to the checkout’s owner so bind-mounted output lands owned like the rest of the worktree — a developer-tooling concern; on the chart, results leave the pod as artifacts.

Setup

  • Dockerfile: tests/e2e/Dockerfile (FROM playwright, COPY tests, npm ci)

  • Config: tests/e2e/playwright.config.ts

  • Run: cargo xtask e2e (checks health, starts if needed, auto-rebuilds Playwright container, runs tests)

Projects

The project matrix lives in tests/e2e/playwright.config.ts — it is the source of truth and grows too often to enumerate here (16 projects defined at 2026-08-25, of which 14 materialize in a default run; screenshots and degraded are env-gated). degraded runs in the merge train’s car job (xtask e2e --degraded), not in the pre-push hook; screenshots stays manual by design, because a run rewrites the tracked images under docs/modules/ROOT/images/screenshots/ and a gate must not dirty the tree. The shape: a setup project logs in each per-role browsing principal (jane.doe, bob.smith, admin, dana.county, rita.regional, sam.state, paula.county, carol.reader — each a SEED.users entry, never a literal, #1792) and saves per-role storageState files; the per-role browsing projects (caseworker, bobsmith, admin, county, readonly) each load their role’s state and own a testMatch alternation of spec files; county also runs subsidies-office.spec.ts, whose describes switch to the rita / sam / paula states for one subsidy approval act per office floor (#1792); auth runs unauthenticated; auth-cookies covers the ADR-013 session lifecycle; config-guard fails any spec file no project’s testMatch claims (an orphaned spec cannot silently never run); and the special-purpose projects (screenshots, degraded, accessibility, intake-ui, intake-ui-shines, intake-ui-shines-tls, intake-ui-integrated) carry their own fixtures; and the journey project (#668, B4) owns every journey-*.spec.ts — the file-name marker ADR-071’s served-level rule keys on, so no other alternation may claim those files.

Edge visual-regression baselines (COMP-06, #756 / #1772)

tests/e2e/specs/intake-edge-visual.spec.ts (project intake-ui-shines-tls) pins four Git LFS baselines under tests/e2e/specs/screenshots/intake-edge-visual.spec.ts/: /report step 1 and /keygen, each in the light and the dark palette. They are generated and compared only inside the fixed-Chrome e2e image.

  • Framing and tolerance. Every shot frames the body element (expect(page.locator('body')).toHaveScreenshot), not the viewport, with maxDiffPixelRatio: 0.01 and Playwright’s default per-pixel threshold of 0.2. intake-public.css gives body a max-width and padding but no min-height, so its box is sized by its content, and adding or removing a form row changes the image height on either page. Playwright fails a size mismatch at any tolerance, so the tolerance is not what catches a layout change. Never loosen these numbers and never go back to a viewport shot: in the light palette a near-white control moving over a white card falls under the 0.2 threshold, which is how #648’s new Report Source row passed under 1 % (#1772). The framing crops the solid --page side margins, and anything painted outside body is not compared.

  • Guards. Two sad tests insert one synthetic labelled <select> row into step 1, assert that it grows the body box, and assert that each palette’s baseline rejects the page (expect(page.locator('body')).not.toHaveScreenshot). A negated match never writes a baseline, even under --update-snapshots, and a missing baseline fails it.

  • Regenerating. Any change to what step 1 or /keygen renders regenerates all four. Examples, not a full list: report.html, keygen.html, intake-public.css, the intake .ftl strings, the page JS, and the jurisdiction’s palette (GA’s bundle/theme.toml names the Simple Statehouse palette). Run cargo xtask e2e — --project=intake-ui-shines-tls --update-snapshots=all intake-edge-visual.spec.ts. Use --update-snapshots=all: the bare --update-snapshots rewrites only the baselines that currently fail. Commit the PNGs that changed.

Journey specs, the knob-evidence registry, and the post-journey sweep (#668, B4)

A journey spec (tests/e2e/specs/journey-<slug>.spec.ts, the journey project, jane.doe’s session for UI legs) enacts ONE corpus scenario end-to-end on entities the B2 given-builders construct, asserts the row’s oracles it can reach through APIs, and records its footprint — the scenario id plus the entity ids it built or mutated — via JourneyLedger (tests/e2e/lib/journey.ts) as test-results/e2e/journeys/<epoch>-<scenario>.json. The container has no SQL client, so the relational half runs afterwards: cargo xtask e2e reads the records stamped with THIS run’s epoch (stale leftovers from earlier runs are ignored, never deleted) and executes the SQL invariant catalog SCOPED to those ids (craig_test_lib::journey_sweep — the selector table names, per stem, the output column and entity kind; the body’s LIMIT is stripped so twenty strangers' rows cannot hide the journey’s). Scoping is the baseline (the entities did not exist before the journey), and EVERY hit fails with the scenario named — journeys are the enforcement vehicle for the report-only oracles. Verification: crates/craig-test-lib/tests/journey_sweep_scoped.rs plants an occupancy drift on a given-built home and proves the sweep fires there and nowhere else. The two outbox-joined cases invariants judge only inside the published-outbox retention horizon (30 d, ADR-058) — older events are pruned by design.

tests/e2e/knob-projects.toml is the knob-evidence registry: which Playwright project runs with which default-off CRAIG_… knobs ON. The scenarios audit joins a knob-gated corpus row’s bound spec file → the registry project whose glob matches it → that project’s knobs; a row is graded Covered only when some resolving project carries EVERY knob it names, else it caps at Partial and reports knob-capped. The audit never reads the environment; the registry is the declared evidence, and the config-coverage spec pins each registry glob to the SAME spec files the project’s real testMatch selects.

The cases-side oracles now have a catalog bucket, crates/craig-invariants/sql/ craig-cases/ (plan_superseded_same_tx, active_plan_review_due_required — DDL-backed, blocking — and cohort_bump_same_tx_as_event), with their corpus enforcement flipped to the invariant class the bidirectional join requires.

#1634 added the financial-side payment_events_staged_in_order (report-only; the outbox created_at of financial.payment_approved/issued/cleared must order the lifecycle, judged 25 days back inside the 30-day published-outbox retention) and four more sweep selectors — a selector may now name a second key column (alt_column) for pair-shaped invariants whose orientation is fixed, such as subsidy_coverage_overlap — that stem over a journey’s payments, and the three BLOCKING subsidy invariants (subsidy_projection_matches_head, subsidy_child_as_party, subsidy_coverage_overlap) over its agreements — so a spec that `ledger.track`s those kinds may assert the stems by footprint (the #669 footprint rule).

Lifecycle journeys (#3187)

A lifecycle journey is one named family story walked to an outcome: tests/e2e/specs/journey-lifecycle-<story>.spec.ts, one corpus row, its acts through the given library, and a JourneyLedger footprint for the sweep. Partner variants of a story are further tests in the same file. The programme’s rules are on the plan page.

The first is journey-lifecycle-reunification.spec.ts (core.permanency.report-to-reunification): a report is screened in and investigated, the finding is substantiated, a case opens, the child enters custody and a foster home, and the child then goes home (the placement ends, the removal episode exits as a reunification, custody closes on the exit date, the case closes). It asserts the in-care state before the outcome and the agreed state after it, across craig-cases, craig-placement, craig-financial and the audit trail.

Along the walk the family meets the education agency (georgia.exchange.doe-education-in-care, a row of Georgia’s pack), played by the DOE simulator. The child has a GTID and is a student the agency knows. With custody open the agency lists the child; its weekly batch runs, an admin collects the file, and the case’s worker reads the report through the API and on the education page, where it is a view with no control, while a caseworker who is not on the case is refused. The child changes school, and the next file replaces the report. After reunification the agency no longer lists the child and the report is withdrawn. The file’s second test, "the education agency does not know the GTID", walks a child the agency was never told about: the listing is refused (partner-rejected), a collected file reports nothing, and the family still reaches the closed case.

Those beats run under the doe fixture of tests/e2e/lib/doe-education.ts. craig-exchange sends to an interface’s one active partner whose agreement admits, and the seed links no agreement to any partner, so on a seeded stack the education agency is listed nothing. The fixture creates a partner of the test’s own at the simulator’s endpoint with an admitting agreement, parks every other active doe_slds partner for the test, and afterwards parks its own and reactivates the seeded one. The slot is deployment-wide; the Playwright battery runs one test at a time, which is what makes that safe. Because the partner is the test’s own, every send and every listing under it is that test’s, so the journey asserts exact lists. The fixture’s creates derive their request ids from the run, so a retried test gets the same partner back.

The same walk meets the person index, played by the EMPI simulator. Its scenario row, georgia.exchange.empi-person-index, is in Georgia’s pack (scenarios/exchange.toml of the Georgia layer config-sources.lock pins), where it is bound to the tests below: cargo xtask scenarios audit lists it as covered. Once the case is open, and before custody, the case’s worker opens the Household tab and asks the index about the child. (Before custody because recording the ID changes the child’s record, and a send to the education agency that was staged for the record as it was is abandoned as superseded and staged again, which the education beats would count as a second listing send.) The index is sure of the child, so the page offers that one record, already chosen, and no registration; the worker records it, the child’s EMPI id is on file as matched in the index, and the simulator holds CRAIG’s participation under the child’s person id. Two more tests in the file ask about a child the index is less sure of ("a near match in the person index must be chosen, and registering is closed") and a child it does not hold ("a child the person index does not hold is registered once the record is complete"): the page names the two facts the child’s record lacks, the worker records each on the page its link leads to, asks again and registers, and the id is on file as assigned by the index. Those beats run under the personIndex fixture of tests/e2e/lib/person-index.ts, which claims the index’s partner slot as the doe fixture claims the education agency’s; both use tests/e2e/lib/partner-slot.ts.

The same walk meets the eligibility system, played by the IES simulator (#3193). While the child is in custody the case’s worker submits the child’s Medicaid application on the custody panel. CRAIG refers it, and the system’s application number comes to rest on the application as its receipt, which the page shows. The walk then has the system do its scheduled work, its call to craig-exchange’s return listener, and the page shows what the system decided: the status, the system’s case, the program ID, and the interface that reported it. Two more tests start from a child in custody whose application the system has taken: the system denies it ("the eligibility system denies a Medicaid application"), and an administrator revokes the system’s certificate, after which the call is answered 403, the application holds its receipt and nothing else, and the system still owes the outcome ("a revoked certificate refuses the eligibility system, and the application learns nothing"). Those two build their child through the API and replay on a retry; the system’s call carries every outcome it still owes, so each test asserts on its own application only.

Those beats run under the returns fixture of tests/e2e/lib/returns-fixture.ts. It registers and approves the simulator’s client certificate against a craig-security partner of the test’s own, claims the interface’s partner slot with that partner as the row’s caller, and after the test revokes the registration and restores the slot. The registry holds a certificate live at most once, so a registration an interrupted run left behind would refuse the next one; the fixture then searches the slot’s caller partners by their name prefix (returns-slot-), revokes what they hold under the slot’s label and registers again. craig_test_lib::returns_slot uses the same label and prefix, so the Playwright battery and the Rust suites each clear what the other left. The core corpus row core.exchange.partner-return (compliance/scenario-inventory/exchange.toml) binds these tests. Georgia’s pack states the same journey for its own wire as the row georgia.exchange.ies-medicaid-referral, bound to this journey and to the devstack suite services/craig-cases/tests/api/medicaid_referral.rs. One of its oracles, that a referral sent again keeps one receipt, is bound to CRAIG’s half only (a_receipt_that_was_not_applied_is_sent_again_under_one_identity, on the reference partner, and a_repeated_outcome_is_a_replay); that IES itself answers a repeated transaction with the same application number is held by a test of Georgia’s own partner crate, which a binding cannot name.

The suite has no clock to move and the services refuse a future date, so a story’s business dates run backwards from business today. An instant a story writes is noon UTC of a day before today: today’s noon has not passed before 07:00 Eastern. For the same reason two weekly files of one walk carry the same date: the second replaces the first’s report because its facts differ, not because it is later.

The second is journey-lifecycle-adoption.spec.ts (core.permanency.report-to-adoption, #3230): a family walked to an adoption by the foster parents. The child’s mother and father are on record as the child’s parents; the child enters custody and a foster home; the permanency goal changes from reunification to adoption; a petition to terminate is filed against the father, the mother surrenders her rights, and the court terminates the father’s by an order that also states the child’s permanent custody. The foster home then becomes the child’s pre-adoptive home, which is a second placement in the same home, since a placement’s categories are fixed when it is made. The adoption is final: the placement ends, the removal episode exits as an adoption naming the two adoptive parents, custody closes as adoption finalized on the exit date, and the case closes for adoption. Every act is a builder. The walk reads the worker’s pages twice: the custody panel lists the status the order stated, marked as a court order’s, and the child’s episodes page shows the exit to adoption with the two adoptive parents in its correction form.

It asserts, through the service that owns each fact:

  • one live parental-rights row per parent, the father’s superseding his petition and naming the order;

  • that the order’s status joined the custody episode already open;

  • the goal in force on each side of the day it changed;

  • each placement’s per-diem settled to the days the child was in it, at its own rate, with the day of the move paid once and nothing paid from the day of the adoption;

  • the exit’s adoptive answers, custody closed on the exit date, and the closed case with its audit record;

  • the home’s occupancy at each beat, including across the move.

The child is a student the education agency knows, as in the first journey: the agency still lists the child after the termination order, since the custody episode is the same one, and drops the child when custody closes on the adoption. Georgia’s row georgia.exchange.doe-education-in-care binds this journey, and the guardianship journey below, to its oracle that the agency lists a child only while in custody.

The file’s second test, "an adoption cannot be finalised out of order", asks for four acts too early and is refused each one with the problem type the service documents, with nothing written: a parental-rights action naming a person who is not the child’s parent (400 parent-not-linked), one naming an order that is not a termination order (400 parental-rights-order-invalid), the adoption exit while the child is placed (409 episode-has-open-arrangement), and the case’s close while custody is open (409 custody-open).

A journey’s in-care assertions describe the family as it stands at that beat: listed, placed, in custody. A walk that has reached its outcome therefore cannot be walked again under the same run id. A retry converges when the first attempt stopped before the outcome: each act replays to its first row, a placement that has since ended included.

What the product does not have on this path is not walked: adoption assistance (#1966), anything that seals an adopted child’s record, and any partner that is told of a termination or an adoption.

The third is journey-lifecycle-guardianship.spec.ts (core.permanency.report-to-guardianship, #3237): a family walked to a relative’s guardianship, and what the relative is paid on the way. The child enters custody and is placed with a grandmother, a relative placement in a kinship household, which under Georgia’s layer gets no per-diem. The county director enrols her in the Enhanced Relative Rate (ERR), which covers from the placement’s first day, and a generation pays every month from then through the current one, the first prorated by days. The permanency goal becomes guardianship and she signs a subsidized guardianship (SG) agreement, which pays nothing while pending. The court grants guardianship in the month before the current one: the placement ends, the removal episode exits as a guardianship naming her, and custody closes as guardianship. The county director ends the ERR as of that day and activates the SG, and a second generation takes back the ERR’s payment for the current month and pays the SG for it. The case closes for guardianship, and the SG goes on.

The story’s rules count calendar months (six months with the relative before the guardianship; payments from the month after it), so its dates are fixed by month and not by days back from today: the placement on the 6th of the eighth month back, the guardianship on the 10th of last month. They hold whatever day of the month the walk runs. The guardianship is deliberately recorded after the current month’s ERR payment exists, since a court’s order reaches the record after the fact and the generator has to correct for it.

It asserts, through the service that owns each fact:

  • the ERR’s nine payments after the first generation, each for its month and its amount, and no per-diem;

  • after the second, the ERR’s payment for the current month voided, its payment for the month of the guardianship standing whole, the SG’s one payment, and exactly one live subsidy payment a month from the placement on;

  • the SG active with its transfer day the exit’s day and its payments beginning the first of the current month, and the ERR terminated as guardianship_finalized from that day, which the SG’s page also shows the worker;

  • the exit’s guardian, custody closed on the exit date, the closed case with its audit record, and every reference between the placement, the agreements and the child.

The first three are Georgia’s subsidy policy and not the product’s. The core corpus row carries the last group only; the subsidy oracles are the row georgia.subsidy.err-to-sg-handoff of Georgia’s pack (scenarios/subsidy.toml of the Georgia layer config-sources.lock pins), which binds this journey to all three and craig-financial’s suites sg_generation_boundary, sg_activate_api and sg_exit_witness to the handoff and the activation. No Rust test is bound to the first, that the ERR’s first month is prorated from the placement’s first day: the journey alone shows it. The spec records both agreements in its footprint, so the post-journey sweep runs craig-financial’s subsidy invariants over them.

The file’s second test, "a guardianship before six months with the relative is not subsidized", places a second child with a grandmother three months before the guardianship. The SG’s activation is refused with 400, and its detail names the residence floor, the day the residence began and the transfer day; the agreement stays pending and nothing is paid. The refusals of the handoff’s order (an activation while the child is still placed, or beside an open ERR) are held on the county director’s pages by subsidies-guardianship.spec.ts.

Each generation the walk runs is generateCurrentMonth (tests/e2e/lib/subsidy-generation.ts), which is deployment-wide; the walk asserts on its own child’s payments. A retry converges when the first attempt stopped before the handoff. After it, a retried walk cannot pass its first-generation beat, which asserts the ERR’s nine payments as they stood before the guardianship.

What the product does not have on this path is not walked: anything that ends the ERR or activates the SG when the guardianship is granted (#3238), a court order for a guardianship (#3239), and a per-diem for a relative placement under Georgia’s layer (#3231).

The fourth is journey-lifecycle-reentry.spec.ts (core.permanency.reentry-after-reunification, #3243): a family the product has seen before. The first time is the first journey’s story, told by builders: a report, a substantiated investigation, a case, custody, a foster home, a Medicaid application the eligibility system approves, and the child home again with the case closed. The report described a child by an age, so the worker links its entry to the person record they made. Then a second report names the same child by full name and birth date, and its screener attests the family’s prior history. It is investigated and substantiated; a second case opens with the same child; the child comes back into custody and into the same foster home. The walk ends with the child in care.

The first stay runs from twelve days ago to seven days ago and the second from four days ago. A report, an investigation and a case are stamped when they are made, so both pairs are made as the walk runs.

It asserts, through the service that owns each fact:

  • that craig-cases tied the second report to the child’s record when the report was converted, with no act of the worker (ADR-019): the child’s reports are the two, and the family chain page links both reports, both referrals, both investigations and both cases;

  • that the first case is still closed, and the child’s cases are the two;

  • one custody episode in each case that share no day, with custody dated the day the child went home refused first (409 custody-episode-overlap: a re-entry opens the day after at the earliest);

  • two removal episodes, the first exited as a reunification and the second open under the second case;

  • the second placement’s own pending per-diem, the first stay’s per-diem as the reunification settled it, every reference between the two cases, placements and episodes, and the home’s occupancy at each beat;

  • that the person index is not asked about a child who holds its id (409 person-index-person-identified);

  • a second Medicaid application, of the second custody episode, with a receipt under its own reference. The eligibility system then denies the child and reports that for both applications in one call, and each record comes to rest on its own application: the first, whose custody has closed, holds its receipt, the approval and the denial; the second its receipt and the denial.

The education agency meets the child twice as well. It lists the child in care, drops the child at home and lists the child again under the second custody episode: three sends, the last one doe_slds.custody_opened, and the listing names the second case’s referral. The school report withdrawn at home comes back with the next weekly file, under the new listing. These, the receipt and the routing by reference are Georgia’s oracles; the core corpus row carries the product’s rules.

The second referral carries PRIORITY_24HR where the first carries STANDARD: Georgia answers a family with prior CPS history within 24 hours, and the builder checks the priority the screener’s attested facts derive. The product does not derive that fact (#3247).

The file’s second test, "a child in custody is not taken into custody again", opens two cases with the same child and takes the child into custody under the first. Custody under the second is refused with 409 custody-episode-overlap, naming the open episode, and a removal episode under the second with 409 episode-overlap; nothing is written.

A retry converges when the first attempt stopped while the child was first in care. Once the child has gone home, a retried walk cannot pass its first beats, which assert the family as it stood the first time (the child listed, one school report, the application approved and nothing after).

What the product does not have on this path is not walked: a worker’s view of a child’s earlier episodes across cases (#3244), and a re-entry on the day of the exit, which craig-placement takes and craig-cases refuses (#3245).

Single-service restart (used by auth-cookies spec)

cargo xtask dev restart-service <name> restarts one CRAIG application service (data preserved) and polls its healthcheck until green. Service name is validated against docker::CRAIG_SERVICES. The E2E helper restartCraigWebAndWait() in tests/e2e/lib/helpers.ts uses this to prove that cookie-encrypted sessions survive a web-tier restart.

Spec files and counts

Spec files live under tests/e2e/specs/ — the directory is the source of truth, and counts drift too fast to pin here (ls tests/e2e/specs/*.spec.ts | wc -l for the file count, cargo xtask e2e --list or the Playwright report for the run count). The suite runs single-worker, sequential (workers: 1, fullyParallel: false), so serial order is usable as a state proof within a file.

The journey "given" library (#666, B2)

tests/e2e/lib/given/ (TS) and craig_test_lib::given (Rust) build journey PRECONDITIONS by replaying the real service endpoints as a named actor — the "honest constructor" doctrine: an S2S-witnessed row or an event chain cannot be fabricated in SQL, so a given never touches the database. The precondition closure of the B4 journeys: givenReport (public intake edge), givenScreenedInReferral (decision + convert), givenInvestigation, givenCase (+ household children + primary caregiver), givenActivePlacement (+ givenHome), givenApprovedPlan, givenErrAgreement (county director), givenReviewCompleted (the subsidy renewal review).

The lifecycle journeys (#3188) add the builders that take a family to an outcome: givenSubstantiatedClose (a substantiated allegation, then the investigation’s close), givenCustodyOpened and givenCustodyClosed (the craig-cases custody episode, through the legal-status ledger), givenPlacementEnded, givenEpisodeExit (the craig-placement removal episode’s exit) and givenCaseClosed. givenCase takes existingChildren, for a child who exists before the case opens, as an investigation’s victim does. A status act (a close or an end) reads the row first and skips the write when it already holds: re-sending a transition that has happened is a refusal, not a replay.

The adoption journey (#3230) adds what a court decides about a child’s parents, and the answers an adoption exit carries:

  • givenParent (case.ts) creates a person and links it to the child as mother, father, legal_guardian or putative_parent. A parental-rights action may name only a linked parent. readParents reads the links in force.

  • givenPermanencyGoal (permanency.ts) records a permanency plan with the day it was established; the plan in force on a day is the one established latest on or before it, which readPermanencyGoal reads. The case plan givenApprovedPlan builds carries no goal.

  • givenCourtOrder (court.ts) records an order and, when asked, the legal status it states for children of the case. For a child with an open custody episode that status joins the episode; it opens no second one.

  • givenParentalRightsAction (court.ts) records how one parent’s rights end, voluntary or involuntary, with a petition date, a termination date and the order. givenParentalRightsCorrection restates a row: a petition becomes a termination once the court has ruled, and the new row supersedes the old. readParentalRights reads the live rows.

  • givenEpisodeExit takes answers: the adoption and guardianship answers of the exit, among them the two adoptive parents as craig-cases persons. The service admits them on an adoption or guardianship exit only.

  • custody.ts names two more of Georgia’s legal statuses: PERMANENT_COURT_CUSTODY (PCT) and ADOPTION_FINALIZED (NAF).

The guardianship journey (#3237) adds the handoff from the relative subsidy to subsidized guardianship, in subsidy.ts. The agreements are the county director’s acts, so a journey calls these as given.as('danaCounty'):

  • givenErrAgreement takes caregiverFrom, the first day of the caregiver binding it makes. A family that goes on to a guardianship binds from the placement’s first day: the guardianship agreement’s activation reads the binding as of the day the guardian took the child. The agreement’s coverage starts on the placement’s first day however long ago that was, within the twelve months the generator reaches.

  • givenPendingSgAgreement creates a pending subsidized guardianship agreement, signed on the day it is given. It may sit beside the child’s active ERR.

  • givenErrEndedForGuardianship terminates the ERR as guardianship_finalized, dated the day of the episode’s guardianship exit, which is the only day the service takes.

  • givenSgActivated activates the pending agreement. The caller states no date: the service takes the transfer day from the exit, and payments begin the month after it.

  • The last two are transitions, and a transition that has happened is a refusal and not a replay, so each reads the agreement first and leaves it alone when it already stands as asked. readAgreement reads an agreement’s status, its dates and its statuses over time.

  • custody.ts names GUARDIANSHIP_GRANTED (NGP), and backpay.ts has dayOfMonthBack beside monthStartBack: a story whose rules count calendar months fixes its dates by month, so they hold whatever day of the month it is told on.

tests/e2e/lib/subsidy-generation.ts runs the monthly payment generation: generateCurrentMonth enqueues a run for the current month and waits for its job (waitForJob), then answers the run’s report. A generation is deployment-wide. It pays the month for every payable agreement and repairs every agreement-month queued since the last run, which craig-financial also does by itself when it starts and every hour; so a spec asserts on its own child’s payments and never on a count across the deployment. craig-financial takes one generation job a month at a time and refuses a second with 409 job-already-active, naming no job to wait on. The helper asks again until its request is taken, so its run starts after the other one ended and sees everything its caller did before asking.

The re-entry journey (#3243) puts one child through two cases, so its builders are entered a second time for the same person:

  • A builder whose route names its case or its report only in the path carries that id in its builder name: the screening decision (screening-decision:<report>), a household member (household:<case>:<person>), a case plan (plan:<case>) and a Medicaid application (medicaid-application:<case>:<child>). The services claim a request id together with the path, so the same id presented under another case is refused as 409 idempotency-conflict; with the id in the name, the second case gets a row of its own and each case’s builder still replays. Three builders whose parent also rides only in the path are unchanged: a trafficking statement and a trafficking report (each per removal episode) and a home’s training (per home). No journey enters any of them for a second parent.

  • A report’s child (GivenChild, report.ts) states an age in years or the birth date itself (bornOn). A reporter who does not know the child gives an age; a report that names the child as the person record does can be matched to that person when it is converted (ADR-019: Georgia’s ruleset links on an exact name with an exact birth date).

  • givenReportPersonLink (report.ts) is a worker’s link of one child entry of a report to a person: the worker’s own choice, so the link names no matching ruleset. A person’s reports are the linked ones.

  • givenScreenedInReferral takes a third response, within24Hours: the screener also attests that the family has prior CPS history, which Georgia answers within 24 hours (PRIORITY_24HR). The product does not derive that fact from the people it holds; the screener states it.

What the lifecycle journeys share is in tests/e2e/lib/lifecycle-walk.ts: the walk from a report to an open case (investigateToCase, which takes the report’s options and the screener’s response, so a second walk from another report reaches a second case with the same child), the student the education agency knows (recordStudent), the listing that follows custody (expectListed, sendsSoFar, LISTING_SEND), the delisting that follows its close (expectDelisted) and the closed case (expectClosedForGood, which takes the closure reason). It also holds a stay in foster care, shared by the stories that have one: custody, the removal episode, a foster home, its first per-diem and a case plan (intoCare), going home (reunify), the per-diem settled to the days in care (expectPerDiemSettledAtHome), the child’s sex on record (recordSex) and one week’s file collected from the education agency (collectTheWeek).

  • Actor: the given fixture (import { test } from '../lib/given/fixture.js') opens one GivenContext per test as the project option givenActor (default jane.doe); given.as('danaCounty') switches principal for one act (ERR needs the county-director office proof) without changing the run. Bearers are minted through the craig-api ROPC client; the browser session is the JOURNEY’s vehicle, the bearer is the GIVEN’s — case and investigation creation have no BFF path (#333).

  • Isolation: runIdFor(testInfo) = g + sha1(run epoch · parallelIndex · title path)[..10]. Two workers never collide, two tests never collide, a retry reproduces the id. cargo xtask e2e stamps CRAIG_E2E_RUN_EPOCH per invocation; a hand-run npx playwright test is stamped once by playwright.config.ts; the Rust side falls back to a per-process epoch (nextest = one process per test), so a local re-run never replays an earlier run’s consumed build.

  • Get-or-create: every create’s client_request_id is uuid-v5(runId · builder · canonical body). Re-entering a builder AS THE SAME ACTOR replays under ADR-062’s request-claim identity (same id + same intent → the original entity), and a changed body derives a different id — never a 409; the effective actor is part of the intent, so a different principal re-entering an actor-less body (home, person, report, decision, plan) in the same run is a 409 by design. Server-idempotent legs (convert, review completion) read-then-act. Dates are anchored to given.today (Eastern business today, fixed at context creation) so one chain never straddles a day; a placement starts business yesterday by default so a same-run renewal re-sign lands strictly after the head term.

  • No cleanup: run-scoped names + the reseed between batteries own isolation; builders never register deletes. Persons are findable by GET /v1/cases/persons?name=<runId>.

  • Actor rule for placements (#1213): placement’s create authz reads the case_assignments projection; a pure caseworker is refused fail-closed until it lands. Build placements as a supervisor-class actor; the builder’s 403 names the rule rather than polling around it.

  • Contract spec: specs/given-builders.spec.ts (round trip → typed id → readable; re-entered partial build converges without duplicates; the outcome builders and the adoption builders each converge on re-entry, before and after the case closes; the guardianship builders converge on re-entry, and two generations asked for at once then both run and pay what the two agreements are owed; run-id collision probe) and crates/craig-test-lib/tests/given_roundtrip.rs mirror the plan’s B2 verification row verbatim.

Seed Data

  • Generated by craig-seed — deterministic seed generator (tools/craig-seed/)

  • Pinned defaults: CRAIG_SEED=42, CRAIG_FAMILIES=12 (pinned in docker-compose.yml; CI inherits 12 through compose’s :-12 fallback — there is no separate .gitlab-ci.yml pin). The generator binary’s OWN default stays --families 9 — the reproducibility baseline pinned by the seed42/families9 byte-identity fixture. The 12-vs-9 split is intentional two-tier layering (#1006): operational dataset vs baseline corpus; the compose env line carries the authoritative comment. --families is at least 4 (craig_seed::MIN_FAMILIES, #2793) because the base subsidy fixtures anchor to the first four generated cases and each family yields at most one, and a seed whose families still generate fewer cases than its fixtures and active scenario variants need is refused rather than seeded with orphaned rows.

  • SQL: auto-generated at container startup, seeded via craig-seed binary in Docker

  • TypeScript manifest: tests/e2e/lib/seed.ts — auto-generated via craig-seed --manifest

    • Indexed naming: case0_floyd, ref0_fulton, inv0, home0_bibb, partner0, icpc0, plan0

    • Person keys: camelCase(firstName, lastName) — e.g. keiraRolfson

    • Cross-entity refs: contacts have caseId, placements have caseId/childId, agreements have partnerId, ICPC has childId

    • SEED.scenarios.<key> (#667, B3): EVERY known seed scenario VARIANT, { active, slug, …pinned ids when active }. Narrow on .active and test.skip(!s.active, 'scenario <slug> not seeded — run: cargo xtask e2e --scenario <slug>') — the skip is visible in the list/junit/html reports. The committed manifest is the BASE seed (all inactive). A test that skips this way takes { tag: '@seed-variant' }, the tag the car’s scenario line greps for; an xtask unit test (every_variant_gated_test_carries_the_tag_the_car_greps_for) fails a gated test without it.

  • Seed scenario variants (#667, B3): cargo xtask e2e --scenario <slug> / cargo xtask dev reseed --scenario <slug> (repeatable) layer a named BACKGROUND state over the base families — subsidy-generator-backlog (an ACTIVE ERR with no payment rows, the generator’s target) and foster-home-at-capacity (a home at max_capacity 2). Every variant pins all of its ids (blocks …5000_10xx / …5000_11xx) and draws nothing from the streams, so the base renders stay byte-identical with variants off; the active set joins the seed identity, so a slug change needs a volume-wiping verb (dev reseed). Not a corpus scenario (ADR-071) and not perf --scenario.

  • The variant legs run in every car (maintainer ruling 2026-11-12, #2610). Three tests skip on the base seed: the two variant legs of seed-scenarios.spec.ts and the one test of journey-subsidy-generator-month-emission.spec.ts, the e2e-spec binding of the t1-core corpus row georgia.subsidy.generator-month-emission. The car runs them as one line right after the main browser run, and so does cargo xtask validate (--profile full): xtask e2e --scenario subsidy-generator-backlog --scenario foster-home-at-capacity --grep @seed-variant.

    • It activates every variant (they are additive and pin disjoint id blocks, so one line serves both; an xtask unit test holds the line to the slugs the committed manifest lists) and greps for the tag, so Playwright runs the three tests and the setup project they depend on, in one phase. The rest of the suite is not repeated: the main run covers it on the base seed, which is the seed its specs are written against.

    • The run regenerates the tracked tests/e2e/lib/seed.ts with active sections, bakes it into the e2e image, and reseeds with the variants. When it ends, green or red (a failed prelude included), it regenerates the base manifest, so git status is clean afterwards. If that last regeneration fails, a green run fails, naming the file.

    • The stack stays seeded with the variants until the next reseed. In the car that is the next line: e2e --degraded reseeds with no variant, so sdk-test, security and perf run on the base data. After running the line by hand, cargo xtask dev reseed returns the stack to the base seed.

    • The scenarios audit resolves an e2e-spec binding from the spec’s source (the file and its test.describe title; a .skip or .fixme suite does not resolve) and reads no run result, so it graded that corpus row covered while its only binding skipped at run time in every gate. The audit is unchanged; the binding now runs in every car.

  • With seed=42, families=12: 50 persons, 15 referrals, 12 investigations, 10 cases, 6 plans, 6 contacts, 5 court orders, 3 foster homes, 12 placements, 5 partners, 6 agreements, 2 ICPC (one a pinned overdue received exemplar), 5 rate tables, ~36 payments, 1 claiming record

  • Subsidy fixture (#1068/#1081, pinned ids …5000_00xx — seed-independent): 2 agreements (SG + NRSG), each with rev-1 terms (dues AS-OF-relative: renewal +11 months, paper +5), a pending→active interval chain, 2 open cycle-1 review slots (renewal_12mo + paper_6mo, due on the terms anchors — the shape materialize_anchor_slots seeds at activation), and a 3-month unit-month payment history ending at the as-of month

  • Default pagination: per_page=25 (BFF handler). Use ?per_page=10 in tests to force pagination with 15 referrals.

  • Case number format: {COUNTY}-{DATE}-{HASH} (e.g. FULTON-20260305-7AE1)

Page Object Model

  • tests/e2e/pages/ — CasesListPage, CaseDetailPage, FosterHomeDetailPage, RulesListPage, PaymentDetailPage, etc.

  • Helpers: tests/e2e/lib/helpers.ts (scrollAndWaitForFragment)

  • Compiler settings: tests/e2e/tsconfig.json and sdks/typescript/tsconfig.json set noUncheckedIndexedAccess and exactOptionalPropertyTypes on top of strict. A spec reads a list element or a regex group through tests/e2e/lib/defined.ts (at, first, group, ymd), which throws naming what was missing and never supplies a default; it omits an optional key instead of passing undefined, and opens a context without the project’s storage state with NO_STORAGE_STATE (tests/e2e/lib/portal-login.ts).

  • Lazy htmx panels: tests/e2e/lib/lazy-panel.ts (scrollUntilRead, armSettle, unfold, answerOn, submit, and openFederalFactsPanel for a child’s Federal facts card). A spec imports these; it does not copy them. The Medicaid section of the custody panel has its own (tests/e2e/lib/medicaid-application.ts: the submit, a row, and what a row says the eligibility system reported).

Do not reuse a spec-targeted CSS class on a new element

When adding a UI element to a page an e2e spec covers, do not reuse a CSS class that a spec targets via a generic page.locator('.classname'). Playwright strict mode fails a locator that resolves to more than one element — and a node counts even when it is x-show-hidden, because Alpine x-show only toggles visibility and leaves the element in the DOM. (x-if is safe: it removes the node.) A hidden new element sharing an existing class therefore produces a two-match strict-mode failure that breaks unrelated tests — and it surfaces only at the pre-push gate, after a full validate cycle, not where the new element was added.

Before reusing an existing class on a new element, grep the specs first:

grep -rn "locator('.classname')" tests/e2e/

If any spec targets it generically, give the new element a dedicated class. Mirror styling via the existing design tokens (var(--danger-) / var(--success-)), never raw hex — the intake_public_css_has_no_raw_hex_colors unit test rejects raw hex in the public CSS.

The Playwright container reaches the plain-http intake instances by container URL (http://craig-intake…:<port>;), which is not a secure context: crypto.subtle, crypto.randomUUID and passkeys are unavailable there, so specs on those projects stay crypto-free and assert what the pages do when they cannot sign. Browser signing runs in tests/e2e/specs/intake-passkey.spec.ts on the intake-ui-shines-tls project. That project starts Chromium with a host-resolver rule mapping localhost:8013 to the TLS instance, so the page’s origin is https://localhost:8013, the one the devstack keyring’s WebAuthn policy lists, and the spec drives Chromium’s virtual authenticator over the DevTools protocol. The rule applies to the browser only; a spec’s request fixture resolves names itself.

Manual passkey compatibility pass (#2203)

Real authenticators cannot run in CI, and the Playwright suite covers only Chromium’s virtual one. This pass is run by a person on each class below before the passkey work is declared done, and again when a class’s browser, OS or extension has a major release (ADR-082). An authenticator-specific failure gets its own fix: issue; nothing here is relaxed to make a class pass.

Classes
  • Windows Hello, in Edge or Chrome

  • iCloud Keychain, in Safari

  • Google Password Manager, in Chrome

  • the Bitwarden browser extension

  • a FIDO2 hardware key with a PIN

Setup, once per machine
  1. cargo xtask dev start --profile dev. The SHINES intake is then at http://localhost:8011, an origin the devstack keyring’s passkey policy lists.

  2. Approving a passkey is an administrator call the stack does not publish. Run it on the project network, with the kid the registration page shows:

    cargo xtask dev exec -- curl -sf -X PUT -H 'authorization: Bearer devstack-keyring-admin-token' \
      http://craig-intake-keyring:8010/keys/<kid>/approve
Steps, per class
  1. Register. On /keygen, enter a user identifier and a display name and create the passkey. Expect the "Pending Approval" confirmation and a kid starting wa_.

  2. Pending is refused. On /report, file a mandated report and submit. Expect the "Signature not accepted" message with the form still filled.

  3. Sign a report. Approve the kid, submit the same form again. Expect the success view with a tracking reference.

  4. Dismiss the prompt. Start another mandated submit and cancel the passkey prompt. Expect "Signing was cancelled. Nothing was sent." and the form still filled.

  5. Self-service. On /passkeys, show the passkeys, then save a new display name. Expect the passkey listed as approved and in use, and "Name saved."

  6. Add a device by hybrid QR. On /passkeys, add a device and, at the first prompt, choose another device (a phone, by QR code). Then confirm with the passkey in use. Expect a second passkey, approved.

  7. Capture a vector. Paste sdks/test-vectors/webauthn/capture-manual.js into the console on /keygen, as its header describes, and save the printed object.

  8. Clean up. Revoke the passkeys on /passkeys and delete them, and the vector’s credential, from the authenticator.

Recording the pass
  • Add each class’s captured object to a file sdks/test-vectors/webauthn/<class>.json with the members chromium-virtual.json has: rp_id (localhost), origin (http://localhost:8011) and vectors. crates/craig-webauthn/tests/vectors.rs reads every *.json in that directory, so the new file is verified, and refused after any one-byte change to its assertion, with no code change.

  • State in the MR, per class: the browser, OS and extension versions, the date, and each step’s result.

Two things are not known until the first pass: whether Safari offers a passkey on http://localhost, and whether a phone accepts a hybrid request for the RP ID localhost. If either refuses, record it on #2203; the answer is a deployment with a real host name and certificate for that step, not a change to the pages.

axe-core accessibility-audit configuration

The accessibility-audit spec drives @axe-core/playwright (AxeBuilder). Three configuration gotchas produce silently-wrong audits — a run that passes while asserting less than intended:

  • options() OVERRIDES withTags() / withRules() — they do not compose. Passing options() discards any tags or rules set via the separate builder methods. Put all configuration in a single options({ runOnly: { type: 'tag', values }, rules }) call rather than mixing the two styles.

  • The target-size rule ships enabled: false by default and must be explicitly enabled to run — include its tag in runOnly and set rules: { 'target-size': { enabled: true } }.

  • Under forced-colors / high-contrast, axe returns color-contrast as incomplete by design. That is expected behavior, not a failure — allowlist the incomplete color-contrast result when auditing a forced-colors media emulation rather than treating it as a violation.

nextest Profiles (.config/nextest.toml)

Profile Use Case Slow Timeout JUnit Output

default

Local dev (cargo nextest run)

60s

unit/results.xml

integration

The local full battery’s main stage (cargo xtask validate: ONE workspace run with --run-ignored=all) and the scoped run (cargo xtask test --package <crate> --integration: one package, #1802)

60s

integration/results.xml

ci

CI --lib --bins run (devstack-bound tests are `#[ignore]`d and never execute here)

default

unit/results.xml

ci-integration

The car’s battery lane (#3046): cargo xtask test --integration --profile ci-integration against the stack dev start brought up; blocking on a merge train (ADR-086); no retries

120s

integration/results.xml

Every per-test override — the [test-groups] serializations (subsidy lease, SSA partner slot, person-index slot, detection scans, adapter-kind global, reap finalizers, docker-secrets) and the slow-timeout envelopes — is written ONCE, under [profile.default] (#2318). nextest checks a profile’s own overrides first and then default’s, so `integration, ci-integration and local runs all apply the same set; the two battery profiles define none of their own. The xtask nextest_profiles pin (#1648; runs in the battery) reduces each override to (filter, test-group, slow-timeout, retries, threads-required), refuses a battery-profile override that copies a default one, and holds integration and ci-integration equal, naming any one-sided entry. Add a shared override to default; a genuinely profile-specific one goes under BOTH battery profiles.

All four profiles use fail-fast = false and test-threads = 8 (bounded so integration tests don’t overwhelm the Docker devstack services). JUnit paths are relative to the store dir + profile: the battery’s report lands at test-results/integration/integration/results.xml. The integration profile deliberately has NO retries (#1165: a retry masked a real contention failure — first-attempt red must red the battery).

Every host runs the integration profile’s 8 threads (local-dev § Battery threads and the nextest environment); 16 measured faster but unstable on the reference host (#2243; closed won’t-do, #2244). The battery removes NEXTEST_TEST_THREADS and NEXTEST_RETRIES from nextest’s environment, so the profile’s threads and its no-retries rule hold over a shell export. CI’s ci-integration never selects a row.

Serialization groups ([test-groups])

Contention pairs are serialized by group, never masked by retries. Both groups carry their full charters as comments in .config/nextest.toml; membership is re-checkable with cargo nextest show-config test-groups --profile <p> --run-ignored=all (the selection flag matters — without it, `#[ignore]`d members are invisible).

Group Charter (abridged)

subsidy-generation-lease

The subsidy lifecycle/sweep tests contend on the two deployment-global run leases whose exclusivity IS the feature under test (#1068/#1096) — and, since #1937–#1939, on the financial job arbiters (subsidy_generate:<month>, import_finalize:<batch_id>, the per-jurisdiction singleton sweep_preview:<jurisdiction>, sweep_execute:<run_id>). Every term of its filter is anchored to the binary it matches (binary_id(…), #2318): four whole binaries, the craig-financial::api suites by module, and the lib’s lease and gate unit tests, the bin’s drain legs and craig-web’s subsidy_agreements unit tests. The xtask nextest_profiles pin refuses an unanchored term.

security-detection-scan

The craig-security tests that mutate shared detection state (scan-invoking — every scan is global — plus ack-invoking and the 8-way volley). Tertiary defense behind the #1172 partial-unique arbiter and the devstack scheduler disable (#1167 D4); pure validation/authz/EXPLAIN tests and the hermetic template-clone tests stay parallel.

The subsidy-generation tick is a standing legitimate contender (#1108)

Unlike the security scan scheduler (disabled on the devstack, #1167 D4), the financial subsidy-generation scheduler stays ALWAYS ON — its hourly
on-restart tick against the current business month is deliberately part of the environment under test (ADR-053; #1108 recorded the posture decision). The serial group excludes test-vs-test contention but NOT the tick, so generation-suite assertions must be tick-tolerant:

  • Never assert global run counters (report.generated == 0 fleet-wide) — the tick, or a concurrent suite’s fresh seed swept up by your own global run, legitimately mints rows. Scope every oracle to a test-owned child. (Exception: report.errors == 0 on a global run is safe ONLY because the fault-arming suites share the same serial group — a child-gated insert fault can never be armed while another group member’s global run sweeps.)

  • Month-window row oracles. Fixture agreements are open-ended, so the tick may mint a current-real-month row for ANY test child between seed and assert. Bound row counts to the months the test exercises (subsidy_generation_lifecycle::live_rows(pool, child, from, until)).

  • Sum generated + already_existed when a test’s fixed month can collide with the current real month — either party may mint first; per-month uniqueness is the property.

  • hold_generation_lease fences multi-step seeding that must not interleave with a tick (the reconcile-drain suites' pattern); 409 AlreadyRunning from a test’s own run is retried as the documented client semantic (run_for_child).

Template pre-warm (#1275, epic &78 M4)

Scratch databases clone from migrated TEMPLATE databases (craig_test_lib::template_db, #1162). Before #1275 the templates were built LAZILY by whichever test hit ensure_template first — under 8-way nextest contention the first battery run after a migration-set change was a rebuild storm and waiters died at the 120 s kill. Now cargo xtask test and validate’s test phase run template_db::prewarm_all BEFORE nextest: every base in the explicit WARMABLE_BASES registry (8 bases over 4 unique migration dirs) is warmed through THE SAME ensure_template path the tests use, the security group arriving as 1 leader apply + 4 Postgres file copies (each unique set applies once). Bounds: 3 min cold total, 1 min per-base warn, per-base timings printed.

Completeness is RUNTIME-ENFORCED, grep-free: ensure_template refuses a base not in WARMABLE_BASES, so a new call site fails its own first run with the registration instruction. Fingerprint parity (runtime dir migrator == embedded sqlx::migrate!()) is pinned per unique dir by the four prewarm_fingerprint_parity_runtime_vs_embedded tests — the warm can never silently produce a template name the tests don’t consume.

The test-plane Postgres instance (#1403)

The checkpoint-storm class. Every DROP DATABASE (and the file-copy CREATE DATABASE … TEMPLATE) forces an IMMEDIATE full checkpoint — cluster-wide, unskippable, serializing all Postgres I/O while it syncs. Run in parallel under nextest, the scratch-DB lifecycle suites (the 8 ADR-063 gate proofs, the keyed-harness template clones, retention/lease/invariant scratch DBs) produced hundreds of forced checkpoints per battery on the ONE devstack instance — starving the LIVE services the api suites talk to (observed 2026-08-11: single-row UPDATEs at 25 s, pool acquires past the 5 s timeout, eight craig-cases::api collateral failures; the full forensics live on #1403). Serialization via nextest test-groups was REJECTED as the fix: bounding test parallelism masks the performance surface instead of removing the artificial aggressor (the no-retries charter’s doctrine — see also #1404, which owns the product-side degradation posture the storm exposed).

The guard. ALL database-lifecycle churn targets the dedicated postgres-test compose service via craig_test_lib::postgres_test_plane_db_url — same devstack/postgres build as the shared instance (init.sql role + pg_trgm parity), but volume-less: the data dir is a tmpfs and the durability knobs are the test trio (fsync=off, synchronous_commit=off, full_page_writes=off), so a forced checkpoint costs memory writes, not fleet I/O. Everything on it is throwaway BY CONTRACT — templates rebuild on the next pre-warm after any recreate. Live-instance READS (asserting what a running service wrote: postgres_test_db_url("craig_<svc>")) stay on the shared instance; the resolver doc-comment carries the boundary. When the test-plane port is absent (a stack from before the service existed), the resolver falls back to the shared instance with a once-per-process warning — shared fate degrades loudly, never silently dials a dead port. Budgets: the shared instance’s 250-connection derivation lost its ~80 scratch pools to postgres-test (its own floor: 150) — both pinned in crates/craig-db/tests/connection_budget.rs.

AMQP establishment stalls (#1783)

The shapes. craig-mq bounds every AMQP establishment by the compiled 15 s AMQP_LIVENESS_TIMEOUT, and an expiry reads as one of these lines:

  • AMQP session build for queue <q> (in <step>) exceeded 15s — a subscription’s session build;

  • AMQP replayer session build for queue <q> exceeded 15s — the parking replayer’s session build, which names no step;

  • AMQP tcp connect exceeded 15s, AMQP amqp handshake exceeded 15s or AMQP connect (amqps fallback) exceeded 15s — connect_owned’s own bounds, reached by every `craig_mq::connect caller, the depth sampler and the connection both session builds open first.

A session build keeps ONE deadline that every step shares, so the step in flight at expiry is the one the line names, and each step points at a different stall:

  • connect — the TCP dial plus the AMQP handshake: the broker’s acceptor or AMQP reader (an acceptor out of fds still completes TCP from the listen backlog but never sends Connection.Start). This step runs connect_owned, whose own 15 s bounds start just after the shared deadline’s. tokio rounds a deadline up to the end of its 1 ms tick and polls the inner future before its own timer, so when both deadlines fall in one tick the inner text wins: a dial stall usually, and a handshake stall after a sub- millisecond dial, surfaces as connect_owned’s own `tcp connect / amqp handshake line, not as (in connect);

  • queue declare + bind and dlq companions — a Khepri Raft commit on the devstack 4.2 broker: one fdatasync per WAL batch. Past the broker’s own 30 s Khepri timeout the same stall surfaces as #1401’s INTERNAL-ERROR … metadata store operation timed out instead (known-issues.adoc);

  • channel open and basic.consume — the broker’s channel path.

Reading the witness. The subscriber_shutdown suite fails a subscription build with an establishment witness (craig_test_lib::amqp_witness). Since #2358 so do the exhausted craig_test_lib::provision_connect panic (#1567) and the craig-composition cache tests' publisher connects (through amqp_witness::connect_failed, which redacts URL credentials). The witness holds a fresh Connection.Start timed from the test process, the management API’s round trip and object totals, each node’s fd_used/fd_total, run queue, alarms and uptime, and host load plus PSI. Every probe is capped at 3 s and runs AFTER the expiry, so read it with that in mind:

  • a slow or unanswered Connection.Start with a fast management API means the broker’s AMQP path is STILL stalled — a stall the #1799 compose probe cannot see (its header-less TCP connect completes from the listen backlog);

  • fast probes mean only that the stall had cleared by probe time: a starved test process and a broker stall that ended before the probe look the same. Read them with the named step, the PSI and the uptime;

  • a high PSI means the host stalled, and a starved host slows these probes too;

  • a short broker uptime at expiry is the #1401 cold-store window after a broker recreation, and reopens the data-dir question below.

Measured (read-only sampler, every 5 s; 2026-10-13, one battery’s e2e leg, 133 samples, host load 1.9–10.0, p50 5.3): fresh Connection.Start p50 1.8 ms, max 4.2 ms (tcp max 3.2 ms); management /api/overview max 6.4 ms; at most 40 broker connections; fd_used peak 110 of fd_total 2048; run queue at most 1; PSI some avg10 peaks cpu 1.84, io 0.22, memory 0. The only sampler errors (4) fell in the leg’s two broker recreations. A healthy build is about four orders of magnitude under the bound: an expiry is a stall, never slowness.

Decided. No test-side budget above 15 s and no nextest serial group: the bound is a liveness floor, deliberately not a knob, and serializing five cheap tests removes no contender (the #1403 doctrine above; #1567: "a [test-groups] serialization does not address broker-wide handshake capacity"). The broker’s data dir stays in the container’s writable layer, not a tmpfs: the live services share this broker, and keeping production durability on the live plane is the maintainer’s call by analogy with the postgres ruling (#1148) — one decision with #1897’s broker lever. Broker tuning reopens only when a witnessed capture attributes a stall to queue declare + bind (or shows a short uptime at expiry), or a measured fd_used peak passes half of fd_total. Recurrences go to #2358, the open owner of this class.

Paused-Time Tests (tokio test-util)

First used by the #784 eval-timeout suite (services/craig-rules/src/engine.rs mod tests). Technique for testing time-dependent behavior with zero sleeps and zero flake surface:

  • Dev-dep tokio = { workspace = true, features = ["test-util"] } (the workspace feature set deliberately omits test-util from production builds).

  • #[tokio::test(start_paused = true)] + tokio::time::advance(…​) drive a virtual clock. Spawn the future under test first and yield_now().await before advancing, so its timers register; a sequential await would silently rely on auto-advance.

  • prop_assert! stringifies its condition into a format string — bind matches! results with { .. } patterns to a bool first.

  • Counter-seam oracle: when asserting "work was NOT done" (e.g. the eval loop skipping dead requests), thread an &AtomicUsize through an _inner variant of the loop — a "the live path still works" assert alone passes even without the guard. Production wraps the inner fn with a write-only local counter (one delegation line, no cfg(test) code).

Failure-path testing helpers

craig_test_lib::concurrent provides spawn-N-await-K helpers for concurrency and race tests. Reach for them whenever a test asserts a property under contention (atomic claim, idempotent retry, capacity bound, transition matrix).

Helper When to use

concurrent_fire_collect(n, builder)

Drop-in spawn-all/await-all. Panics propagate to the test thread.

concurrent_fire_collect_ordered(n, builder)

Need per-task latency, ordered-by-start, or panic-as-data instead of test-thread panic.

concurrent_fire_synchronized(n, builder)

Recommended default for race tests. All N start within one scheduler tick; caller cannot leak the sync point.

concurrent_fire_with_barrier(n, builder)

Need a post-prep, pre-race sync point inside the builder body (e.g. all N pre-fetch state, barrier, then race to UPDATE).

concurrent_fire_until_first_success(n, builder)

Any one Ok suffices (transition-allowed tests, JWT-mutation parametric tests).

concurrent_fire_first_n(n, k, builder)

Exactly K of N succeed (concurrent same-key claim races, capacity races).

// Recommended default — N-way race with no leakable sync point.
// (Same-key convert-class races carry the shared client_request_id in
// the request BODY per ADR-062 §B — the request_claims era.)
let report = concurrent_fire_synchronized(8, |i| async move {
    client.post("/v1/cases/persons", payload_with_request_id(i, key)).await
}).await;
assert_eq!(report.ok_count(), 8, "winner creates; every loser replays 2xx");

// Caller-controlled sync point.
let report = concurrent_fire_with_barrier(4, |i, bar| async move {
    let snapshot = client.read_state().await;   // pre-prep
    bar.wait().await;                           // race start
    client.commit(snapshot, i).await
}).await;

The original concurrent_fire(n, builder) is a deprecated alias for concurrent_fire_collect; new tests should call the new name.

Fault injection

craig_test_lib::fault provides the harness for failure-path tests — the codepath worked under contention; now exercise it under timing, intermittent failure, or back-pressure. Reach for these whenever the test asserts that a recovery / retry / DLX / live-response path actually fires.

Wrapper When to use

LatencyInjector::new(inner).with_pre_delay(d)

Force a real wall-clock stall on the wrapped callsite (e.g. winner stalls 5s so loser ceiling-409s).

IntermittentFlapInjector::new(inner, pattern)

Test retry-with-backoff: pattern [true, true, false] fails twice then recovers.

ConsumerBackpressureInjector::with_ack_delay(d) / .drop_every(n)

Slow-consumer / hung-slot simulation for outbox-depth alarms, DLX surface, /readyz flips.

FaultInjector is the common shape; Attempt records each invocation; ScenarioGuard’s `Drop asserts the wrapped callsite was actually reached (otherwise the test silently "passes" while exercising nothing). Suppress with .disarm() only when the test deliberately skipped the codepath.

let injector = LatencyInjector::new(real_store)
    .with_pre_delay(Duration::from_secs(6));
let report = concurrent_fire_synchronized(2, |_| async {
    client.post("/v1/cases/persons", payload_with_request_id(0, key)).await
}).await;
// Winner stalls inside its claimed tx; the loser's claim statement
// waits on the row lock and classifies as Replay after the commit.

HTTP recording

craig_test_lib::recording (#2701, plan runtime-coverage-matrix D1, D2) records every request the harness sends, one JSONL file per test process. It records; it asserts nothing, and no production code changes.

  • Activation. Every devstack battery (cargo xtask validate, test --integration, test --package <crate> --integration) empties test-results/http/records/ after the C24 record reset and sets CRAIG_TEST__HTTP_RECORD_DIR to it for nextest. The same reset deletes the run manifest (test-results/http/run.json) and both coverage-matrix reports (test-results/http/coverage-matrix.json, target/coverage-matrix.md; #2703). The process recorder exists only when that variable and nextest’s NEXTEST_RUN_ID, NEXTEST_BINARY_ID, NEXTEST_TEST_NAME and NEXTEST_ATTEMPT are all set, so the battery refuses a cargo-nextest older than 0.9.116. A direct cargo nextest run records nothing.

  • What routes through it. Every ServiceClient verb, post_upload_attempt_form, the typed upload clients, download_stream, get_unauthenticated and post_unauthenticated. A raw reqwest call routes through it as recording::send(builder, hint).await in place of builder.send().await: same result, same reqwest::Error. An in-process server registers itself with recording::register_origin(&base_url, "craig-<service>") once it binds (#2702 adds those calls); until then its requests record svc: null.

  • The key hint. CridHint::FromBody reads a JSON body’s top-level client_request_id, Known(id) names a multipart form’s, and None records none. ServiceClient::post_multipart takes the caller’s hint.

  • The file. <dir>/<uuid-v7>.jsonl. Its first line is {v: 1, run_id, binary_id, test, attempt}, then one line per request: {svc, method, path, status, crid, t0_us, t1_us, armed, replayed}. svc is the service registered for the origin (the nine matrix services' TestConfig URLs are pre-registered; intake’s three URLs are craig-intake), else null. path has no query string. status is null when no response arrived. The times are wall-clock µs. replayed is the response’s Idempotent-Replayed: true (request_claims::IDEMPOTENT_REPLAYED). RecordHeader, HttpRecord, parse_line and read_file read a file back; a bad line is named file:line.

  • The arm window. armed is craig_fault_core::window::armed() when the request starts: true while any ArmWindow in the process is open. PgFaultArmer holds one from arm to finish / disarm. ToxiproxyClient holds one while any added toxic or disabled proxy is live (one window for the whole set), released when the last toxic is removed, proxy re-enabled or proxy deleted. arm_stage_fault’s guard holds one. `OpCountdown and PreSendInjector hold one while failures remain. s2s_stub::spawn_fault_server opens one for the rest of the process. A new armer opens an ArmWindow (ArmWindow::open_for_process() if it never disarms).

  • Failure. A record directory or file that cannot be created or written panics, naming the path.

  • Who reads it. The full battery’s run manifest and coverage-matrix steps (Coverage Matrix).

Multi-replica testing

craig_test_lib::multi_replica::MultiReplicaCluster is the C20 (epic &83 / #1515) dedicated cluster rig: it runs the SELF-CONTAINED docker-compose.cluster.yml (craig-financial ×2 + craig-composition ×1 since #1539 + its own postgres/rabbitmq/keycloak + the per-service ADR-063 migrate gates; zero fixed host-port publishes; resource limits) under a unique craig-cluster-{run} project — never the devstack compose pair the original design reused. Use it only when a test needs two real OS processes contending on shared infra: kill legs, lease-release-by-socket-death, competing-consumer failover.

The NORMAL entry point is the stage, not the builder:

$ cargo xtask cluster-tests    # sweep → build → up --wait → legs → artifacts → down -v

The stage owns the lifecycle (signal-safe: Ctrl-C tears the project down) and exports CRAIG_CLUSTER_PROJECT; the kill legs in crates/craig-test-lib/tests/multi_replica.rs attach to it via MultiReplicaCluster::attach. Every test in that file is a leg of the cluster plane (§ Opt-in planes): #[ignore = "requires cluster-tests rig"], selected only by the stage’s --profile cluster --run-ignored only, and a kill leg run without CRAIG_CLUSTER_PROJECT fails loud. The rig’s guard-rail unit tests live in tests/multi_replica_guards.rs, which the battery runs. OUT-OF-BAND ONLY: the weekly CI schedule ("Weekly main", pipeline schedule 4540282: Mondays 06:00 America/New_York on main, with CLUSTER_TESTS=true and POLICY_DRIFT=true; the project’s only schedule, since bare-schedule jobs co-fire on any schedule, #2651), the cluster-tests MR label, or manual — never the per-push battery (plan F1/L10). Artifacts land in test-results/cluster/.

The self-managing path (cluster_lifecycle_smoke) runs inside the same stage since #2567: it brings up a second rig for ~1-2 min and builds its postgres / rabbitmq / keycloak images from cache. It has a best-effort Drop teardown so a panicking run does not leak the project; a stale craig-cluster-* leak from a killed run is reaped by the next stage run’s sweep:

let mut cluster = MultiReplicaCluster::builder()
    .replica("craig-financial", 2)
    .build();
cluster.start().await?;   // up -d --wait: returning Ok IS readiness
let urls = cluster.replica_urls("craig-financial", 8005).await?;
cluster.stop().await?;

Tests that don’t need multi-replica should continue using the existing TestHarness against the global single-instance devstack. (The middleware-era §D3.8 multi-replica idempotency verification retired with the middleware in B2 #1194; the three C19 worker kill-leg oracles land on this rig as #1539.)

Named scenarios live in craig_test_lib::fault::scenarios::* — prefer them over open-coding (bp_scenarios::steady_50ms() over BackpressureScenario::Steady { ack_delay: Duration::from_millis(50) }). The base injectors land per the ADR-067 §D7 disposition (superseding the plan §D2.0a roster): the statement-boundary faults are served by pg_armer::PgFaultArmer (§D5); the publish-fault split — a stage_event StageFault (craig_mq::fault::arm_stage_fault) + a Publisher pre-send injector (craig_mq::fault::PreSendInjector) — lives in craig-mq under its default-off fault-injection feature (§D6, epic &83 C7), re-exported as craig_test_lib::fault::mq; the confirm-latency injector (craig_mq::fault::ConfirmLatencyInjector, ADR-067 Amendment #2593) sits beside them under the same feature, imported from craig_mq::fault; CipherErrorInjector (C8) and ObjectStoreErrorInjector (C9) land under their host crates' features. RabbitDownInjector was RETIRED, not built (§D7) — one abstraction cannot express both a graceful AMQP close (L1) and a TCP reset (L2), which are the Toxiproxy legs.

Background-job seams (plan background-jobs D3 / D8; #1933–#1940)

The eight backgrounded engines (ADR-068 § Amendment — #1571) are tested through TWO seams — never a sleep:

  • The wire half — craig_test_lib::jobs, FREE functions (ServiceClient sits at the F-054 sixteen-method ceiling): enqueue(client, path, body) is the ONE place a test reads a response header (the 202’s Location); job_path(service, id) and wait_for_job(client, service, id) poll the generic read-only GET /v1/<svc>/jobs/{id} every POLL_INTERVAL (2 s — the CLI’s and the web fragment’s cadence) under eventually::JOB_COMPLETION and fail LOUDLY with the last JobView, so a hung executor reads as a failed test, never a slow one. A devstack-gated API leg POSTs { client_request_id, … }, asserts the 202, polls to terminal and decodes the kind’s typed result (FinalizeReport, PreviewSweepResult, the GenerationReport, the NCANDS submission); the synchronous oracles — authz, the consent gates, forged fields → 422 validation-failed, a fresh id while one is active → 409 job-already-active — are asserted with no claim row left behind.

  • The executor half — JobsRuntime::drain_pending() (crates/craig-api/src/jobs/runtime.rs), the ONE test seam (plan D3): it runs every queued row this instance owns to terminal on the caller’s task, serially, permits and lease slots ignored, and returns a DrainReport: terminal (how many reached a terminal state; the report compares equal to that count, so assert_eq!(drained, 1) prints the whole report when it fails), parked (each row it stopped visiting short of terminal, with its ParkReason — start CAS missed, start failed, reclassified, waiting for lease, lost CAS, write failed; a waiting_for_lease row stays queued) and scan_error. A test whose next act would panic on a stalled drain (a fresh-id enqueue’s expect, a read of the terminal job’s rows) asserts the drain first (#2096). A row stamped with a foreign owner is reached through classify_stale first — adoption, exactly as in production.

  • The hermetic scratch-base pattern (lifted from the placement pilot — B8, one copy): the suite builds the REAL kind on a test JobsRuntime over the service’s pre-warmed scratch base (craig_test_lib::template_db::scratch_db with the crate’s own MIGRATOR — no devstack executor in the loop) and drives it with the toolkit’s second half: JobSeed + insert_queued / insert_running seed a row exactly as a dead replica would have left it, aged(secs) is the clock, view projects through the substrate’s own into_view, owner_version is the adoption CAS witness, wait_until(budget, what, probe) the bounded poll, lease_pid the session-lease backend lookup, and ConsentProbeKind / FailingKind the two probe kinds the recovery matrix needs (a consent kind that must never run; a proof-less kind whose every attempt is an engine failure). The suites: placement tests/expiry_sweep.rs, security tests/archive_engine.rs, rules and reporting in-module (src/jobs.rs), exchange in-module (src/jobs/tests.rs, on the collection tests' rig: a stub partner and a stub craig-placement, #3190), financial’s three binaries (tests/background_jobs.rs — the per-service READ-policy pin — tests/import_finalize_jobs.rs, tests/sweep_execute_jobs.rs).

  • The covered-anchor legs. Each executor is a PROMOTED contested worker anchor (ADR-067): worker.craig-placement.lib.watch.4, worker.craig-security.lib.watch.3, worker.craig-rules.main.watch.3, worker.craig-reporting.main.watch.3, worker.craig-financial.main.watch.3, worker.craig-exchange.main.watch.4 (#3190; its drain legs are the_collection_job_executor_drains_promptly_on_cancel and, with an attempt in flight, an_interrupted_run_is_recorded_and_its_rerun_completes; the collection schedule beside it is worker.craig-exchange.main.watch_optional.5, with a drain leg and a crash leg in src/collections/schedule_tests.rs) — each with its *background_jobs_executor_drains_promptly_on_cancel drain leg and a native crash leg (a stale running row + a second JobsRuntime’s scan → attempt `crash; a convergent kind re-queues and converges, a consent kind ends failed with its consented run / finalizing batch intact), recording a FaultRecord under the anchor id so the C24 gate counts it.

  • Serial groups. The jobs suites ride the engine leases' nextest groups (.config/nextest.toml, all three profile blocks): financial’s background_jobs:: / background_jobs_drain_tests:: / subsidy_import_jobs:: / subsidy_sweep_jobs:: and the three hermetic binaries in subsidy-generation-lease; placement’s in placement-expiry-lease; reporting’s in reporting-ncands-jobs — the per-kind arbiter and the engine leases are exclusivity UNDER TEST, so serializing exercises their real semantics instead of masking contention with retries.

  • The engine thread (#2169). The supervisor runs every engine future on its own blocking-pool thread (spawn_engine, crates/craig-api/src/jobs/attempt.rs), so a long synchronous section never leaves the runtime’s IO/time driver unattended. Its pins live beside supervise: the cadence legs (no beat gap over twice heartbeat_interval across a section of stale_after / 2, on both runtime flavors, with a recording clock and a pool that fails fast instead of a database), the abort, panic and log-capture legs. The engine carries the caller’s tracing dispatcher, so a thread-scoped capture_logs still sees it. A job test cannot use paused time (a blocking task stops the paused clock’s auto-advance).

Eventual-consistency polls (#2927, #2928)

A test that waits on something asynchronous polls through craig_test_lib::eventually::eventually(budget, what, probe), which probes every 500 ms until the probe answers Some and panics naming what and the budget once it is spent; eventually_every(budget, every, what, probe) takes its own cadence for an observation 500 ms could step over (a job seen running, a session parked behind a lock for a moment). The budget names the kind of wait:

Budget Limit Covers, and how it was sized

AUDIT_DELIVERY

100 s

craig-security’s audit row for a published event. Measured on the 2026-11-06 battery: audit lag up to 62.8 s while every outbox row published within 2.1 s.

EVENT_DELIVERY

75 s

A bus event consumed: a handler’s effect, an inbox row processed, another service’s projection row, a queue reaching or draining a depth. The longest current window among its sites (craig-mq’s burst floods); no measurement beyond audit’s.

JOB_COMPLETION

100 s

A background job or worker pass finished (background_jobs terminal, a send job or transaction out of pending, an archive, purge or sweep run). `jobs::wait_for_job’s old 120 s ceiling equalled the nextest kill and so never fired first; 100 s is the longest the envelope admits with audit’s margin.

LEASE_OR_LOCK

60 s

A lock or lease state the test arranged: a session parked behind a blocker, an advisory lease acquired or freed, a job in its waiting-for-lease phase. The longest current window among its sites.

SERVICE_READINESS

90 s

A dependency up or reattached: a control API answering, a consumer attached or detached, a consume session rebuilt. Sized like fault::mq_sever::RECONNECT_DEADLINE: three of craig-mq’s 30 s reconnect-backoff caps.

STATE_PROPAGATION

60 s

In-process or cached state catching up: an authz or decision cache refresh, a ruleset reload, a log line, a metric, a spawned task’s flag, a worker directory entry. The longest current window among its sites.

Every budget in eventually::ALL must stay below nextest’s kill (slow-timeout period × terminate-after in .config/nextest.toml, the smallest over the battery’s profiles) less 15 s of setup: the unit test every_budget_fits_inside_the_nextest_kill_envelope reads the file and fails when either side moves past the other. A test that must clean up before it asserts runs the poll on its own task and re-raises the panic after cleanup (eventually::panic_text turns the task’s JoinError into the panic’s text for that report). The hermetic jobs::wait_until(budget, what, probe) wraps eventually_every at 50 ms under the caller’s own budget.

A helper whose caller needs the failure’s value instead of a panic polls through eventually::poll_within(budget, every, probe): the probe answers ControlFlow::Break(value) when done and ControlFlow::Continue(last) otherwise, and a spent budget returns the last Continue payload as Err. jobs::wait_for_job uses it under JOB_COMPLETION and still answers Err with the last JobView; concurrent::wait_for_blocked_behind, EventCollector::wait_for_event, RabbitMgmt::{consumer_connection, await_depth} and case_assignments::wait_case_assignment use it under their caller’s Duration, wrapped in a Budget named for the helper, until every caller names a class budget instead.

A sleep that deliberately lets time pass (a TTL, a backoff under test, a retry’s backoff, a scripted pause) is not a poll and stays a sleep; inside a loop it carries // deliberate sleep: <reason> on its own line or the line above.

cargo xtask lints no-sleep-polls, a blocking step of cargo xtask validate that --profile fast and the car run too, holds the suite to this. A syn walk over every .rs under the lint roots refuses a call whose path ends sleep or sleep_until inside a loop, while or for body, read up to the nearest fn or closure, in test code. Test code means tests/ trees, craig-test-lib’s src/, #![cfg(test)] files, files a cfg(test) mod x; mounts, and cfg(test) items and inline mod tests elsewhere. A macro body is read as tokens, so a sleep in a select! arm inside a loop counts. The marker passes a site when it sits on the sleep’s line or the line directly above, with a non-empty reason. A marker with no reason, or with no sleep call on its line or the next, is itself a finding, so markers cannot go stale. crates/craig-test-lib/src/eventually.rs is the one exempt file. There is no baseline and no allowlist. Straight-line sleeps are out of scope.

Streaming downloads (plan streaming-downloads D5 / D6; #1946–#1947)

A streamed download (ADR-068 § Amendment — #1572) is pinned at FOUR levels, each proving what only it can — never with a sleep, never against a product timeout:

  • STORE — infrastructure-free (crates/craig-store/tests/get_stream.rs over craig_test_lib::store_double::OnDemandStore, the full ObjectStore trait producing frames ON DEMAND): nothing is read before the body’s first poll and N polls produce exactly N frames (range_reads_are_zero_after_get_stream_returns_and_before_the_first_poll, n_polls_produce_exactly_n_frames_across_chunk_boundaries); frames forwarded unmerged; the exact emitted prefix on an error at frame k; if_match == e_tag on every chunk; a foreign overwrite’s Precondition ends the body; the chunk_ranges tiling proptest; chunk concatenation == get to 40 MiB; two concurrent streams byte-exact. The double’s seams: insert / e_tag_of, hold_frame(k) / release() / fail_at_frame(k), and the counters produced_frames / produced_bytes / range_reads / get_calls / if_match_seen.

  • HELPER — hermetic on the wire (crates/craig-api/tests/download_response.rs: a real axum router over Store::from_parts(Arc::new(OnDemandStore), ..) on an ephemeral TcpListener, no devstack): the head carries length / type / disposition / no-store before any body read; the first frame reaches the client BEFORE the double produced the last (hold_frame + release); the three outcome deltas (completed / failed / abandoned) through the OTel → Prometheus bridge, each exactly once; a stream error after the head truncates and the client’s read errors; the compression exemption with its gzip control; the #1953 correlation pins through request_span_layers under capture_logs (the failure line carries the inbound or minted request_id the response echoed, an oversized inbound id never reaches it, and under tower_http=debug the id rides the parent span).

  • ROUTE — devstack-gated (services/craig-cases/tests/api/attachments_streaming.rs, the keyed harness on from_parts(OnDemandStore); every leg #[ignore = "requires devstack"]): head before the first frame with the release GATED on the client; a slow reader bounds the producer lead to one chunk + buffers over a 256 MiB logical object; HEAD → headers, empty body, zero range reads; the REAL DELETE mid-download ends the body short and the next GET is 404; 404 at head(); the fleet 403 before any store access; the Garage 64 MiB leg. Header assertions on all eight backend routes use craig_test_lib::download_stream(&ServiceClient, path) → DownloadHead { status, headers, response } (a bearer client WITHOUT a total timeout; the body left UNREAD — pull frames with response.chunk().await; portal_subject::download_stream_as_portal_subject for the two-token channel), never get_bytes, which discards headers.

  • EDGE — per route, in-process (craig-web ×4, craig-portal, intake; the budget legs once per edge crate) over craig_test_lib::hold_release_upstream — a real axum upstream on 127.0.0.1:0 whose body a DownloadPlan feeds from a channel: DownloadPlan::attachment(ct, filename, body) sends the head + Content-Length + the FIRST half, parks at Step::Hold, and sends the rest on HoldReleaseUpstream::release(); drip(ct, filename, &frame, count, every) sends frames on a cadence; refusal(status, body) is a buffered non-2xx; with_steps / with_header shape the rest. A route test drives the router in-process and polls the response body FRAME BY FRAME (http_body_util::BodyExt::frame in craig-web; std::future::poll_fn + HttpBody::poll_frame, the same primitive, in the portal and intake): the first downstream frame is read while upstream.wait_until_held() proves the second half is still parked — a route that buffers cannot pass — then release() and drain to byte equality; Content-Length == N, Content-Type, Content-Disposition and Cache-Control: no-store are asserted forwarded, and the non-2xx arm rides the route’s existing oracle (refusal). The budget legs build the edge’s second client with craig_common::http::build_streaming_client_with_idle(name, ver, Duration::from_millis(500)): an attachment plan never released ends the body with an error frame ≈ 500 ms after the head; a drip of 300 ms frames for 2 s completes (idle resets per frame — no total). The BFF transport’s own legs (crates/craig-bff/src/transport.rs; wiremock for the head, the fixture for the body): get_stream_hands_back_5xx_as_data_not_error, get_stream_head_timeout_is_transport_error (the http_client sample AND the untyped class, via the test-only with_head_budget), get_stream_body_stall_ends_at_read_timeout, get_stream_short_stall_recovers, get_stream_progressing_stream_completes_without_total.

The injected-budget rule. Every budget a streaming test exercises is INJECTED small (_with_idle 500 ms, with_head_budget, a hermetic ObjectStoreConfig with its own request_timeout_secs) — never a product timeout: nextest terminates a test at 120 s (slow-timeout 60 s × 2), which is exactly DOWNLOAD_IDLE_BUDGET. The class pin is every_extended_row_is_a_post in each of the five ceiling_table_tests (cases, placement, exchange, reporting, intake): the one-directional coverage guard cannot pin a deleted row; this test can.

Mock-server harness (spawn_for_test)

craig_mock_server::spawn_for_test() is the ephemeral-port mock-server harness, at tools/craig-mock-server/src/lib.rs. It mounts no partner (no build compiles one in, ADR-090): it serves the broker and craig-cases stand-ins, capture and the control surface. A partner crate’s tests hand their own mock to spawn_for_routes and get the same host around it, nested at /partner/<kind>.

pub async fn spawn_for_test() -> Result<MockServerHandle, std::io::Error>;
pub async fn spawn_for_routes(
    routes: Vec<(&'static str, craig_state_bundle::MockRouteFactory)>,
    opts: MockServerOptions,
) -> Result<MockServerHandle, std::io::Error>;

impl MockServerHandle {
    pub fn base_url(&self) -> &str;  // e.g. "http://127.0.0.1:54321"
}
impl Drop for MockServerHandle { /* aborts the spawned task */ }

It binds a TcpListener to 127.0.0.1:0 (so parallel test runs never collide on a port), spawns axum::serve in a tokio task, and returns a handle whose Drop aborts that task — the server lives until the test drops the handle. The reference partner’s tests are the consumer to copy (crates/craig-partner-testonia-registry/tests/kit/native.rs):

let routes = vec![(KIND, Arc::new(mock::routes) as craig_state_bundle::MockRouteFactory)];
let server = spawn_for_routes(routes, MockServerOptions::default()).await.expect("spawn the host");
let url = format!("{}/partner/{KIND}", server.base_url());

The consumer crate needs craig-mock-server plus tokio (rt, macros, rt-multi-thread) in [dev-dependencies]. A partner’s mock module exposes a routes() → MockRoutes (its router, and its simulator when it has one) with a typed POST / (Json<Adapter::Outbound> in, Json<Adapter::Inbound> out) and HEAD|GET /health for test_connectivity() probes. It is strictly a test harness — never spawn it in a production path; the cargo run -p craig-mock-server bin target is for devstack only.

For a partner crate the legs themselves are shared: crates/craig-partner-test-harness (836) defines accepted_round_trip / rejected_via_sentinel / connectivity / the StubTransport byte-identity proof / the #1460 bounded body / the ADR-067 fault_leg triple / the #779 erased refusal ONCE, generic over PartnerUnderTest; a crate’s tests/round_trip.rs is its fixtures, one impl PartnerUnderTest, and one [tokio::test] per leg (spawning the mock as above and passing server.base_url()) under the test NAME the contested-surfaces registry pins. Adding a partner crate = the fixture + the impl + the named tests; a new leg for every partner crate = one fn in the harness.

The harness is the conformance kit of the partner specification (#3196, Writing a partner crate). Beside the manual-send legs above it holds the checks of a triggered-send leg (leg), of a partner simulator (simulator), of a partner set (set) and of an inquiry (inquiry), and its own tests show each check failing on a leg, a simulator or an inquiry built with the matching flaw. The reference partner, crates/craig-partner-testonia-registry, runs all of them. No build of the mock server compiles a mock in, so its tests use craig_mock_server::spawn_for_routes(routes, opts): the host (the /partner/<kind> nesting, the control surface, fault injection, capture) over a list of routes the caller hands it.

craig-exchange’s own unit tests of the trigger machinery (admission, the resolve passes, the listing gates, the acts, the credential gate, the seeded contention suite) drive the reference partner’s legs, never a jurisdiction’s: triggers/test_support.rs names them (Leg::STAGE_OPENED, Leg::RESIDENCE_OPENED, …), boots the fixture layer over the reference set (reference_registries()) and serves its simulator behind that same host (spawn_reference_partner). The simulator is a closed world, so a rig tells it of each person a record is sent for. A jurisdiction’s own leg rules are tested in its partner crate, beside the rules.

No test outside a jurisdiction’s partner crates links one (#3200, ADR-090), so those crates can live in the jurisdiction’s configuration layer. A test went one of three ways:

  • A test of the product’s machinery runs on the reference partner. craig-exchange’s unit tests (the registries a boot builds, membership, the reserved collection type, the outbound credential on the wire), the mock server’s (mounting, the credential check) and craig-test-lib’s simulator client each boot the fixture layer over the reference set or stand up a partner of their own. The SSA worker suite (services/craig-exchange/tests/api/ssa_worker.rs) asks the reference partner’s benefit desk through its built module, granted the standing the module reports (PartnerModules::partner_set_as_reported(), the host’s test-only stand-in-sources); its worker with no authority holds the set a boot takes (partner_set()). The devstack’s partner rows are of the kinds its deployment registers, so the suite’s row is of the deployment’s SSA kind and the desk answers under that name.

  • A devstack test of the running deployment stays and states the jurisdiction’s payloads as JSON. The devstack runs Georgia’s deployment, so the outbound-trigger suites read what its partners received: tests/api/outbound_triggers/georgia_wire.rs names the fields a test reads or writes, by the wire’s own keys, with the wire’s tokens as text. A field the wire always carries is required there, so a body without it fails the decode; one the wire may leave out is optional, as on the wire.

  • A pin of a jurisdiction’s own set, and a test of its wire or rules, is the jurisdiction’s. Georgia’s are in its configuration repository, beside its partner code, where they run on the layer’s built modules (partners/src/set/tests/the_set.rs and each crate’s own tests). What this repository holds of a pinned layer is that its modules load and boot its configuration (every_pinned_layers_modules_load), that none is granted send authority (no_pinned_layer_claims_send_authority), that its committed modules are their source (cargo xtask partners check --pinned, a battery step), and that Georgia’s manifest seeds the seven mock partner rows the seed’s pinned bytes are built over (the_locked_georgia_layer_seeds_the_pinned_mock_partners).

The fixture modules (#3200)

The tests of craig-partner-host, of the reference partner and of craig-exchange’s boot load WebAssembly modules built from crates/craig-partner-host/tests/modules/ (Partner modules says what each is for). Nothing built is committed, so they are built before the tests that load them:

cargo xtask partners build --fixtures      # into target/partner-fixtures/
cargo nextest run -p craig-partner-host

cargo xtask test, cargo xtask validate --profile fast, cargo xtask test --unit and the battery each run the build themselves, as a step of their own before nextest. A test that finds no built module panics with that command. craig_test_lib::partner_fixtures reads them for a test: built_module, manifest_text, and reference_layer(), a copy of the fixture jurisdiction’s layer that also holds the reference partner’s modules, since the fixture layer itself holds no partners/. The build is cargo’s, so a second run with nothing changed takes a second; after an edit to the SDK, the contract or a fixture, run it again before the host’s tests, or they load the old modules.

The fixtures are built with the workspace’s toolchain against the versions the workspace locks: each fixture’s Cargo.lock is a copy of the root one, which cargo trims, and is ignored by git.

Partner simulators (#3187)

A partner mock that keeps state is a partner simulator: a stand-in for one partner system that answers about a person only from the records it holds. It is a closed world. A request about a person it does not hold gets the partner’s own "not known" answer, where a stateless mock accepts anything. A simulator derives its records from the people it is given, by its own rule, so the same people always make the same partner world. Mocks become simulators one partner at a time (the plan, rule R1); a mock that has not been converted answers as before and carries no simulator.

A partner’s mock hands the host its simulator beside its router (craig_partner_sdk::MockRoutes, PartnerSimulator), and craig-mock-server serves the control surface that loads every simulator it holds: the ones in the partner modules of the configuration layers it is given (Partner modules), and in a partner crate’s tests the one that crate hands it:

Route What it does

PUT /_sim/people

Replaces the world: every simulator forgets what it holds, then loads the people in the body.

POST /_sim/people

Adds the people in the body to the world that is there. A test adds its own family this way.

POST /_sim/reload

Replaces the world with the people file the host was started with (MOCK_PEOPLE_FILE). 409 with no file configured; 500, naming the file and the cause, when it cannot be read or parsed, and the world is left as it was.

POST /_sim/partners/{kind}/run

For a simulator whose partner calls CRAIG (#3193, a return): makes every call the simulator says is due, to the return listener (MOCK_RETURNS_LISTENER) over mutual TLS with that simulator’s client certificate, hands each answer back to the simulator, and answers {"calls": [{"leg": …, "status": …}]}. status is null for a call that got no answer (the listener was not reached, or refused the handshake); the simulator is then told nothing and the call stays due. 404 for a kind with no simulator that makes calls; 409 when the host was started with no listener to call; 500, naming the file, when the simulator’s certificate cannot be read.

GET /_sim/partners/{kind}/caller-certificate

That simulator’s client certificate, PEM, which a test registers in craig-security as the partner’s. The key is never served. Refuses as the run does.

The caller’s certificates are development ones: craig-mock-server pki --out <dir> writes a development authority, the listener’s certificate and one client certificate per simulator that makes calls, and keeps what the directory already holds, so a certificate a test registered survives a restart (the devstack’s returns-pki volume). The same authority is a library (craig_mock_server::pki), which the return listener’s own suite issues its certificates from.

Each answers {"people": n, "simulators": m}: the people offered and the simulators that received them. A person is a SimPerson (person_id, first_name, last_name, date_of_birth, optional sex, identifiers by kind token) under the length caps CRAIG’s own person and identifier wires carry; an unknown field, or a person over a cap, is a 422 naming the person’s position and the field, and nothing loads. The people file is held to the same caps. A partner’s own control routes (set one person’s situation, run its scheduled work, read what it holds) live in its router under /partner/<kind>/_sim/…. Control traffic is not recorded by /_capture.

The people come from the seed. craig-seed --partner-people <path> writes one SimPerson for every seeded person who carries an identifier, in person-id order, from the same generated data as the SQL (so it moves no SQL byte and no seed identity). In the devstack, seed.sh writes it to the partner-sim volume and, once the databases are loaded, calls POST /_sim/reload; a refusal fails the seed. The mock server reads the same file at boot, so a restarted container knows the seeded people again. What a simulator accumulated since (a test’s own people, lists, sent answers) does not survive a restart: a restart ends a run’s partner state.

A test only ever adds people on the shared devstack. Replacing the world would take every other test’s people with it, so the clients offer no replace and no reload: craig_test_lib::partner_sim::PartnerSim (Rust, PartnerSim::devstack().add_people(&[…])) and the partnerSim fixture of tests/e2e/lib/partner-sim.ts (Playwright, partnerSim.addPeople([…]), on the given library’s test). Both clients also reach a partner’s own control routes: partner_put, partner_post, partner_get and partner_delete in Rust; partnerPut, partnerPost and partnerGet in Playwright, whose failures name only a route’s first segment, since a partner keys a person’s routes on an identifier. An in-process server starts with its people through MockServerOptions::with_people. The surface is unauthenticated and exists only in craig-mock-server, which publishes no host port and is never deployed.

The DOE simulator

Georgia’s Department of Education (doe_slds) is the first simulator (mock::DoeSimulator in Georgia’s craig-partner-doe-slds, in its configuration layer’s partners/src; the devstack’s mock server runs it from the layer’s simulators module). It holds three things, keyed by GTID:

  • Students. A loaded person with a gtid identifier and of school age (five to eighteen) is a student, except one in twenty, who is not enrolled in a Georgia public school. The school system comes from a table of four fictional ones, and the school and grade follow from the age. Every draw depends only on the person’s id, so the same people make the same students.

  • The custody list. POST /partner/doe_slds is the custody-list wire CRAIG sends. An entry that fails validation is a 422. An entry for a GTID that is no student answers ERR, which craig-exchange settles partner-rejected. An INC lists the child, keeping the entry’s person, case and stage ids; an OUC or an RMV unlists; each answers SNT.

  • The weekly file. GET /partner/doe_slds/weekly serves the first page (DoeSldsWeeklyPage) of the latest file, or 204 before the first batch; GET /partner/doe_slds/weekly?file_id=…&page=… serves a later page of that file. The file holds one DoeSldsStudentRecord for every listed child who is a student, the whole list each time, at most 1,000 to a page. A page of a file a later batch has replaced is a 409, so a reader never joins two files, and a page the file does not have is a 404. The record carries four facts of the specification’s "Current School Information" (school, district, grade, school entry date); its JSON is CRAIG’s own (the specification lists the page’s fields and gives no file layout).

Its control routes, under /partner/doe_slds/_sim/:

Route What it does

PUT students/{gtid}

DOE knows this student, with the body’s facts (school, district, grade, school entry date). 204.

DELETE students/{gtid}

DOE no longer knows the student; the listing goes with it. 204.

POST batches/weekly/run

Produces this week’s file now. Answers the file’s id, its date and its record count.

GET custody-list/{gtid}

The child’s listing (the person, case and stage ids of the INC), or 404.

A test that needs DOE to accept a child’s GTID states the student first: the devstack suite’s known_student (services/craig-exchange/tests/api/outbound_triggers/doe_slds.rs), or PartnerSim::partner_put("doe_slds", "students/<gtid>", &student). A GTID no one stated is refused, which is its own test (a_gtid_doe_does_not_know_settles_partner_rejected).

The EMPI simulator

Georgia’s person index, the EMPI (empi), is the second simulator (mock::EmpiSimulator in Georgia’s craig-partner-empi, #3192). It holds clients, keyed by the EMPI’s nine-digit client id:

  • A loaded person who carries a nine-digit empi identifier is in the index under it.

  • A find (POST /partner/empi/match) answers the clients whose first and last names are the request’s, without regard to case, and whose date of birth is the request’s when it carries one. A client scores by its standing, which a test sets: known 100, near 90 to 99, weak 50 to 89. A person is known until a test says otherwise.

  • A registration (POST /partner/empi) creates a client under an id drawn from the person’s id (from the names and the date of birth, for a person the simulator was not given), who is known from then on. The same registration sent twice answers the same id.

  • A participation (POST /partner/empi/update) is noted for a client the index holds and refused for an id it does not.

Its control routes, under /partner/empi/_sim/:

Route What it does

PUT people/{person_id}/standing

The loaded person matches this well from now on: the body is {"standing": "known"}, "near" or "weak". 204, or 404 when the index holds no loaded person of that id.

GET clients/{client_id}

What the index holds under the id: the person id, how the client came to be there (loaded or registered), its standing and score, and the person id a participation named. 404 when it holds no one there.

craig-exchange asks the index through the deployment’s one active empi partner row, under that row’s active agreement, and the devstack seeds the row with no agreement linked. A test that asks the index claims the slot first: craig_test_lib::person_index_slot::claim parks the seeded row, installs a partner and an agreement of the test’s own at the seeded row’s endpoint, and restores the seeded row when the test ends. Tests that claim it run one at a time (the person-index-slot group of .config/nextest.toml). A test puts its own person into the index with craig_test_lib::person_index_sim::index_holds (at a standing) and reads what the index holds afterwards with held_under. The suites are services/craig-exchange/tests/api/person_index.rs (the three exchange routes) and services/craig-cases/tests/api/person_index_conversation.rs and person_index_concurrent.rs (the conversation, against Georgia’s real choice ruleset). Two of the conversation tests put a second person of the child’s name and date of birth into the index, so that an ask answers two records: a weak record beside a near or a sure one is shown and may not be selected, and selecting it is refused before the index is told. A test with one record cannot show that, since the best record is selectable under any floor. The conversation’s refusals are tested in process, with doubles of craig-exchange and craig-rules that count what reached them (services/craig-cases/src/api/person_index/tests.rs).

The IES simulator

Georgia’s medical-assistance system, IES (ies), is the third simulator (in Georgia’s craig-partner-ies, #3193). It is the first whose partner calls CRAIG, so it has both sides of the Medicaid referral (a referral leg and a return):

  • A loaded person who carries an empi identifier is a client under it. A referral about anyone else is answered "mandatory fields not received" with no application number, which the referral leg reads as rejected: no receipt reaches the application. So an application another test submits is never taken by the simulator.

  • A referral (POST /partner/ies) is held under the client id and answered with a ten-digit application number; the same referral sent again gets the same number.

  • The decision is approved unless a test says otherwise, with a Medicaid id drawn from the person’s id.

  • Its scheduled work is one SOAP 1.2 call to the return leg referral_status, holding every referral whose outcome CRAIG has not taken. POST /_sim/partners/ies/run on the mock server makes it. An outcome CRAIG answered as unknown or failed, and any call that was refused, stays due: a later run sends it again, so a call a test triggers may also carry what the simulator still owes an earlier test.

Its control routes, under /partner/ies/_sim/:

Route What it does

PUT people/{person_id}/outcome

What the simulator decides for that person from now on: the body is {"outcome": "pending"}, "approved", "denied" or "closed". Their applications are due again. 204, or 404 for a person it was not loaded with.

GET people/{person_id}

What it holds for the person: the client id, the decision, and each referral with its application number and whether CRAIG took its outcome. 404 when it holds no one there.

A call is admitted only for a registered and approved certificate whose partner is named as the caller of the interface’s one active partner row, under that row’s agreement; the devstack seeds none of that. A test claims the return slot first: craig_test_lib::returns_slot::claim registers and approves the simulator’s certificate (GET /_sim/partners/ies/caller-certificate) against a craig-security partner of its own, parks the seeded ies row, installs a partner row at the seeded row’s endpoint that names that caller and has an admitting agreement, and undoes all of it when the test ends (it revokes the registrations it made, by their label, so the next claim can register the certificate again). The same row is the one a referral is sent through. Tests that claim it run one at a time (the returns-partner-slot group of .config/nextest.toml). A test tells the simulator of its own child with returns_slot::simulator_knows before it submits the application, runs the partner’s calls with PartnerSim::run_calls, reads what the simulator holds with returns_slot::simulator_holds, and asserts on its own application only. The child’s first and last names must each fit in thirty characters, the width of the referral’s name fields: Georgia’s leg refuses to assemble a longer one, the record ends payload-invalid, and nothing is sent. The names PersonBuilder draws are longer than that, so the suite names its children itself.

The suite is services/craig-cases/tests/api/medicaid_referral.rs:

  • the referral, its receipt (the simulator’s application number), the approved outcome and then the denied one;

  • an application of a child the simulator does not hold, which ends rejected by the partner with no receipt;

  • an outcome CRAIG cannot place (the child’s EMPI retracted), which stays due and lands on a later call once the child holds the EMPI again;

  • the call recorded in craig-exchange as a return transaction;

  • a revoked certificate, and a caller whose partner was removed, each refused with the outcome still due.

Property tests

proptest is a workspace dev-dep; opt in per crate via [dev-dependencies] proptest = { workspace = true }. Properties live under <crate>/tests/properties/<property>.rs with a tests/properties.rs module-index file declaring submodules via #[path = …​] mod …​, mirroring the existing tests/api/*.rs pattern.

Convention Rule

Path

<crate>/tests/properties/<property>.rs

Test name

prop_<invariant> — e.g. prop_stored_file_name_invariants.

Cases

Default 256; override per property in code (not env var) so CI and local match.

Fail-first comment

Each property carries a // FAIL-FIRST: …​ comment naming the one-character production bug that demonstrates the property bites + the expected shrunk counter-example.

Runtime budget

// PROPTEST_BUDGET_MS: <N> comment so reviewers spot regressions.

Run the full property suite with:

cargo nextest run --workspace -E 'binary(properties)'

Adding a new property: write the prop_<invariant> body, deliberately break the production code with a one-character flip, watch proptest shrink to a minimal counter-example, then revert and land. The shrunk-input log line goes in the MR description.

Fuzz targets (#3207)

Coverage-guided fuzzing covers the code a partner’s bytes reach first. The targets are in tools/craig-fuzz/, a workspace of its own outside the root one: libFuzzer, through cargo-fuzz, needs a nightly toolchain and sanitizer flags, and neither may reach the stable build. cargo xtask fuzz is the one way to run them. It first copies the workspace’s Cargo.lock beside the fuzz crate, so the fuzzed code is built from the versions the workspace pins.

Target What it reads, and what it holds

partner_answers

A partner’s answer, read by every part of the reference partner (craig-partner-testonia-registry): the adapter’s acknowledgement, the person index’s three answers, the benefit inquiry’s reply, the school roll’s file and each leg’s classification. Each part asks its question over a stub transport that answers 200 with the body, and again over one that refuses with it. Nothing panics. One input gives two bodies: the input’s own bytes, which the parse must survive, and a well-formed answer of one of the registry’s shapes whose values are drawn from the input (any text for an identifier, any score, a refusal with or without its code). Changed bytes rarely stay JSON, so only the second body reliably reaches what the crate does with an answer it could read.

transport_decode

One body through JsonAdapterCore::send_json and fetch_json, as a success and as a refusal. Nothing panics. A body that is not the expected type is reported by serde’s category and position, so the error’s text stays short however long the body is. A refused body, which is kept as text, is cut to BADSTATUS_BODY_MAX_BYTES and marked when it was cut.

module_boundary

One value of the module contract (crates/craig-partner-host/wit), of one of the twenty-three types craig-partner-sdk’s conversions read into a partner-contract type, built from the input by arbitrary: a date is any day number, a score any u8, an id any text. Reading it returns a value or a refusal. A value that was read is written back, read again and written again, and the two writes agree.

return_decode

One body through the reference partner’s return leg, as a partner’s call (#3193). The decode returns, and never says Busy. What it decoded passes or fails the contract’s bounds without a panic. A call that was admitted is acknowledged 200 with one result for each report. The same body under another content type decodes to nothing.

module_boundary generates the contract’s types with the generator the host uses and expands craig-partner-sdk’s module_conversions!, person_index_conversions!, referral_conversions! and return_conversions! over them, as craig-partner-host does. That is the host’s conversions from their source, expanded a second time; it is not the host’s compiled code. What other code reads is outside it. craig-partner-host reads three things by hand: a module’s failure (src/failure.rs), a collection’s result and reports (src/set.rs) and a leg’s declared facts when a set is loaded (src/modules.rs). The SDK’s guest half, built only for WebAssembly, reads the record context, the referral context, the sent record and the benefit question by hand (crates/craig-partner-sdk/src/guest/partner_set.rs). The host’s unit tests, its boundary tests over real modules and the hostile fixture cover those with named cases.

cargo xtask fuzz                                          # every target, 60 seconds each
cargo xtask fuzz --target module_boundary --seconds 600   # one target, longer
  • The verb needs a nightly toolchain and cargo-fuzz. --install adds whichever is missing; without it the verb stops and names the command.

  • seeds/<target>/ in the fuzz crate holds the tracked inputs every run starts from: well-formed answers, so that a short run reaches the code behind a parse that succeeds. corpus/<target>/ is what a machine’s own runs have grown, and is not tracked.

  • A failing input is written under artifacts/<target>/ there, and the verb fails once every target has run, naming each that failed. Add the input’s case to the crate’s own tests, then fix the code.

  • The sanitizer build goes to target/fuzz, about 2 GB.

  • Each target was shown to stop on a planted defect, within seconds: instant_of halving its nanoseconds (module_boundary); bounded_body_text dropping its marker (transport_decode); a leg that expects a refusal to carry a code, and an index that trusts the registry’s identifier (partner_answers). The last two are why that target generates well-formed answers: from changed bytes alone, a one-minute and a two-minute run found neither.

The stable twins run in every battery: the reference partner’s parse_never_panics property tests, and the host’s boundary property test over a real module (crates/craig-partner-host/tests/boundary.rs).

Hash-pinned regression tests for deterministic byte emitters

When refactoring code that emits deterministic bytes — SQL output, IaC YAML, manifest files, JSON renderers — bake a SHA256 of the pre-refactor output (against a known input) into a regression test. Mechanical rewrites (e.g. converting many INSERT builders into impl SqlRow blocks) fail in subtle ways a compile check and input-side unit tests miss: a dropped space, a swapped column order, an off-by-one comma. Only an end-to-end byte comparison catches them, and the hash pin makes that comparison cheap (~10 LOC) with an actionable failure (a SHA256 mismatch naming the file). The same six pins later proved the #846 rewrite byte-identical: the seed’s 46 impl SqlRow blocks became sql_row! invocations whose column list and value list are ONE token list (the header and the positional tuple can no longer drift), with no hash re-blessed.

How to apply:

  1. Before refactoring, capture the current output’s SHA256 for each well-defined input.

  2. Refactor the code.

  3. Re-run the test — it must pass with the same hashes.

Bless flow: pair the pin with a second test that prints the current hashes, #[ignore]`d and selected by its own nextest profile (the seed pin’s is `cargo nextest run -p craig-seed --profile seed-bless --run-ignored only, the seed-bless plane of § Opt-in planes; the profile prints a passing test’s output). For the inevitable case where output bytes should change (a deliberate schema tweak), run the printer, copy the printed values into the constants, and ship the MR with the intentional hash change documented.

Caveat — the input must be deterministic. Never pin a hash against output that depends on Utc::now(), random values, or HashMap iteration order. Fix the non-determinism first (preferred), or skip the pin for those outputs with a docstring explaining why. This pattern is faster than diff-based comparison (no fixture files to commit) and its failure mode is clear.

Mutation testing

cargo-mutants answers a question coverage cannot: do the existing tests actually catch wrong code, or do they just execute it? Mutation testing flips comparisons / deletes statements / replaces returns and re-runs the test suite per mutant. A surviving mutant means the test suite has a real semantic gap on that line.

Where What

Workspace config

.cargo/mutants.toml — timeout, nextest runner, exclude_globs for tests/examples/benches/main.rs.

Baseline

xtask/baselines/mutants-baseline.toml — committed list of accepted surviving mutants. Ships empty; populate after a clean smoke run.

Install

cargo install cargo-mutants --version "^25.0" --locked.

Smoke run

cargo xtask mutants --smoke (xtask wrapper) or cargo mutants directly.

Gated run (#1425)

cargo xtask mutants --gated [--package <name>]… [--shard k/n] — the DEVSTACK context, run on the project network (cargo xtask dev exec — cargo xtask mutants --gated …; the craig-tools image carries cargo-mutants, and the verb refuses off the network): stack ensured ready, keyed seed verified, scratch templates pre-warmed, and the #[ignore = "requires devstack"] suites opted in via the trailing -- --run-ignored=all (the flag is what un-gates them). Defaults to craig-mq — the crate whose missed set is dominated by broker suites. LONG-RUNNING (hundreds of mutants × the 300 s timeout floor): plan an unattended window with no conflicting devstack lifecycle operations. --shard k/n slices the mutant set for parallel/overnight splits.

Packages and exit codes (#2092)

A run over several packages is ONE cargo mutants --package a --package b … invocation, so its one mutants.out keeps every package’s outcomes (each invocation rotates mutants.out to mutants.out.old). Exit 0 (every mutant caught), 2 (missed mutants, listed in mutants.out/missed.txt) and 3 (timeouts) are results the wrapper reports; 1, 4 and any other exit fail it.

Residue scan (#1425)

Every wrapper run snapshots git status --porcelain before/after and FAILS on new entries (report-and-bail, never auto-delete) — an --in-place run must restore the tree exactly, and e.g. a proptest-regressions seed shrunk against MUTATED code is meaningless for the real implementation.

Catch variance (#1472)

Consecutive gated runs over a large service crate disagree by ~25–30 entries on which WEAKLY-COVERED mutants get "caught": incidental in-process code paths catch region mutants nondeterministically across runs. A caught verdict is therefore evidence only where a DELIBERATE killing test exists; treat each run’s fresh tail as candidate gaps to triage (the #1470→#1472→#1474 chain), never as regressions. Corollary for craig-cases: black-box TestHarness suites exercise the devstack CONTAINER’s unmutated binary — kills come only from inline units or the in-process keyed harness (#1162).

Critical crates

craig-api, craig-mq, craig-auth, craig-store, services/craig-cases/src/transitions/. Highest-leverage, not most-touched.

Per-mutant timeout

300s (kills hangs).

Total wall budget

<30 min for the full smoke. "Expect a coffee." The gated craig-mq run is multi-hour.

Mutation testing is never a pre-push gate — runtime cost is too high for a per-push cycle. Run quarterly or when adding tests to a known-thin module.

A future plan can tighten the budget by requiring new MRs not to increase the missed count (delta = 0) and requiring each reason = "tracked-issue-#NNN" line in the baseline to reference a real backlog issue. The first iteration enforces neither — "available, not gated."

Mutation-testing fixture rules

Three fixture-shape rules from the #1475 gated-run triage. Each names a mutant class that survives a fixture whose shape happens to make the mutant’s wrong answer indistinguishable from the right one — the fix is the fixture, not more tests.

  1. Assert totals over cardinalities ≠ 1. A 1-row fixture cannot distinguish the real count from a mutant’s constant (count → Ok(1) survives against total == 1). Seed ≥ 2 rows — or 0 where the emptiness is the property — whenever the assertion is a count or total.

  2. Behind wire-equivalent paths, assert at-rest side effects via raw sqlx. Where two outcomes share a status code (the deleted-download trap: a soft-deleted attachment 404s whether the guard ran or the blob is simply gone), the wire cannot see the guard mutant — read the row/blob state directly with a raw sqlx query and assert the at-rest truth.

  3. Search fixtures carry a non-matching decoy row. A suite that seeds ONLY rows matching the filter under test returns the identical page when the filter is no-op’d (a deleted bind arm) — the mutant survives. Seed one row that does NOT match and assert its id is absent from the filtered page (id-based, never bare counts; order the decoy so a no-op’d filter would place it on the truncated page).

Signal handling

craig_test_lib::sigterm_proof::assert_sigterm_drains(cmd, ready_marker) (2905, Linux only) spawns a REAL service binary, waits for the output line containing ready_marker and then for /proc/<pid>/status to show a SIGTERM handler (services log their listening line before that handler registers), sends SIGTERM with the system kill, and asserts exit 0 plus craig_common::supervisor::shutdown_signal’s SIGTERM log line. craig-intake’s `tests/sigterm.rs runs it in the plain battery (standalone mode boots with no infrastructure); craig-intake-keyring’s verifies its schema before it listens, so its leg is [ignore = "requires devstack"] over a template scratch database.

Evil Input Corpus

Single source of truth for "what does a hostile input look like." Plan test-framework-hardening.adoc §D15.

Module

crates/craig-test-lib/src/evil/ — 12 categories:

Category Coverage

jwt

Single-axis JWT mutations (wrapper over craig_test_lib::jwt_mutation).

upload

Magic-byte-spoofed uploads (wrapper over craig_test_lib::upload_fixtures).

string

Overlong (1 KB / 1 MB / 4 MB), invalid UTF-8, NUL/CRLF/RTLO/ZWSP injection, NUL-truncated.

uuid

Wrong version, wrong length, all-zeros, dash scrambled, non-hex, embedded NUL.

json

Depth bombs, ref cycle, integer overflow, schema-stuffing, type-swap, missing required.

path

../, double-encoded, NUL-truncated, UNC, alternate data streams, backslash separator.

html

Script tags, onerror, javascript: URLs, base64 data URLs, double-decode escapes.

unicode

NFC/NFD pairs, homoglyphs, BiDi overrides, UTF-8/UTF-16 BOMs.

enum_value

Unknown variant, case mismatch, adjacent typos, trailing whitespace.

date

Leap-second, year-9999, negative year, fractional overflow, no-offset, invalid Feb-30.

multipart

Missing boundary, malformed Content-Type, oversized field count, empty filename, content-type spoofing.

signature

Truncated JWS, empty signature segment, alg=none, malformed garbage, alg-confusion.

Public API

craig_test_lib::evil::all_evil_cases()              // every case across every category
craig_test_lib::evil::evil_cases_for(EvilCategory)  // filter by category

// The macro emits one #[tokio::test] block per category it does
// not skip (evil_jwt, evil_upload, …, evil_signature). Wrap in
// a `mod` to qualify the test names.
mod cases_post_evil {
    use craig_common::error::problem_types;
    use craig_test_lib::evil::EvilCategory;
    use craig_test_lib::parametric_evil_test;

    parametric_evil_test! {
        // The closure returns (HTTP status, raw response body). The body lets the
        // harness honour ExpectedRejection::ProblemType by comparing the RFC 9457
        // `type` member (see craig_test_lib::evil::rejection_matches), not just a
        // generic 4xx.
        endpoint: |case| async move {
            match client.send_with(case).await {
                Ok(r) => (r.status.as_u16(), r.raw),
                Err(_) => (0, String::new()),
            }
        },
        skip_categories: [EvilCategory::Multipart],
        // #954: tighten specific categories to the exact RFC-9457 `type` this
        // endpoint guarantees (verify each against the running service first).
        // The shared corpus default stays AnyClientError for every other
        // endpoint — only this invocation asserts the specific type.
        problem_types: [(EvilCategory::EnumValue, problem_types::INVALID_ENUM_VALUE)],
    }
}

Each emitted test is nextest-addressable (cargo nextest run -E 'test(evil_jwt)' filters to the JWT category). A regression in one category does not hide regressions in the others.

Each category test runs its cases through craig_test_lib::evil::run_evil_category (#2523), which checks two things per case: the response meets its expectation, and the body does not echo the case input. The echo check (body_echoes) looks for each echo_needles text verbatim or as its JSON string escape: a Str payload’s string, or each string leaf and number literal of a Json payload. Needles shorter than 6 chars are dropped (they would match ordinary prose), and so are needles that parse as a UUID: ApiError::NotFound names the path id, so a well-formed UUID is a resource name, not an echo. An echoing failure withholds the response snippet; any other failure prints the body’s first 200 chars. A category in skip_categories (spelt EvilCategory::<Name>, so a misspelling fails the build) emits no test at all, and an exercised category with no case fails instead of passing vacuously.

The optional problem_types list (#954) turns a category from a generic-4xx check into an assertive one: every case in a named category must return that exact RFC-9457 type, not merely a 4xx. It is a per-endpoint override — the shared EvilCase::expected is untouched, so no cross-service cascade. Verify before asserting: only pin a type you have confirmed against the running handler for every case in the category. A category that isn’t uniform (e.g. craig-rules String, where the 4 MiB overlong case is rejected by the HTTP body-limit layer as a 413 plaintext, never reaching garde) must stay on the AnyClientError default rather than be force-pinned.

Contracts

Test Purpose

crates/craig-test-lib/tests/evil_corpus_self.rs

Self-test: every category contributes ≥1 case, names unique, deterministic iteration, ≥60 cases total.

crates/craig-test-lib/tests/evil_corpus_global_contract.rs

Global ingestion-rejection contract: every evil case rejected as 4xx at the public-intake endpoint. No 500s, no 200s, no silent acceptance. Its no-echo leg (#2335) drives the same cases and asserts no response body quotes the case input back (echo_needles / body_echoes), with a floor of 40 cases that carry an echo needle.

crates/craig-test-lib/tests/evil_corpus_macro_demo.rs

Compile-time demonstration of parametric_evil_test! macro. It skips four categories, so cargo nextest list -p craig-test-lib lists its 8 tests.

Adoption

Per-service tests/api/evil_corpus.rs files are tracked as backlog (plan §D15.6). Each service exposes ~5 public-ingestion endpoints; landing the macro per service is mechanical fan-out once the contract module proves the pattern in evil_corpus_global_contract.rs.

A devstack leg that sends a body past a service’s body limit and expects the 413 sends it through craig_test_lib::body_limit_probe::send_past_limit (#2866). A service refuses only once it has read past the limit (axum’s Limited body counts the bytes it reads and never consults Content-Length), then closes with the rest unread, so a client writing the whole body can see a connection reset instead of the 413. The probe declares the whole body over a raw TcpStream, sends exactly one byte past the limit and then reads the answer, so nothing is left unread. Its limit must equal the service’s limit, and the probe does not verify it: a higher service limit fails as a 30 s timeout, while a lower one may pass unnoticed or fail as a write or read error. An endpoint closure that POSTs JSON (a parametric_evil_test! adoption) uses body_limit_probe::post_json_past_limit, which probes only a body past the limit and returns None for the closure to send any other its usual way; DEVSTACK_BODY_LIMIT is the 2 MiB limit every craig-api devstack service keeps on its plain JSON routes (#2876); craig-intake’s edge keeps its own body_limit (11 MiB by default, which the devstack does not override), and its public adoption passes that. cargo xtask lints evil-body-probe, a blocking step of cargo xtask validate (#3024), holds every parametric_evil_test! adoption to this: its endpoint (the tokens after endpoint: up to the next top-level comma) must call post_json_past_limit or send_past_limit, itself or through a fn defined in the same file whose body calls one (craig-placement’s post_untyped). The rule asks nothing about what the endpoint sends, since a typed client call can be spelled any way: an endpoint that cannot reach a body limit (a stub, a multipart or query send) carries // no body-limit probe: <reason> on the line above endpoint: or inside the endpoint. A marker with no reason, on no endpoint, or on an endpoint that probes is itself a finding. A refusal that stops reading mid-body below the whole-body limit takes the same probe with limit at the last byte it reads, as craig-intake’s oversized-attachment leg does at the edge per-file cap.

Adding a new attack class is a single file edit — append a new EvilCase to the relevant category module — and every test using parametric_evil_test! or all_evil_cases() picks it up automatically.

Constraint tests

Hand-curated harness for verifying API-boundary rejections (UNIQUE conflicts, FK lookups, enum validation, duplicate-create handling). Plan test-framework-hardening.adoc §D14.

Convention

File Purpose

crates/craig-test-lib/src/constraints.rs

Helper module: ExpectedRejection enum + two assertion helpers (assert_constraint_violation_status for status-only, assert_constraint_violation_returns when an RFC 9457 type URL is known to exist).

services/<svc>/tests/constraints.rs

Module-index file declaring #[path = "constraints/<file>.rs"] mod <file>; per constraint.

services/<svc>/tests/constraints/<constraint>.rs

One test per constraint. Each #[tokio::test] async fn <constraint>_evil() asserts against a real handler.

Running

cargo nextest run --workspace -E 'binary(constraints)'   # all constraint tests
cargo xtask reliability                                  # also runs them via the failure-path filter

Tests carry #[ignore = "requires devstack"] so they’re skipped by default and run when devstack is up via cargo nextest run — --ignored (or via the full battery: cargo xtask validate locally, xtask test --integration in the car). Plan D F-024 converted the legacy if !devstack_available().await { return; } early-return pattern; see Devstack-gated tests in this doc for the canonical shape.

Auto-generation rejected

Per §D14: auto-deriving negative tests from migrations was rejected. CHECK constraints are arbitrary boolean expressions, UNIQUE constraints are tuples, FK constraints have ON DELETE semantics that vary, NOT NULL is the only constraint where the negative space is trivial. Even when SQL parsing succeeds, the interesting assertion is at the API boundary, not at SQLSTATE. Hand-curation is mandatory.

Adding a new constraint

  1. Identify the API endpoint that exercises the constraint.

  2. Write a test in services/<svc>/tests/constraints/<name>.rs following the same template as the existing tests (TestHarness, #[ignore = "requires devstack"], typed/raw client call, assert_constraint_violation_status).

  3. Add #[path = "constraints/<name>.rs"] mod <name>; to services/<svc>/tests/constraints.rs.

  4. Run cargo xtask test --package craig-<svc> --integration --test constraints against a live devstack (1802). The constraint tests are [ignore = "requires devstack"] (#1179), and the scoped run includes them. A bare cargo nextest run --test constraints runs zero of them and exits green, a false all-clear.

The full enumeration of constraints is tracked in the backlog (issue filed alongside this plan).

Invariant tests

Post-test-run platform-invariant sweeper. Plan test-framework-hardening.adoc §D17. Runs SQL queries from a per-service catalog against each service’s Postgres DB; non-zero rows are invariant violations. The full sweep (craig-manage invariants) is report-only; since #860 the pre-push cargo xtask validate battery ALSO enforces a curated BLOCKING subset (craig-manage invariants --gate) — the list is BLOCKING_INVARIANTS in xtask/src/cmd/invariants.rs, entries that hold by construction (single-writer stores, GENERATED columns, triggers), so a violation always means a bypass write.

Pre-run debris scan (#1801)

The gate answers "did THIS battery leave the data consistent?", so the battery clears debris before it starts. Debris is rows an earlier run committed and never cleaned up, typically tests that panicked before their teardown. Right after ensure_ready, the pre-push phase runs the BLOCKING subset once (invariants::scan_debris):

  • Clean: one ✓ line, and the battery proceeds.

  • Dirty: each violated invariant is printed loudly: service, name, row count, and every row (at most the catalog’s LIMIT 20, clipped to 240 characters) with its age, read from the row’s youngest UUIDv7 value ("age unknown" when it has none). The report goes to stdout and the validate-phases.log journal. Then cargo xtask dev reseed wipes the volumes, and the scan runs again.

  • Still dirty on the fresh seed: the push fails. That is a seed or migration defect, not debris.

The reseed also wipes report-only rows; they never gate, and craig-manage invariants shows them first if wanted.

Chosen over excluding rows older than the run stamp: the catalog rows carry no timestamp, and every seed row predates any stamp, so a seed row the battery breaks would be laundered. Chosen over diffing against a pre-run baseline: the catalog’s LIMIT 20 lets 20 debris rows hide a new one. cargo xtask test --integration does not scan (the car’s stack is fresh); validate --profile full runs it with the hidden --pre-push, which does. The standalone craig-manage invariants and --gate never scan or wipe (an unpinned property since #2299 deleted the source-text pin); a developer previewing the gate sees the whole database.

Catalog: crates/craig-invariants/sql/

Bucket Applies to Entries

craig-mq/

every stateful service DB (cross-service)

6 entries: outbox_unpublished_beyond_grace, inbox_unprocessed_beyond_grace, outbox_retention_overrun, inbox_retention_overrun, request_claims_retention_overrun, inbox_identity_collisions_present

craig-cases/

craig-cases only

5 entries: active_plan_review_due_required, case_household_member_unique, cohort_bump_same_tx_as_event, investigation_admin_unit_from_referral, plan_superseded_same_tx

craig-exchange/

craig-exchange only

6 entries: stuck_pending_transactions, retried_never_reterminal, send_jobs_retention_overrun, ssa_active_run_below_watermark, ssa_provenance_hot_window_overrun, ssa_transport_retention_overrun

craig-financial/

craig-financial only

35 entries: the payment-integrity pair (ffp_amount_stale, day_count_gross_consistent), the ADR-052 subsidy-ledger family (subsidy_projection_matches_head, window/revision contiguity, party rules, subsidy_coverage_overlap, …), the #1069/#1070 flow watchers (subsidy_perdiem_same_month_overlap, sg_transfer_matches_activation, sg_no_payment_before_boundary, review-sweep queues, …), and the four #1071/ADR-057 conversion guards — subsidy_active_missing_review_slot, subsidy_terms_cover_active, subsidy_closed_cohort_qualifying_date, subsidy_cutover_iff_imported — ALL FOUR in the blocking subset, and the #1115 backpay guard subsidy_backpay_bounds (blocking), and the report-only #2041 perdiem_disbursed_on_retracted_placement and #3199 perdiem_disbursed_past_placement_end

craig-placement/

craig-placement only

6 entries: the occupancy pair (occupancy_mismatch, occupancy_over_capacity), child_record_admin_unit_from_episode, left_care_ending_without_exit (report-only), placement_ended_missing_ended_at, placement_replacement_target_invalid

craig-reporting/

craig-reporting only

1 entry: validated_with_errors

craig-rules/

craig-rules only

3 entries: null_rule_output, rule_evaluations_hot_window_overrun, rule_set_snapshot_revision_gap

craig-security/

craig-security only

6 entries: audit_log_hot_window_overrun, audit_log_partition_horizon (#3173), dead_letter_hot_window_overrun, identity_issuance_log_hot_window_overrun and identity_issuance_log_partition_horizon (#3173), and the #2739 identity privilege matrix identity_execute_matrix (blocking)

One row per bucket directory. Each Entries cell opens with the number of .sql files in that bucket, and every backticked name in it is one of that bucket’s invariants. Large buckets name their families, not every file. The catalog self-test pins all three (#2068), so a new catalog file fails until its row’s count moves.

Each .sql file’s first comments are TOML-fragment metadata (name, service, grace, remediation, severity); the body is a SELECT that must return zero rows.

Running

craig-manage invariants                   # sweep all stateful services
craig-manage invariants --service craig-cases --database-url <url>
craig-manage invariants --gate            # fail only on the blocking subset
craig-manage invariants --catalog path/to/alt-catalog

The verb was cargo xtask invariants until #3132. The catalog is compiled into the binary (--catalog reads a directory instead). There is no default database: a whole sweep needs CRAIG_<SVC>__DATABASE_URL set for all nine stateful services and names every missing one; --service needs only that service’s, by variable or --database-url. Sessions refuse writes. Against a devstack, export the nine URLs first; the battery’s gate (cargo xtask validate) supplies the devstack’s itself.

Outcomes

Outcome Meaning

OK

Query returned zero rows

FAIL

Query returned ≥1 row — invariant violated; details + remediation pointer printed

N/A (not_applicable_to)

The invariant’s header declares this database out of scope (-- not_applicable_to = "<service>, …", cross-service files only; #2653): a database without the tables it reads by design, such as craig-intake-keyring for the outbox, inbox and request-claims invariants. No query runs

FAILED: table … is missing

Postgres SQLSTATE 42P01 on an invariant that applies here: a renamed or dropped table. A blocking invariant fails the gate; an advisory one prints REPORT-ONLY FAILURE. Never a skip (#2653); the debris scan follows the same rule

ERROR

Query failed for any other reason; treated as a failure

Drift contract

A self-test in crates/craig-test-lib/tests/invariants_catalog.rs enforces:

  • Every .sql file parses; metadata header is well-formed.

  • Every name is unique across the catalog.

  • The § Catalog table above has one row per bucket directory. Each row’s count is that bucket’s .sql file count, and each name a row cites is an invariant in that bucket (#2068).

  • The grace header literal and the SQL body’s INTERVAL '<n> <unit>' literal both match the corresponding craig_common::constants::*_GRACE Duration.

Adding a new time-based invariant requires touching three places in lock-step: a constant in craig_common::constants, the .sql file, and the mapping table in the self-test. Drift fails CI.

Local subcommands

The xtask runner registers stable entry points for the failure-path, property, contract, invariant, and mutation suites. None are part of the pre-push gate, except quality-budgets --fail-on-regression, a blocking validate step; invariants, the battery’s data-consistency gate (#860), which fails it on a merge-blocking invariant; and coverage-matrix, which every full battery runs with its blocking coverage-signature gate (--check) — they exist so contributors can run a single test category locally and so CI dashboards have a deterministic command to pin to.

Command Filter / scope Plan §ref

cargo xtask reliability [--filter <expr>]

nextest test(::concurrency::) | test(::recovery::) | test(::fault::) | test(::invariants::) | test(::properties::) | binary(properties); --filter ANDs an extra expression onto the default

§D11.2

craig-manage invariants [--service <name> [--database-url <url>]] [--gate] [--catalog <path>]

SQL platform-invariant sweeper over per-service Postgres DBs; N/A where a header declares a database out of scope, a missing table fails the invariant (#2653); bail on violations. Replaces the Step-12 nextest-filter stub. See "Invariant tests" subsection above.

§D17

cargo xtask contracts [--service <name>]

nextest test(::typed::) (or test(::typed::<service>::))

§D11.4

cargo xtask mutants --smoke | --full

cargo-mutants over the 5 critical crates (smoke) or workspace (full); reads .cargo/mutants.toml

§D11.3

cargo xtask coverage-matrix [--records <dir>] [--junit <xml>] [--output <md>] [--check]

Reads the battery’s HTTP records (§ HTTP recording) and that run’s nextest JUnit; credits each passed test’s final attempt; matches each record to its service’s from-source OpenAPI route; derives happy / sad / evil / conc / replay / fault per route; writes test-results/http/coverage-matrix.json and target/coverage-matrix.md. --check then runs the coverage-signature gate: it fails on a required signature missing and not in xtask/baselines/coverage-signatures.toml, or on a stale baseline entry; cargo xtask baselines bless --only coverage-signatures rewrites the baseline, shrink-only (Quality Gates § Coverage-signature gate). Every full battery runs it with --check after nextest: a broken recorder or a failed gate fails the battery.

plan runtime-coverage-matrix D3–D6

cargo xtask quality-budgets --report [--fail-on-regression]

Reports the budget table against the record in xtask/baselines/quality-budgets.toml (thresholds/globs/markers are constants in xtask/src/cmd/quality_budgets.rs); cargo xtask baselines bless --only quality-budgets rewrites the record. --fail-on-regression is the BLOCKING pre-push + CI gate (#522).

§D12

reliability, contracts and mutants print an "opt-in; not part of pre-push gate" banner so contributors are not misled into wiring them into hooks. coverage-matrix prints its own banner instead (=== Coverage matrix (#2703, plan runtime-coverage-matrix D3–D5) ===, then === Coverage-signature gate (#2704) === with --check), because every full battery runs it (Coverage Matrix).

Ruleset Discovery Test

  • File: services/craig-rules/tests/ruleset_discovery.rs

  • Runs as part of cargo nextest run --workspace (no devstack needed — loads JSON from disk)

  • Scans every config layer’s top-level *.json at runtime (craig_test_lib::config::all_layers: the fetched layers and the testonia fixture)

  • Validates: JSON parse, structure (nodes/edges), zen-engine compilation, evaluation with synthetic default input

  • Adding a new jurisdiction: rules check walks every layer of the fetched view (ruleset_dirs() in xtask/src/cmd/rules.rs), so add its layer to config-sources.lock, register it in BLOCKING_JURISDICTIONS (xtask/src/cmd/policy.rs), ship its blocking citations.toml + policy-source.toml in the same MR (the audit walks every dir the moment it exists), and for a jurisdiction ship its bundle/ (its settings.toml business_timezone is the business clock, #2207); the discovery test then picks the files up.

Config bundles in tests

A test gets a jurisdiction’s reference data from craig_test_lib::config, never from a compiled crate:

  • config::bundle("<layer>") returns the &'static ConfigBundle of one layer (georgia, texas, or the fixture testonia): the bundle a service configured with only that layer runs under. Tests hand it to a service’s boot function. One bundle is loaded per layer per process and the same reference comes back on every call. It installs no business timezone, so a test of a boot path sees only what that path installed.

  • config::snapshot("<layer>") is a working-copy ConfigSnapshot over the one layer; config::layer("<layer>") is its directory; config::palette_modes("<layer>") is its palette as plain tuples.

  • georgia and texas are the layers config-sources.lock pins, read through the view cargo xtask config fetch builds (target/config/layers/<name>). A test that needs one panics on a checkout without the fetch, naming cargo xtask config fetch; it never reads an empty layer. testonia is in source (fixtures/config/testonia/, one bundle file of every kind), so a test that must run with no fetched configuration uses it.

  • Business zones in a test binary come from craig-common’s test-only test-zones feature, which craig-test-lib enables: a jurisdiction nothing installed answers from a fixed table (Georgia, Texas), and an installed zone wins.

  • A test may still implement StateBundle with a fake of its own (craig-financial and craig-exchange do).

  • The locked layers are held to the product by tests that run in every battery: craig-config-bundle’s `tests/locked_layers.rs asserts the Georgia layer’s reference data item by item. The tests that hold the layer’s adapter list, trigger matrix and legal statuses to Georgia’s partner code and wire are Georgia’s, in its repository (partners/src/layer), since the code is.

Conversion-import test surface (#1071 / ADR-057)

API suites — four devstack-gated files under services/craig-financial/tests/api/ plus one hermetic binary, all members of the subsidy-generation-lease nextest serial group (max-threads = 1 in .config/nextest.toml, all three profile blocks — the deployment-global advisory leases subsidy-gen / subsidy-sweep / the per-batch finalize lease AND, since #1938, the per-batch import_finalize:<batch_id> job arbiter are exclusivity UNDER TEST, so serializing the group exercises their real semantics instead of masking contention with retries). Since #1938 (plan background-jobs U6) finalize is an ENQUEUE: every finalize leg POSTs { client_request_id }, asserts the 202, and polls the job to terminal through craig_test_lib::jobs::wait_for_job, decoding the LAST pass’s FinalizeReport from result; the synchronous 4xx oracles (manifest gate, below-floor office, no-office admin, authz) are unchanged — they enqueue nothing.

Suite Pins

subsidy_import.rs

The batch lifecycle end-to-end; the full §Replay-semantics table incl. replay-after-mutation (finalize → native lifecycle action → resend → 200 with the ORIGINAL facts) and canonical equivalence (money 450.5 ≡ "450.50"); manifest-gate 409s carrying the four numbers (and never burning the batch); abort claim-freeing
post-finalize abort refusal; the 22.9 grace-boundary split + finalize world-drift rejection looping the batch; cross-service reference blockers + the terminal payment assessment; the authority matrix (non-admin / office refusal naming state_office / wire refusals); the AC1 closed-cohort create re-pin. (The knob-OFF contract — typed 403 naming CRAIG_FINANCIALSUBSIDY_IMPORTENABLED, GETs open — is pinned at the UNIT level in subsidy_imports.rs::gate_tests: the devstack runs gate-ON stack-wide, the ERR F4 precedent.)

subsidy_import_concurrent.rs

Concurrent same-reference stages → one winner, the loser answers from a FRESH transaction per the replay table (never a 500); concurrent finalizes with two fresh ids → one 202 + one 409 job-already-active (the arbiter over import_finalize:<batch_id>; DELIBERATE oracle change from the pre-#1938 lease 409, named in its commit) and a straggler after finalized is a NEW job whose single pass is the deterministic replay; a native create racing finalize → the record rejects typed and the batch loops

subsidy_import_finalize_fault.rs

The crash shape constructed EXACTLY as a crash leaves it (the batch flipped finalizing) → a fresh-id enqueue resumes exactly-once under the SAME batch id with correct totals (per-record transactions + the live-reference unique + the same-tx record flip); the partial pass (result.status = staging, 2 materialized / 1 rejected) then the remainder on a fresh id; a peer-held subsidy-import-finalize:<batch_id> engine lease → 202
progress.phase = waiting_for_lease, succeeded once released (DELIBERATE oracle change from the 409, named in its commit)

subsidy_import_jobs.rs (#1938)

The finalize job wire: 202 + Location: /v1/financial/jobs/{id} + the JobView with resource = the batch; replay by client_request_id (the SAME job, no second execution) and forged / missing fields → 422 with no claim row; a fresh id while a finalize is active → 409 job-already-active with its claim rolled back; the synchronous gates enqueue nothing (manifest 409 with the four numbers, the below-floor office, the office-less admin); two batches finalizing in parallel under two lease keys; the post-crash resume — a finalizing batch beside a terminal failed(crash) job row → a fresh-id enqueue resumes per record exactly once while the old job stays failed (immutable). The job READ policy is pinned once per service by the U5 battery (background_jobs.rs), not repeated per kind

import_finalize_jobs (#1938 — hermetic binary services/craig-financial/tests/import_finalize_jobs.rs over the financial scratch base, the REAL ImportFinalizeKind on a test JobsRuntime; binary_id(craig-financial::import_finalize_jobs) is in the group filter)

The plan’s pinned Evil row: a stale queued finalize seen by a SECOND runtime’s scan → failed(lost_proof), never running, the batch unchanged; a stale running finalize → attempt crash, the job failed (a consent kind never re-queues) with the batch still finalizing, then a fresh-id enqueue + drain_pending resumes per record exactly once (the FaultRecord under worker.craig-financial.main.watch.3, its second crash leg — a_stale_running_import_finalize_job_is_classified_crash_and_ends_failed_with_the_batch_still_finalizing); three barren passes (a BEFORE-UPDATE trigger on subsidy_import_records refusing the materialize flip — the swallowed infra-error path) → failed(no_progress) with remaining_staged in error.detail (the streak reset by a progressing pass is unit-pinned beside the kind over a scripted run_passes); a queued row this replica never stashed a proof for → failed(engine_failed) proof_missing; the knob OFF at attempt start → failed(refused_at_start); a failed consent job fires JobKind::on_failed exactly once from EACH terminal-failure writer (the executor and the classifier)

The raw-SQL fixture builder — crates/craig-test-lib/src/subsidy_fixtures.rs (D10): the store primitives now REFUSE shapes tests still need as raw material (import_agreement_history refuses open-pending heads and open programs; the native creates enforce the full witness battery), so the builder writes identity + interval
terms (+ party) rows directly, deliberately bypassing every store invariant — honest about being a fixture, never a production path. Rows built imported: true carry provenance (source_system = "test") AND a payment_cutover_month (the cutover-iff-imported CHECK demands the pair; the default cutover is the first interval’s month-start so generation semantics are unchanged), and imported-shaped rows keep the F4 belt exemption so a pending fixture can still drive the REAL public transition writer. The caller owns invariant compliance — a nonsensical chain trips cargo xtask invariants exactly like production corruption. Its crash-residue sweep sweep_subsidy_residue (#1373) removes a marker’s residue payments through purge_payments, which first deletes every row holding a blocking FK onto them (PAYMENT_PURGE: adjustments, claim exclusions, per-diem handoff facts; #1978); tests/constraints/subsidy_residue_sweep.rs pins that list to the schema, so a migration adding a blocking referrer of payments must extend it. The agreement delete likewise clears the agreement’s RESTRICT referrers first (AGREEMENT_REFERRER_PURGE: its backpay and import-ledger records are deleted and a successor’s predecessor_agreement_id is nulled; #2918), pinned to the schema in the same file. Per-suite teardowns share the same order (#2919): purge_payments_created_by for a marker, purge_payments_by for a payment, case, child, placement or agreement id (with a fallible try_ form for best-effort harness cleanups), purge_child_subsidy for a child’s payments and agreements under its pay-excl lock, and sweep_residue_agreement for an agreement held by id. A bare DELETE FROM payments in a teardown is the bug.

Seed family F — the conversion-ledger fixture (tools/craig-seed/src/datagen.rs): a FINALIZED shines batch + one MATERIALIZED record + the imported rcs agreement it landed (first Active 2013-06-01, strictly before the 2014-01-01 closure; a closed 2013 terms revision + the open revision with CURRENT future dues; cycle-1 renewal AND paper slots; state-office attribution; pinned ids, no stream draws). Its payment_cutover_month = as_of + 1 month is the PRE-CUTOVER pin: the scheduled generation tick judges BeforeCutover and counts the skip (skipped_before_cutover = 1) instead of paying, so the deterministic zero-generation seed contract holds with NO payment rows — pre-cutover months belong to the legacy ledger by machine rule. The canonical payload/hash on the record row are fixture literals (the fixture-C hash posture), deliberately not real digests.

Review-sweep job test surface (#1939 / plan background-jobs U7)

The manual sweep is three acts — the preview ENQUEUE, the token POST, the execute ENQUEUE — so its suites re-shaped onto 202 + poll (DELIBERATE oracle changes named in their commits per R-U67-5, never deleted: the rotation legs preview_response_loss_retry_rotates_the_token_on_the_same_run — renamed preview_replay_returns_the_same_job_and_the_token_issues_once — / preview_concurrent_same_key_yields_one_run — a replay returns the SAME job and the token issues ONCE by the POST — and execute_token_contract_over_http, whose expiry arm keeps its 409 + expired stamp). The HTTP suite services/craig-financial/tests/api/subsidy_review_sweep.rs (a subsidy-generation-lease member by the test(review_sweep::) substring) previews through the job (craig_test_lib::jobs::wait_for_job → PreviewSweepResult), issues the token through FinancialSubsidySweepClient::issue_sweep_token and executes through the job; the store suite tests/store/review_sweep.rs drives consent_run (inside a transaction) + run_consented (a detached JobBoundary) where it drove the synchronous execute, and the constraints suite pins the widened CHECK (consented admitted). The hermetic binary services/craig-financial/tests/sweep_execute_jobs.rs (the REAL SweepPreviewKind / SweepExecuteKind on a test JobsRuntime over the financial scratch base; binary_id(craig- financial::sweep_execute_jobs) joins the group filter) pins the plan’s sweep rows by name: a_consented_sweep_run_is_invisible_to_reap_stranded_runs_while_a_scheduled_pass_runs, a_stale_running_sweep_execute_job_is_classified_crash_and_the_run_reads_failed_with_counters_intact (the third crash leg under worker.craig-financial.main.watch.3 — its FaultRecord rides the same anchor; no new anchor, worker or migration class), an_execute_attempt_that_fails_mid_set_commits_counters_per_agreement, a_stale_queued_sweep_execute_job_is_failed_lost_proof_and_its_consented_run_reads_failed_with_counters_null_not_zero (Option A, R-U67-2: SweepExecuteKind::on_failed flips the run from the classifier’s writer, counters NULL — never zeros), waiting_for_lease_under_a_scheduled_pass_then_success (the proof survives the re-stash) and a_queued_execute_without_a_stashed_proof_fails_proof_missing. The unit pins beside the kinds cover the key derivations, the strict inputs (a forged execute_token on the job input is refused — the token never rides the row), the two failure maps, the empty preview intent / run-only execute intent, and the ONE failed-stamp statement (the_failed_stamp_preserves_counters_and_guards_on_in_flight_states).

Edit this page · latest