Testing (Canopy)

Table of Contents

For a contributor or agent writing or running Canopy tests: this page owns the test lanes and their one invariant, what git push runs, the E2E battery, the seed harness and the canopy-test-lib idioms. The universal strategy — philosophy, nextest basics, the Playwright mandate, the evil-input corpus, mutation and property testing, the test-results/ layout — is Testing (Standard) and is not repeated here; the canopy-test-lib API surface is summarised in Shared Crates. Every cargo xtask flag below is derived from xtask/src/cmd/*.rs; the full catalog is cargo xtask Subcommand Catalog.

Running the suite

cargo xtask test is the entry point (xtask/src/cmd/test.rs):

cargo xtask test                        # fmt --check, clippy -D warnings, then both lanes
cargo xtask test --unit                 # unit lane only: no devstack, no locks
cargo xtask test --integration          # infra lane, in-network (ADR-015); refreshes the devstack first
cargo xtask test --integration --host   # infra lane with host nextest (IDE / single-test debugging)
cargo xtask test --integration --host --no-refresh --skip-static --run-ignored -p canopy-notices
                                        # one crate's lanes through the battery's own path (#2004)
Flag Effect

--unit / --integration

Run one lane. Neither flag runs both.

--no-refresh

Skip ensure_ready (the devstack refresh) before the infra lane; you assert the stack is up.

--host

Run the infra lane with host cargo nextest instead of the canopy-integration compose service.

--skip-static

Drop the fmt + clippy gates. For CI lanes only, where dedicated jobs own them (#1389).

-p <CRATE> (repeatable)

Scope both arms to the named crates. The integration arm then requires --host (the in-network ENTRYPOINT is workspace-wide) and tolerates an empty selection (--no-tests=pass).

--run-ignored

Append --run-ignored=all. The battery’s own arms never pass it.

Anything but --unit takes the two battery locks — the project lease in $TMPDIR/<project>-xtask.lock and test-results/.validate.lock (xtask/src/docker.rs) — so a lane never overlaps the battery or another lane. JUnit output lands per nextest profile (table below). An infra lane is followed by the post-lane schema sweep even when it failed; a unit-only run creates no schemas and never sweeps.

Lanes and the one invariant

The partition (#1377)

Every lane selects on one classification: a lib/bin test that needs live infrastructure lives in a module whose path has a segment ending in infra_tests — infra_tests itself, or a suffix spelling such as canopy-snap’s crate-root postponement_infra_tests (#2080); everything else is pure. The filtersets are the constants in xtask/src/lanes.rs, and test-lanes-lint classifies on the same word (INFRA_MODULE_SUFFIX):

Lane Selection (xtask/src/lanes.rs) Profile / threads

cargo xtask test --unit

--lib --bins -E '!test(/(^|::)[a-z0-9_]*infra_tests::/)' (UNIT_FILTER)

default 8

cargo xtask test --integration --host

-E '(kind(test) | test(/(^|::)[a-z0-9_]*infra_tests::/)) & !(package(canopy-test-lib) & binary(/^idp_conformance_/)) & !(kind(test) & test(/(^|::)contested::/))' (INTEG_FILTER: the integration targets and the infra tests, less the conformance suites, which only identity matrix runs, and the fault lane)

integration 12

cargo xtask test --integration (the Dockerfile.integration ENTRYPOINT, from the archive; under CANOPY_CI=true the job joins the compose network and runs from its own target/ in the car profile, #3353)

INTEG_FILTER, the same filterset

integration 12 / ci-integration

validate pure-unit arm

-E '!kind(test) & !test(/(^|::)[a-z0-9_]*infra_tests::/)' (VALIDATE_UNIT_FILTER)

validate-unit 16

validate infra arm

INTEG_FILTER

validate 12

cargo xtask test --fault

-E 'kind(test) & test(/(^|::)contested::/)' (FAULT_FILTER: every test of a tests/ target under a contested module, which puts faults on the transport fault layer)

fault 4

The fault lane (cargo xtask test --fault, a step of the car after the integration lane) starts the transport fault layer, runs its preflight with --required, and only then runs its tests: a layer that cannot be started or proved fails the lane before any test, and a fault test run without the layer panics under CANOPY_TEST_INFRA=required (canopy_test_lib::toxiproxy::layer_available). A new fault test goes in a contested module of a tests/ target; the filter then moves it from the integration lanes to this one. The lane also keeps a fault ledger (canopy_test_lib::fault_ledger, under test-results/fault/ledger): each severance or toxic put on the fault layer is recorded as armed, and the test marks it fired (restore() hands back the record) after the assertion only the fault explains. The broker faults that do not go through the layer are recorded by their tests the same way (ArmedFault::arm): a graceful close through the management API, and a restart, stop or replacement of the broker's container. When the tests pass the lane still fails if nothing was armed, if an armed fault never fired, or if no broker fault fired. It prints the kinds of fault the ledger does not record.

cargo xtask test-lanes-lint --static enforces the classification statically (a syn walk over lib/bin sources for the infrastructure helpers in INFRA_IDENTS, the skip-or-panic probes among them, #2295, plus the URL-literal ban, #1381); --verify-partition set-verifies unit ⊎ integration == the whole cargo nextest list, disjoint, in every battery (the lane-partition stage) — and that every override filterset (the serialized test-groups and the #2140 exclusive-run pins) still matches, so a test rename can never silently unserialize a group.

The archive (#3274). Locally, cargo xtask test --integration builds the nextest archive target/car/tests.tar.zst in the CI image under BATTERY_FEATURES (the runner is Alpine, so its binaries are musl), then the integration runner image (Dockerfile.integration) from it, which holds the archive and the tree. It links the root the archive was built at (target/car/tests.root) to /app, where it extracts the archive, so the paths cargo compiled into the binaries (CARGO_MANIFEST_DIR, canopy-cli's CARGO_BIN_EXE_canopy) resolve. The car builds no archive: on one VM it runs the lane from its own build (#3353).

Battery features (#3343). The battery builds with one feature set, BATTERY_FEATURES in xtask/src/lanes.rs: canopy-api/test-clock,canopy-api/test-fault,canopy-portal/server,canopy-portal/preview,canopy-test-lib/idp-conformance. The xtask lanes (test, validate, coverage, the test-lanes-lint listings), clippy, rustdoc, the doctests, the archive and the car's devstack binaries all pass it, so they share one compile. Resolver 2 unifies dev-dependency features into shared third-party crates only in an invocation that builds tests. So the car builds its devstack binaries in the same --workspace --all-targets invocation as the tests (its one cargo build line); built alone, they gave 35 third-party crates other hashes and the test build after them recompiled every workspace library (the measurement on #3343). A developer's cargo xtask dev start keeps the lighter binaries-only build with DEVSTACK_FEATURES. The operator CLI is the one binary built apart from both, alone and into target/car-cli/, so no other package's features (sqlx among them) are unified into the canopy that ships (#3414, local-dev.adoc#devstack-binaries).

  • canopy-api/test-clock and test-fault compile the settable decision clock and the /test/fault router into every test; the clock reads real time until a test moves it. The production defaults of canopy-common and canopy-api are compiled by feature-builds (lanes::FEATURE_BUILDS).

  • canopy-portal/server and preview (#1988): the portal is a bin-only crate whose tests need both, cargo has no per-target feature setting, and a self dev-dependency is invalid for a crate with no lib target. A portal test build without them stops at a compile_error! in services/canopy-portal/src/main.rs, so a bare cargo nextest run -p canopy-portal adds --features server,preview.

  • canopy-test-lib/idp-conformance builds the three gated conformance suites (CONFORMANCE_FILTER). They never skip, so INTEG_FILTER leaves them out, and the lane partition covers everything outside them; only identity matrix runs them.

A cargo xtask test -p lane passes only the selected packages' entries, because cargo refuses a feature of a workspace member the invocation did not select. A run from the archive names no features (the archive was built with them), and --verify-partition refuses a Dockerfile.integration ENTRYPOINT that names any; the car reads .gitlab-ci.yml's BATTERY_FEATURES, which a lanes.rs test pins to the constant. cargo xtask mutants mutates the portal in its own pass (Mutation testing).

Unit tests read fixture packs only (#3365)

Configuration is not part of canopy's source (ADR-051): the federal layer and each jurisdiction's pack live in their own repositories. A unit test therefore reads only the fixture layers under fixtures/config/: the packs default, test-min and test-max, over the synthetic federal layer test-federal and the neutral notice templates. A change to a real federal table or to a jurisdiction's policy cannot break the unit lane, and a fresh checkout runs it with no network.

There are two kinds of test, and the lane partition already separates them:

  • A test of a mechanism (a loader, a decision's evaluation, a refusal, a rendering path) loads a fixture pack through canopy_test_lib::config::snapshot or layer_dir, and asserts the fixture's values.

  • A test of a real pack's values (Georgia's fee schedule, its certification rows, its notice wording) lives in a module named pack_infra_tests, reads the real layers through config::pack_snapshot or pack_layer_dir, and runs in the integration lane on the car. The name ends in infra_tests, so the partition above routes it there; it needs no devstack.

A test that must hold for every pack is written once, as name_on(real_packs: bool) or name_on(pack), and filters its list of packs with config::is_real_layer. A unit test of that name runs the fixture packs; a test of the same name in pack_infra_tests runs the real ones. Each pack is checked exactly once.

The rule is enforced, not only documented. cargo xtask test --unit sets CANOPY_TEST_REAL_LAYERS=forbidden (lanes::unit_lane_env), under which canopy-test-lib panics when a test asks for the federal layer or a real pack, naming the layer and the two ways out. A bare cargo nextest run does not set it.

CANOPY_TEST_INFRA — infra tests panic, they do not skip

infrastructure_available() (crates/canopy-test-lib/src/infrastructure.rs) TCP-probes postgres AND the rules canary; a partial stack is not available. With CANOPY_TEST_INFRA=required or CANOPY_CI=true set, an unavailable stack PANICS ("skipping is forbidden") — it never returns false. Every cargo xtask lane arms required before its nextest child starts: xtask/src/bootstrap.rs::arm() pushes CANOPY_TEST_INFRA=required and a fresh CANOPY_TEST_RUN_ID last, and the nextest lanes — validate, test and coverage — arm through it (e2e reconciles the devstack through the same bootstrap but spawns Playwright, not nextest); the canopy-integration compose service sets the same variable, and CI's jobs set CANOPY_CI=true. The unit lane carries it as a tripwire: an unclassified infra test panics there instead of vacuously passing on an infra-less box. Only a bare cargo nextest run with the variable unset (or optional) prints the skip warning and returns false. A dependency-level miss after the probe passed — a token mint failed — goes through canopy_test_lib::skip_or_panic(detail), which applies the same posture (the tokens::or_skip helpers report their own miss this way, the token broker); a peer’s /livez miss is reported by TestClient::healthy_or_skip() itself, by service name and URL (#2076), so the setup guard is if !client.healthy_or_skip().await { return None; } with no skip_or_panic after it (#2079). A setup step that fails after the probe passed, such as an ephemeral schema, a pool connect, or a broker or Redis connect, goes through canopy_test_lib::ok_or_skip(result, what). It reports the error, named by what, under the same posture and answers Option, so the helper’s caller skips with a bare let Some(…) = … else { return; }. A bare .ok() in its place turns a migration error or a refused login into that same early return, a pass even in a required lane (#3132, #3133). A seed write past the probe (a test-lib client’s create_*, claim_* or seed_* call, or a raw POST) that a reachable service refuses is a defect, not an absent dependency: it fails the test in every lane with .expect(, never .ok()? or an .is_err() guard that skips (#2533). A bare eprintln!("skipping …"); return; green-passes a required-mode lane and is the anti-pattern (#1396).

cargo xtask test-lanes-lint (check 7, 2533; xtask/src/cmd/test_lanes_lint/loud_miss.rs) holds that bar over every live-test source: services//tests/, crates//tests/ and tools/*/tests/ (#3225), every [cfg(test)] item, out-of-line #[cfg(test)] mod file and infra_tests module in a src/, and canopy-test-lib. It refuses a token mint (tokens::system, portal, worker, stepped_up, cli), a bearer_sub parse, a database connect (PgPool::connect, DbPool::connect, a dialling PgPoolOptions chain, EphemeralSchema::new_for_<service>) or a broker connect (ConnectionManager::new, Publisher::from_manager_and_pool) whose miss is swallowed by .ok(), a bare ? outside a fn returning Result, or an unreporting let … else, and a seed write that turns a refusal into a skip. It accepts .expect(, ok_or_skip(<call>.await, what) with the awaited call as its whole first argument, and a match whose Err(e) arm formats {e} into skip_or_panic. Inside a fn returning Result it also accepts a bare ?, an anyhow .context(…)?, and the awaited call as the body’s tail expression, since each hands the error up typed to its caller; and a poll’s exit, if <call>.await.is_ok() { return; }, whose miss is the poll’s "not yet" and whose deadline panics (#3225). On canopy-test-lib, which implements the mints and connects, it reads seed writes only. It replaced the three per-crate loud_miss_pin_test.rs copies of canopy-applications, canopy-enrollment and canopy-security. Each rule has a floor on the sites it sees, so a scanner that stops matching fails too.

nextest profiles (.config/nextest.toml)

The thread caps are canopy’s own; the file has been canopy-owned since #2990.

Profile Threads Slow-timeout (warn × kill) JUnit

default

8

60 s × 3

test-results/unit/results.xml

integration

12

120 s × 2

test-results/integration/results.xml

validate-unit

16

60 s × 3

test-results/validate/unit-results.xml

validate

12

120 s × 2

test-results/validate/results.xml

ci

8

60 s × 3

test-results/unit/results.xml

ci-integration

4

120 s × 2

test-results/integration/results.xml

coverage

8

60 s × 3

test-results/coverage/results.xml

coverage-integration

4

120 s × 2

test-results/coverage/integration-results.xml

idp-conformance

1

60 s × 2

test-results/integration/idp-conformance.xml

The unit lane overrides its profile's cap: cargo xtask test --unit, the car's line included, passes --test-threads num-cpus, because the lane touches no devstack and the caps exist for runs that share it. On a 32-core box that took the lane from about 172 s to about 110 s with the same tests passing. The serialized [test-groups] still apply.

Every profile sets fail-fast = false. Every profile except idp-conformance replicates the serialized [test-groups] (max-threads = 1: renewals-scheduler-lock, renewals-rollup-lock, live-enact-sweep, appeals-reconcile-trigger, security-audit-archive, applications-scan-quarantine, applications-nomi-lock, applications-leg-trigger). idp-conformance runs only one gated upstream suite (Kanidm’s, Keycloak’s or ZITADEL’s), one test at a time, and carries no group: test-lanes-lint verifies every group filter against the battery build (Local Development › The conformance server). identity matrix keeps each suite’s report as idp-conformance-<idp>.xml (the identity matrix). Every profile, idp-conformance included, carries an exclusive-run override for each fleet-clock steerer. legal_date_stamp_test pins the live canopy-eligibility and canopy-snap clocks across the 2026-09-01 boundary (legal day 2026-08-31 for an Eastern pack; #2140; it replaced the #1915 eligibility-gated-clock group). renewals_test’s a_conversion_tombstone_lands_in_the_legal_month_across_the_utc_month_boundary pins the live canopy-renewals clock across a UTC month boundary (#2523). Two relative nudges move a service’s decision clock 10 s ahead and back (#3036): interview_completion_is_stamped_by_the_decision_clock_on_row_and_mirror on canopy-applications and resolve_stamps_the_decision_clock_and_honors_the_transition_table on canopy-verification. Three gated-clock proofs advance a clock by days and reset it (#3042): the eligibility tracer journeys' tracer_gated_clock_advances_overdue_classification and journey_gated_clock_advances_overdue_classification move canopy-renewals 25 days, and notices_test’s gated_clock_dispatch_evidence_tracks_logical_calendar moves canopy-notices 40 days. Each carries threads-required = "num-test-threads" and so runs with no other test in flight. #3060 retired the renewals-gated-clock group (#1835). Once #3042 moved both tracer drivers to running alone, it serialized only the feed readers (journey_partition_is_seed_portable and the two lifecycle_classification tests) against each other. That protected nothing: no advance runs beside them, and each asserts only on the households it built. every_clock_steerer_is_discovered_registered_and_isolated refuses the group if it comes back, as it does #1915’s eligibility-gated-clock. The rule: a test that writes a service’s /test/clock (an absolute pin, a relative nudge or a reset) runs alone, because the service judges and stamps every request it serves inside the window at the steered time. A nudge is no exception: a sibling that stamps one row inside the window and the next after it sees time run backwards. Tests that merely date fixtures off that clock (every SnapCaseBuilder caller) register nothing. The groups and the overrides, not the thread caps, protect those tests wherever they land. A test past the kill bound is terminated and reported TIMEOUT (#1338): split it or give it a per-test override with a written rationale, never a global loosening. The two devstack-sharing lanes (integration, validate) run at 12 threads; the constrained CI and coverage integration lanes at 4 (#1368).

Registering a clock steerer (3036). cargo nextest run -p xtask runs every_clock_steerer_is_discovered_registered_and_isolated (xtask/src/lanes/clock_steerers.rs), which discovers the steerers. It reads every .rs under services/, crates/canopy-test-lib/ and each crate’s or tool’s tests/. A file steers when it calls a post*, put*, patch* or delete* method whose first argument holds a /test/clock URL, or calls a canopy-test-lib clock helper listed in HELPERS (the journey time::advance and time::reset, and Journey::advance_clock and Journey::reset_clock). A get* call is a read. A /test/clock URL literal anywhere else fails the check, since it cannot tell a read from a write. The steering files must equal the STEERERS registry, so a new steerer fails the check by name, and so does a stale entry. Every steerer runs alone: register it with the filter that names its steering test (package(…) & binary(…) & test(=…), so the rest of its binary keeps its parallelism), and add that filter, followed by threads-required = "num-test-threads", to every [profile.*] section. There is no group or [ignore] alternative: #3042 moved the last such steerers, the tracer journeys and canopy-notices' gated-clock proof, to running alone.

Probing the clock loudly (#3060). A steering test first checks that its service has a /test/clock, because only a test-clock build serves one. The check is if !raw.test_clock_or_skip().await { return; } (TestClient::test_clock_or_skip in crates/canopy-test-lib/src/client.rs; a journey calls Journey::gated_clock_or_skip). Like healthy_or_skip, the probe reports a miss itself, naming the service, its URL and the build feature: under CANOPY_TEST_INFRA=required it panics, and only a skip-friendly lane gets false. A bare if raw.get("/test/clock").await.status != 200 { return; } reports a pass on a build without the clock, in a required lane too. every_clock_steerer_probes_its_clock_loudly therefore scans each registered steerer’s file. The file must call one of those probes, or carry an if on a /test/clock read whose block calls skip_or_panic, and must have no such if without it. The scan knows those two shapes only: a status bound by let and tested later counts as no probe, so a file with no other probe fails.

Discovery is per file: a shared harness module that writes the clock is discovered as that file, and its registration names its callers' tests.

In-process worker cadences (#1607)

Workers a test binary spawns in-process — OutboxDrainer::spawn, canopy_test_lib::chaos::spawn_outbox_drainer_for_chaos, a service booted through canopy_api::bootstrap_with — would otherwise run at their dormant production defaults. AGGRESSIVE_CADENCE_ENV in xtask/src/lanes.rs mirrors the docker-compose.yml MS knobs (CANOPY_MQ_DRAINER_TICK_MS=25 is the one an in-process drainer reads; the CANOPY<SERVICE>__*_MS knobs bite only through a service config built from env), and lanes::nextest_lane_env appends it after the armed bootstrap env for validate’s two arms, test --unit and the host integration runner; the in-network container takes its env from the canopy-integration compose service instead. The table is kept in step with compose by hand — no gate pins the two. No test oracle changes with the cadence: a race the faster tick surfaces is a fix: issue, never a widened tolerance.

What the infra lane does to the devstack Postgres (#2004)

Every infra test replays a service’s migration set into a fresh schema, so an infra arm at 12 threads is catalog churn across every database on the shared instance. The command: lines of the postgres services in docker-compose.yml therefore tune all six instances:

Setting Shared instance Per-program instances Why

shared_buffers / effective_cache_size / maintenance_work_mem

4GB / 12GB / 256MB

512MB / PostgreSQL’s defaults

The shared instance is 2.3 GiB on disk across twenty databases, so 4GB keeps the whole cluster cache-resident with headroom (#2197; vacuum_truncate deliberately stays on — the compose comment records why); the five per-program instances hold 11–50 MiB each and keep the #2004 512MB.

track_io_timing

on

on

I/O wait becomes measurable (pg_stat_database.blk_read_time, EXPLAIN (ANALYZE, BUFFERS)) instead of folding into elapsed time.

log_autovacuum_min_duration / log_min_duration_statement

1000 / 1000 (ms)

1000 / 1000

Catalog autovacuums and slow statements show in the container log at the same 1 s threshold as sqlx’s slow-statement warning.

log_lock_waits

on

on

A lock wait is named in the same log, beside the autovacuum and slow-statement lines.

synchronous_commit

on

on

Back at PostgreSQL’s default since #2201. #1288 turned it off on all six instances when a COMMIT blocked on the WAL fsync ran 9–14 s under the battery on the CoW-era host; with it on, a stalled flush is a slow COMMIT under log_min_duration_statement in the log of the instance that owns it, instead of a downstream symptom (the #2195 signature).

A compose edit lands on the next cargo xtask dev refresh (data volumes are kept). Per-crate iteration goes through cargo xtask test -p (above): a bare cargo nextest run -p <crate> has no run id, and its test_<hex16> schemas sit behind the six-hour sweep floor.

Ephemeral schemas and the post-battery sweep

EphemeralSchema::new_for_<service>(base_url) (crates/canopy-test-lib/src/db.rs; one define_ephemeral_schema_for! constructor per service database in db_constructors.rs) creates a schema named test_<run16>_<hex12> inside a battery (CANOPY_TEST_RUN_ID) or test_<hex16> under bare nextest, opens a pool scoped by search_path=<schema>,public whose every handle co-owns the schema’s drop guard (#1614), replays the service’s migrations from services/canopy-<service>/migrations at runtime (#1380 — a migration edit needs no rebuild) and stamps the schema with an ownership COMMENT (canopy-test run=<id> created=<epoch>). Connections carry application_name = canopy-test:<service>:<schema> (pools) and canopy-test-admin:<purpose> (create / lease / release / cleanup / sweep), visible in pg_stat_activity. Since #1938 the constructor first tries to lease a schema a previous test of the same service, run id and migration key released into the per-database registry (below) — a hit skips the replay after a pristine probe; a miss mints and replays as before and registers the new schema. schema.provenance() says which (Fresh or Reused { use_count }).

let schema = EphemeralSchema::new_for_eligibility(&canopy_test_lib::topology::service_database_url("eligibility")).await?;
let pool = schema.pool();                         // … drive the test …
schema.cleanup().await.expect("schema cleanup");  // closes the pool, then releases to the pool or drops

Cleanup is layered, weakest to strongest: the guard’s Drop backstop (fires when the last owner drops without a successful cleanup() and runs the same teardown — the fenced release for a pooled schema, else the DROP — to completion on a dedicated thread with its own runtime before it returns, so the process cannot exit with the lease held; it blocks the dropping thread for the release, at most 60 s, and reports on stderr a release it could not finish — #2597; before it, the backstop was a detached task the runtime cancelled at shutdown, and every lease of a test that returned without cleanup() leaked); explicit cleanup().await (preferred — closes the pool within CLOSE_DEADLINE, 10 s, and panics naming the schema and the checked-out count if a handle is still held, #1787: scope the handle so it is back in the pool first — then, for a pooled schema, the fenced release described below, else today’s synchronous DROP); and the xtask post-battery sweep (xtask/src/schema_sweep.rs), the guarantee — after the nextest arms, failed arms included, the battery drops every schema carrying its run id across every service database, leased rows included (DropPolicy::Unconditional), and a surviving current-run schema fails the battery. A constructor that fails after CREATE SCHEMA (or after a lease) compensates with an awaited, fenced DROP. Pins: crates/canopy-test-lib/tests/db_cleanup_test.rs (cleanup_releases_or_drops_per_mode, pool_clone_outliving_the_schema_keeps_it_alive_until_the_last_handle_drops, held_connection_fails_cleanup_loudly_within_the_deadline_instead_of_hanging, schemas_carry_the_ownership_comment_stamp, migration_failure_compensates_the_created_schema) and crates/canopy-test-lib/tests/db_pool_test.rs (the pool’s twenty-nine live pins; the backstop’s are a_schema_dropped_without_cleanup_is_released_before_its_process_exits — a child test process that drops its schema without cleanup() and exits leaves its row free — and a_schema_dropped_without_cleanup_under_a_straggler_is_dropped_not_freed).

Raw connections outside the pool (#2184). A test that needs a session the fixture pool cannot give it — a second connection to hold a head lock against, a disposable LOGIN role with production-shaped grants — opens it through the fixture, never by hand: schema.connect_raw("holder") and schema.connect_raw_as(&role, "canopy-test", "app") (EphemeralSchema::connect_raw / connect_raw_as in crates/canopy-test-lib/src/db.rs) return a PgConnection carrying the pool’s search_path=<schema>,public and application_name = canopy-test:<service>:<schema>:<purpose>; schema.raw_connector() is the cloneable RawConnector for tokio::spawned writers (raw.connect("writer")) and for a pool that must share the schema (PgPoolOptions::new().connect_with(raw.connect_options("one")?)). The tag is what the release’s straggler rule reads, so the contract is close it before cleanup() — drop(conn) or conn.close().await — because a helper connection still open at release drops the schema instead of freeing it (the intended refusal: no lessee inherits a foreign session; the test loses its reuse, never its correctness). purpose is a short word: Postgres clips application_name to 63 bytes, the helper clips to the same budget on a char boundary, and the pool prefix is asserted under it so the schema name always survives. A hand-built PgConnectOptions::options([("search_path", …)]) or ?options=-c search_path= URL onto an ephemeral schema is the shape the deny-list pin below rejects. Pins: a_raw_helper_connection_still_open_at_cleanup_forces_a_drop and a_raw_helper_connection_closed_before_cleanup_lets_the_schema_be_reused in db_pool_test.rs; the tag clip in db::raw_connector_tests.

Privilege assertions (#2563). has_function_privilege, has_table_privilege and their siblings answer effective privilege, so a least-privilege test that asserts a grant with them still passes when the explicit grant was dropped and a PUBLIC grant remains. canopy_test_lib::acl (crates/canopy-test-lib/src/acl.rs) reads the object’s ACL instead: assert_privilege(pool, role, &AclObject::…, privilege, Expect::Granted) requires the role’s own aclexplode entry (the default ACL standing in for one never set), Expect::Denied requires the effective privilege to be false (no direct, PUBLIC or inherited grant), and public_privileges with owned_objects sweeps every object a role owns for a PUBLIC entry. The chain-v2 substrate suites (services/canopy-{security,tanf,medicaid}/tests/chain_v2_substrate_test.rs) are the reference uses.

Schema reuse (#1938; plan Ephemeral-schema reuse). Each service database carries a registry schema canopy_test_pool_<sha8> — sha8 is the hash of crates/canopy-test-lib/src/db_pool/registry.sql, so a different test-lib version is a different registry — with one leases row per pooled schema (service, run id, migration key, catalog fingerprint, seed rows, ledger count and head, state, owner ticket). The key hashes every migration file’s sqlx checksum, the idempotency DDL, the registry SQL and CANOPY_TEST_SCHEMA_REUSE_SALT; a schema is leased only under an equal key, one statement with FOR UPDATE SKIP LOCKED, so a migration edit never reuses a stale schema and two tests never share one. cleanup() runs one fenced transaction: lock the row, verify this test’s ticket, look for stragglers, then — under session_replication_role = replica, so no append-only guard or FK trigger fires — TRUNCATE the tables the test wrote to (one statement; the rest of the schema and the ledger are left untouched — a DELETE left heap and index pages that flipped an EXPLAIN pin after a few reuses), reset planner statistics, restore the migration-seeded rows, compare the catalog fingerprint (tables, columns, defaults, constraints, indexes, triggers, policies, rules, full function definitions, types, views, ownership and grants) and the ledger; all equal → the row goes free; anything else → DROP SCHEMA … CASCADE and the row is deleted, exactly the old teardown. Every destructive path — the Drop backstop, the compensating drop, the cleanup fallback, the sweep — goes through drop_if_owner, which locks the row and acts only when the caller’s ticket owns it (or no row exists).

Stragglers: a backend tagged with the schema (other than the pool’s own connections) or one holding a lock on the schema’s relations at release makes the schema drop, never free; a writer mid-transaction makes the release fail loudly within its 3 s lock_timeout with the row still leased, and the sweep collects the schema. A test’s own raw connection is visible to that rule only through its tag (connect_raw, above); an idle, untagged one cannot be attributed to a process on the devstack (Docker’s userland proxy hides client ports; helper pools grow after the schema exists), so the files that still build an untagged search_path-scoped connection by hand — the bare-schema harnesses in db_pool::RAW_CONNECTION_SUITES, plus db_replay_test, whose concurrency pin exists to exercise the replay a lease would skip — never reuse (they replay and drop as before); every_raw_connection_suite_in_the_tree_is_listed fails on a new untagged site anywhere under services/ or crates/, and the fix is connect_raw, not a longer list. The chain suites (chain_v2_substrate_test, chain_v2_append_test, chain_append_drainer_test, audit_archive_test) and scan_quarantine_test pool since #2184. Reuse is off, loudly, for a non-superuser role and under CANOPY_TEST_SCHEMA_REUSE=0. Two report-only records (#1922): [canopy-measure] ephemeral_schema … reused=<bool> use_count=<n> (on a hit replay_ms is the lease and probe time) and [canopy-measure] ephemeral_schema_release … outcome=<freed|dropped-<reason>|dropped-unpooled|not-owner|no-row|error> total_ms=… — dropped-unpooled is the awaited cleanup() of a schema that never leased (a bare, reuse-off or RAW_CONNECTION_SUITES schema), so awaited-versus-backstop teardown is observable for every suite (#2185). A reused schema differs from a fresh replay only in reset statistics, seed-row timestamps and the ledger’s installed_on; the post-battery sweep still drops every current-run schema, so a pool lives for one battery (a bare cargo nextest run -p reuses across local runs within the pool’s five-hour age bound; the sweep’s six-hour floor collects what remains).

Another run’s schemas are never swept without positive inactivity evidence: a stamp older than six hours AND no backend naming the schema in its application_name or holding a lock on one of its relations. The battery lease cannot prove a bare cargo nextest, another worktree or an in-network validate dead, and a sweep landing in a foreign run’s migration window would redirect its unqualified DDL into public. Unmarked schemas are reported, never auto-dropped. The explicit, lock-held path is cargo xtask dev sweep-schemas [--older-than <hours>] [--include-unmarked] (default 6 h).

Reclaiming dead leases (#2595). A test that is killed or crashes before its Drop backstop runs leaves its row leased (before #2597, so did every test that returned without cleanup()); a battery’s own pass drops its run’s rows, but a bare run’s (local) were never collected — 7,822 in canopy_snap and 1,212 in canopy_web by 2026-10-03, and the sweep took 214–327 s probing them. The sweep now reclaims a lease whose run is provably gone: another run’s, stamped, its stamp and its row’s created_at past the six-hour floor — past the pool’s five-hour lease bound, so the row’s ticket is the last owner the schema will have and it has held the schema for over an hour, against nextest’s 240 s kill — and nothing referencing it (the rule above). The drop goes through drop_if_owner with the ticket the sweep read, so a row released or re-leased since is left alone. A database restart is not evidence (it kills no client); the definition and its one residue are the module docs of canopy_test_lib::db_pool::older_runs. Each database’s evidence is one read — its test schemas, its leased rows, pg_stat_activity and pg_locks — judged in memory, and four databases are swept at a time. One post-battery sweep reclaims at most 1,000 dead leases per database, oldest first, so a backlog of N drains in ⌈N / 1000⌉ sweeps (2026-10-03’s takes eight); sweep-schemas reclaims without a bound and needs at least six hours for a lease whatever --older-than says, and collects an older test-lib build’s registry once every row is past the floor and none is leased on a schema that still exists (a leased row whose schema the sweep dropped no longer keeps it, stale_registry_infra_tests in db_pool.rs). The stage ends with one line: [schema-sweep] reclaimed N dead lease(s) across D database(s) (M deferred to the next sweep, R refused by the fence); older dropped=… failed=… in S s. Pins: the six reclaim pins in db_pool_test.rs (a dead run’s lease is reclaimed; a lease with a backend attached, one an untagged lock holder is inside, or one under the floor on either clock is kept; a backlog larger than one batch drains a batch per pass; a ticket changed after the snapshot is refused) and the verdict pins in db_pool::older_runs::tests.

Never sweep a shared prefix from a test. sweep_schemas(base_url, like, not_like) drops every schema matching like. nextest runs crates as separate processes against the same devstack Postgres, so a fixture that sweeps test_% drops a sibling test’s live schema, and that test fails later with relation … does not exist (42P01) — an idle pooled connection whose search_path names the schema holds no lock that would block the DROP. The automatic caller passes run-scoped patterns only; a fixture mints its own unique prefix and sweeps only that (sweep_schemas_drops_matching_and_is_idempotent in db_cleanup_test.rs is the pattern).

Replay locking (#1392, #1808). run_service_migrations walks the migrations itself and picks a lock per migration from global_ddl::scan(&sql).lock_policy() — the same classifier cargo xtask migrations-lint enforces (the global DDL contract). LockPolicy::None — CREATE TABLE, ALTER TABLE, indexes, inserts, everything search_path scopes — applies with no lock, so concurrent constructors replay in parallel; LockPolicy::Always (a locked-class or forbidden statement, or an explicit -- global-ddl: marker) takes exactly sqlx’s per-database migration lock; LockPolicy::IfExtensionAbsent(names) locks only while a CREATE EXTENSION IF NOT EXISTS target is still missing. Live pins: crates/canopy-test-lib/tests/db_replay_test.rs.

What git push runs

.githooks/pre-push (canopy-owned since #2989; activate with git config core.hooksPath .githooks && chmod +x .githooks/*) runs two steps in order. A pure branch deletion skips them both.

  1. cargo xtask test --unit — fmt, clippy and the unit lane; no devstack.

  2. git lfs pre-push — if git-lfs is installed.

That is all git push runs. GitLab's reject_unsigned_commits push rule refuses an unsigned commit server-side (#3249). If those pass, the change ships into the merge train, whose pipeline on the dhs-aws-autoscaler-docker-4xlarge runner runs the whole battery and owns correctness (CI is the gate). Nothing else is asked of anyone locally; cargo xtask validate, cargo xtask e2e and the other subcommands below stay tools a developer may run by hand.

Every run that reaches step 1 ends with a step-timing table on stderr, headed === pre-push: step timings ===: one <N>s <step> line per step that ran, then <N>s total (#3008). It prints after === pre-push: OK === on a pass, and after the failing step on a failure; the hook’s exit code is the step’s, unchanged. A branch deletion prints none. The helpers are .githooks/lib/step-timing.sh, which the hook sources.

cargo xtask validate

Flags: --skip-docker, --timing (xtask/src/cmd/validate.rs). Host tooling: cargo-nextest, cargo-machete and cargo-deny are hard preflight requirements (cargo install <tool> --locked); without glab the visibility gate prints SKIP. The battery is fail-fast over the 73 stages predeclared in xtask/src/validate_report.rs::STAGES, in this order (every stage not marked advisory blocks; a stage marked background is a job joined there, Background jobs (CANOPY_VALIDATE_BACKGROUND, #2612)). A stage that runs out of this order fails the run (#1267). A stage id the inventory does not list is an error, naming it, at every harness entry point that takes one (#2624):

Group Stages

Bootstrap

sysmon-reset, reconcile-ports-env, secrets-decrypt (advisory), secret-floor-write (advisory)

Repository

preflight, visibility, signing, docs (the sync manifest’s mandatory-content pages), spdx

In-process gates

plan-lint, rules-lint-inputs, processing-days-parity, audit-literals, audit-unwraps, jurisdiction-literals, neutrality, determination-status, completeness-reads, typed-ids-path-uuid, http-clients-timeouts, http-clients-redirects, http-clients-builders, secret-loads, db-pools, retention-deletes, route-authz, web-paths, ssn-reads, outbox-migrations, mq-topology, call-graph, delegated-routes, xtask-unix-guard

Toolchain

deny (cargo deny check: advisories, bans, licenses, sources; an advisory with no upstream fix needs an annotated deny.toml [advisories].ignore entry, #2239), fmt, machete, rules, vendor-check, capabilities, quality-budgets

xtask sub-gates, clippy

secrets-yaml-lint, config-in-source-lint, migrations-lint, ci-config-lint, test-lanes-lint (--static), data-tenancy, policy-audit, policy-audit-federal, policy-drift (georgia), action-coverage, input-coverage, scenarios-audit, extension-fixtures, shipped-features, contested-surfaces, clippy (background; --all-targets --features <BATTERY_FEATURES> --profile test: the battery's one set, the gated conformance suites included, which only ci identity runs), feature-builds (clippy in both profiles and rustdoc over each lanes::FEATURE_BUILDS combination no lane builds, #2249, #2512, among them the canopy-portal wasm32 client, linted for wasm32-unknown-unknown with dioxus/web and -D warnings, its binary alone and in the dev profile alone since its dev-dependencies are native-only, #2527, #2294; the catalog)

Devstack

devstack-project-name, devstack-warm (background, advisory), devstack-ready (ensure_ready), devstack-observability, ports-refresh-post-devstack, api-docs (OpenAPI drift against the live stack)

Tests, doc passes

nextest-build, lane-partition, nextest-unit (validate-unit), nextest (validate), schema-sweep (runs even after a red arm), test-report, rustdoc-private (background; cargo doc --workspace --no-deps --document-private-items --lib --bins --features <BATTERY_FEATURES>, -D rustdoc::broken_intra_doc_links -D rustdoc::invalid_html_tags, in its own target/doc-private; it subsumes the #1981 xtask-bin pass, #2253), doctest

Docker

docker-build, image-cleanup (advisory) — skipped under --skip-docker

Background jobs (CANOPY_VALIDATE_BACKGROUND, #2612)

Three long stages, each sharing no state with the stages that run beside it, run as plain child processes (xtask/src/validate_bg.rs), spawned once, right after the repository stages, and joined at their own inventory position:

Stage Job Joined before

rustdoc-private

the rustdoc-private pass above

doctest

clippy

the clippy gate above

feature-builds, which builds in its target dir

devstack-warm (advisory)

docker compose -p <project>-validate-warm --profile <stored profile> build with devstack-ready's build env (#2614, ADR-047 Amendment 9). It runs only when the devstack markers call the images stale, never on an in-network run; its images carry tags the running stack never reads.

devstack-ready, whose own build then finds every layer cached

A job’s stdout and stderr go to test-results/validate/<id>.log; nothing is teed. At the join point the stage records the job’s outcome and the time from its spawn to the join, which overlaps the stages run meanwhile, so the --timing rows no longer add up to the total. A failed job’s log is echoed to stderr, and its tail is the stage’s diagnostics (under stderr, since both streams share the log); a failed warm build is recorded and validate carries on. A failing validate kills and reaps every job it has not joined, so no background cargo or docker outlives it; a killed cargo’s compiler children may finish the unit they are compiling. The jobs stay in validate’s process group, so a terminal Ctrl-C reaches them as well. clippy prints no #1920 compile-churn line now that its output goes to the log.

CANOPY_VALIDATE_BACKGROUND=on runs the jobs in the background; off runs each inline at its join point, with the same command and the same log, so only the timing differs. Unset or empty, the jobs run in the background on a host with at least 16 cores (std::thread::available_parallelism) and inline otherwise. Any other value fails the preflight stage.

The validate report (test-results/validate-report.json, #1253)

Gate stages run before the tests, so an early failure would leave the previous run’s green JUnit in place. After a failed run, read this one file: it is always present, atomically written and self-describing — state (running means killed by a signal; interrupted; pass; fail with failed_stage), runner (host \| in-network), git provenance, every stage with its policy and execution, redacted diagnostics for the failing stage, and the embedded nextest JUnits with each failed test’s captured output. Each stage’s capture is full-tee (a teed child), captured (a query child whose stdout is the value, so it is collected rather than echoed, or a background job’s log), error-chain-only (no subprocess on the failing path) or na (#1255). Its scope is validate only: the pre-push hook’s steps and the other subcommands (e2e, perf, the identity matrix) are outside it, and it never proves remote delivery — git ls-remote does. Validate owns test-results/validate/ exclusively; both JUnits are deleted at bootstrap so an interrupted battery cannot leave a stale green, and a failing arm’s JUnit is copied to failed-<epoch>-<name>.xml beside the original. cargo xtask validate runs one RunSampler (xtask::sysmon, Linux /proc) for the whole battery: a JSONL line per second in test-results/resource-samples.jsonl, each stamped with the stage that was running and carrying CPU/PSI/memory/swap plus filesystem headroom for the repo and the docker root — free and total bytes, and on btrfs Device unallocated, the figure that explains an ENOSPC df cannot (#2190). The filesystem block is re-read every 30 s and stamps its own sampled_at. A sampler that cannot start, cannot write, or wrote nothing becomes a notes entry on the sysmon-reset stage. cargo xtask test/e2e keep their per-phase 1 Hz SysMonitor (a one-shot summary line beside any FAIL) and append to the same stream; only validate truncates it. Diagnostic only — low load during a failure is evidence of a real bug (#653).

Load is never the cause of a test failure. A pegged-CPU or PSI sample says where to look; it does not name a cause. The cause is always our code — an inefficiency, a serialization point, a race — and the fix lands there. Widening a timeout or acquire budget, lowering test-threads, adding a sleep or a retry, or moving the test to a quieter lane makes the symptom go away and is not a fix (TestClient::with_retry below is for tests of retry semantics, never for suppressing a failure). This is the cadence rule (worker cadences) stated generally: a race that faster ticks or a busier host surfaces is a defect, never a widened tolerance.

E2E (Playwright in Docker)

cargo xtask e2e (xtask/src/cmd/e2e.rs) builds and runs the canopy-e2e compose service (tests/e2e/, the pinned mcr.microsoft.com/playwright image; a type error fails at image build) against the devstack. Flags: --no-refresh, --devstack-profile snap-only|full (default full), --seed <u64>, --households <n>, --visual, --capture, --jurisdiction <slug> (default georgia), then -- <playwright args>. Run sequence: project lease → reconcile ports → unless --no-refresh, ensure_ready → the profile check → for full without --no-refresh, an up -d of the stored profile and a whole-stack health wait → feature-build probes when required → artifact-routing pin → re-seed through cmd::seed::run → compose build canopy-e2e → the devstack CA into canopy-e2e's inputs and the ingress leaf’s pin (Signing the battery in) → the token broker up → compose run --rm canopy-e2e → the post-run gates below. No storage state survives a run: auth-setup mints it inside each run’s container.

After Playwright, passing or failing, the run prints its five slowest test cases under e2e: slowest specs, each as <seconds>s <spec> › <title>, read from the time attributes of this run’s test-results/e2e/results.xml (#3008). A case with no time is not ranked. A report this run did not write prints nothing, and the list never changes the run’s verdict.

The profile check (#2603): the refresh builds images only for the devstack’s stored profile (.devstack/profile), so a run whose --devstack-profile that profile does not cover is refused, naming both profiles and the rebuild (cargo xtask dev reload --profile full). Bringing the missing services up would start them on images the staleness guard never built. Only full covers another profile; xtask’s full_profile_runs_every_deployment_service test pins that against docker-compose.yml.

The battery and the journey-lane gate (#1386)

A bare cargo xtask e2e — profile full, no trailing args — IS the blocking battery. It needs three standing devstack properties, all sticky across refreshes: the full compose profile, the test-clock build and the test-fault build. Set up once with

CANOPY_CARGO_FEATURES=canopy-api/test-clock,canopy-api/test-fault cargo xtask dev start --profile full

The two builds belong to the battery’s two feature lanes (FEATURE_LANES, xtask/src/cmd/e2e.rs): one row per feature, holding every spec that guards on it, and those specs test.skip on a stack without it. The clock lane needs canopy-api/test-clock: the journey project (multi-life-event specs that advance the fleet’s logical clocks) and the three caseworker specs that guard on the fleet clock, clock-bff.spec.ts, flow-snap-periodic-report-filing.spec.ts and worker-portal-held-determinations.spec.ts. The fault lane, the fault project (#1325: the dashboard’s error and timeout states under faults injected through /test/fault), needs canopy-api/test-fault. The journey and fault projects run after the other projects via Playwright project dependencies, fault last. xtask’s every_feature_guarded_spec_is_in_its_lane test fails on a spec that calls a lane’s guard probe (clockFleetStatus(), faultsAvailable()) without being one of that lane’s specs, so no guarded skip goes uncounted. Before the suite the runner probes each lane’s control surface — /test/clock and /test/fault on canopy-applications (CANOPY_PORT_CANOPY_APPLICATIONS_8003; canopy-web, which mounts /test/clock too, publishes no host port, and one builder image builds the whole fleet) — and fails in seconds on a stack without the feature, printing the rebuild, which names the whole battery set so fixing one lane never drops the other:

CANOPY_CARGO_FEATURES=canopy-api/test-clock,canopy-api/test-fault cargo xtask dev reload

In-suite, clockFleetStatus() (tests/e2e/lib/clock.ts) probes every clock-bearing service once per worker, and faultsAvailable() (tests/e2e/lib/fault.ts) every faultable one. After a green exit the battery verifies that test-results/e2e/results.xml was written by this run, that the journey and worker-determination-ele projects executed at least one test with zero skips (every journey skip-guard marks an unhealthy battery: non-clock build, missing profile, missing seed), that a walkthrough artifact was written during the run (#1409), and that each feature lane executed at least one test with zero skips (#2602): a skipped fault or clock-guarded spec fails the battery, as a skipped test does in a CANOPY_TEST_INFRA=required nextest lane. A targeted run is exempt from the whole-lane gate but keeps the reality watchdog: a JUnit claiming executed journey tests with no fresh artifact fails loudly. A targeted selection that names a feature lane (its --project, or a positional naming one of its specs) carries that lane’s probe and zero-skip check (#1852).

The fault lane runs in the battery, on the battery’s own devstack, rather than in a lane of its own (#2602). The fleet is built from one builder image with one feature set, so a separate fault lane would need a second build of every service. The test-fault surface exists only in a feature build (canopy_api::test_fault_router), so it costs a production image nothing. The lane runs last and clears every fault in a finally (withFaults), so it degrades no other spec.

The harness retries nothing (#1689)

tests/e2e/playwright.config.ts sets workers: 1 and retries: 0 unconditionally, and no helper re-runs a failed navigation or action (submitWorkerAction in tests/e2e/lib/helpers.ts makes one attempt, #1851). A timeout under battery load is inefficient code, a serialization problem or a race — the run that surfaced it is the suite working. Waiting for state the system reaches on its own (pollUntil, the poll* helpers, the token broker’s own wait-out of a person’s sign-in spacing or an unavailable issuer) is not a retry. An unexplained failure is a fix: issue carrying the trace; the trace, not a second run, is the report.

Where a failure’s artifacts land (#1902)

Playwright’s outputDir is /e2e/test-results, a tmpfs — RAM on purpose, because mid-test writes through the host NVMe were #1374 / #1341; /e2e/results is the host bind of ./test-results/e2e. As each test ends, the retained-artifacts reporter (tests/e2e/lib/retained-artifacts-reporter.ts) copies that test’s trace.zip, test-failed-*.png and error-context.md (failures only; trace: 'retain-on-failure') into test-results/e2e/artifacts/<test>/ and rewrites the attachment path, so results.xml resolves them relative to test-results/e2e/. cargo xtask e2e prints the directory on both exits; CANOPY_E2E_ARTIFACTS_SUBDIR moves it within the same mount. The pairing is pinned: the runner parses playwright.config.ts and docker-compose.yml before the suite, and xtask’s artifact_routing_matches_the_compose_mounts test fails the push if the outputDir stops being a tmpfs or the results mount stops being a host bind.

CAUTION
a trace.zip records request headers — for the worker lanes, the worker’s session cookie and the given helpers' bearer tokens. Treat a trace as a credential: read it locally, never attach one to an issue, an MR or a chat.

A context’s cookies are chosen, never inherited (#2537)

A context built with browser.newContext() inherits every project use option, storageState included, so a bare one in a caseworker project starts with the worker’s canopy-web session cookie. Every .newContext( call in tests/e2e therefore names its storageState, whatever its receiver is called (a Browser handed to a helper under another name is checked too; only request.newContext(, the API-request factory, is exempt): { cookies: [], origins: [] } for a fresh context (an applicant on the portal, a throwaway sign-in), a state file such as 'auth/caseworker.json' for a signed-in one. cargo xtask e2e checks every .ts under tests/e2e before the suite (cmd::e2e_contexts, comments ignored), and xtask’s the_shipped_suite_names_every_browser_context_storage_state test fails the push on a call that leaves it out.

Signing the battery in

The battery reaches canopy-web as a browser does: at its https origins, CANOPY_E2E_BASE_URL (https://web.canopy.test:<W>;) and CANOPY_E2E_XSITE_BASE_URL (https://web.canopy-xsite.test:<X>;), the ingresses' network aliases and reserved ports, the same strings canopy-e2e and the host use. canopy-web publishes no http port. cargo xtask e2e brings the token broker service up for every run, and every worker signs in through it.

  • TLS trust. Chromium pins the ingress leaf’s SPKI battery-wide: xtask computes CANOPY_E2E_WEB_SPKI (base64 SHA-256 over the leaf’s SPKI, devstack_tls::web_leaf_spki) from the leaf it generated, and playwright.config.ts adds --ignore-certificate-errors-spki-list=<pin> to every project’s launchOptions (lib/identity/pinned-browser.ts's webPinArgs, which throws outside cargo xtask e2e). Node (the APIRequestContext calls, context.request) trusts the devstack CA through NODE_EXTRA_CA_CERTS, the CA xtask installs before every run into canopy-e2e's canopy_e2e_inputs volume (read-only at /e2e/inputs) through a one-off of its image; CI’s daemon sees no job files, so it is no bind mount. ignoreHTTPSErrors is never used, which xtask’s canopy_e2e_reaches_canopy_web_over_pinned_tls test checks across the suite.

  • auth-setup. auth/setup.ts signs its nine workers in afresh on every run and saves their storage states inside the run’s container; nothing is mounted from the host or kept between runs, so no state outlives the canopy-web session it names. Each sign-in is lib/identity/sign-in.ts's signInWorker(page, person, origin): canopy-web’s /login (the AC-8 notice), Continue, the upstream’s authorization answered by the broker (routeUpstreamSignIn, below), the callback’s handoff, and the landing page, resolved once the nav names the worker. canopy-web reaches the upstream by a 303 from /login/start, and Playwright routes no redirect’s target, so routeSignInStart fetches that 303 unfollowed and fulfils it as a page that navigates to its Location by script, carrying canopy-web’s flow cookie; startWorkerSignIn stops after Continue, for a spec awaiting a refusal page instead.

  • Budgets. auth-setup, auth, auth-cross-site, journey (two journeys sign the caseworker in inline) and identity-plane take the identity-plane budgets: timeout: 300_000 and navigationTimeout: BROKER_BUDGET_MS.

  • auth.spec.ts (project auth) asserts canopy-web’s own sign-out: the CSRF-checked POST answers a handoff to /login (Kanidm, the default upstream, advertises no end-session endpoint) setting canopy_reauth and clearing the session cookie, /login shows the ruleset’s notice, the session is over, and the next sign-in asks prompt=login, which the headless route refuses without a broker call. It also asserts sign-out’s durability across tabs and against a replayed cookie, and jane.unscoped’s refusal page (missing_primary_programs, 403, on the callback’s own URL, not restarted). The stale-SSO restart (auth_time_too_old, retried once with prompt=login) has no browser trigger: canopy-identity judges a sign-in’s age on the wall clock and Kanidm stamps it from the UAT the broker just made, so its single retry is canopy-web’s route test.

  • auth-cross-site.spec.ts signs jane.caseworker in at the cross-site origin: the Lax flow cookie reaches the callback without a planted Strict probe, the callback answers the handoff, and the handoff’s own navigation carries the SameSite=Strict session cookie.

  • The given helpers. lib/given/auth.ts mirrors canopy_test_lib::tokens (Identity: the canopy-identity token broker (crates/canopy-test-lib/src/identity_broker.rs)) over the broker service: worker(ctx, person, target), steppedUp(ctx, person, target), system(ctx, client, target), portal(ctx, target, scope?) and cli(ctx, person, target), each answering the bearer or throwing BrokerCallError (a refusal) or BrokerUnreachable (the service could not be reached). orSkip holds the same helpers answering null only when the broker is unreachable, a refusal still thrown. cast(username) maps a pre-switch test username to its cast person, and systemCaller(target) is system_caller's rule as a table, which xtask’s the_ts_system_caller_table_is_the_rust_rule test holds to the compiled edges; systemArm(ctx, target) is system for that caller, a system() route’s token. held(mint, initial?) holds a bearer across a poll, minting it again once it is HOLD_MS (60 s) old. The receivers and clients are typed (CanopyService, ConfidentialClient, SystemCaller). A call site maps by the helper rules below (Choosing the helper), as the Rust battery’s do, and a token is for one target: the given library’s Tokens bundle holds one bearer per service, canopy-verification’s being canopy-applications' system token, which the exact-caller batch-context read requires.

The identity-plane project (ADR-049 Amendments 24 and 26)

The identity-plane project (specs/identity-*.spec.ts) proves the harness against canopy-identity directly, on whichever upstream the devstack runs. Its token and stand-in specs sign nobody in to canopy-web, so it has no storage state and no auth-setup dependency; its @identity specs sign in through the upstream’s own pages and canopy-web’s real redirect chain.

  • The client. lib/given/broker.ts's TokenBroker calls the service (CANOPY_TEST__TOKEN_BROKER_URL): delegation, steppedUp, system, cli, authorise, uiCredentials, upstream, and for the vendor specs createPasswordOnlyAccount, deleteAccount and redeem. Each answer is checked against its shape, a refusal throws BrokerCallError (its status, class and public reason), and a request that never reached the service throws BrokerUnreachable. It never retries. A call can wait out a person’s 30 s sign-in spacing, a fresh TOTP step and the broker’s 90 s retry, so the project’s navigations and every wait around a broker call get BROKER_BUDGET_MS (150 s).

  • The verifier. lib/identity/jwks.ts's verifyIdentityToken(token, jwks, {issuer, audience, maxLifetime, now}) checks a token with node:crypto alone. It must be ES256 with typ at+jwt, under a P-256 key whose kid is its RFC 7638 thumbprint, and name the issuer and exactly one audience. It must also meet the receivers' time rules: a lifetime of 1 s to maxLifetime (300 s for a delegation token, 600 s for a system token), iat and nbf no later than now + 60 s, and now before exp + 60 s.

  • identity-tokens.spec.ts checks four token cases against canopy-security’s JWKS:

    • jane.doe's delegation, with act canopy-web and a narrowing reflected in its roles;

    • jane.admin's stepped-up token, from a sign-in at most 300 s old;

    • canopy-eligibility’s system tokens for applications, enrollment, persons and rules;

    • the verifier’s refusals over a key the spec generates, with a valid control.

      It also checks the broker’s 404 for a person outside the cast and its 502 missing_primary_programs for jane.unscoped.

  • Headless sign-in. lib/identity/sign-in.ts's routeUpstreamSignIn(context, broker, person, upstream) routes the browser’s navigation to the upstream’s authorization endpoint, the one its discovery advertises (upstream.authorizationEndpoint; ADR-049 Amendment 26). It sends the query, exactly as the browser wrote it, to the broker’s authorise, which uses the person’s sign-in at the upstream. It then continues to the query’s own redirect, one of the broker’s registered redirectUris (one per canopy-web origin), with the upstream’s code and state, through a page that redirects by script: Playwright 1.60 does not follow a fulfilled 3xx on a navigation. It refuses an unregistered redirect and a prompt=login query without a broker call; a re-authentication goes through the upstream’s page object. canopy-web’s own sign-in uses it through signInWorker (Signing the battery in). lib/identity/stand-in-rp.ts stands in for canopy-web at its registered origin with canopy-web’s authorization query plus a nonce, at the discovered endpoint with the profile’s scopes, prompt=login or max_age when asked. It names its PKCE verifier, nonce and redirect, so a spec can have the broker redeem the code.

  • identity-sign-in.spec.ts signs jane.admin.snap in moments after a sign-in. The navigation waits out the 30 s spacing within the budget, the callback carries the stand-in’s state and the upstream’s code, and no browser request reaches the upstream but the routed one. The spec also checks both refusals.

  • The upstreams' own pages (@identity). Each supported upstream has a page object and a spec, and each spec skips, naming the running upstream, unless the devstack runs its own. A page object answers whichever step is showing, waits for that step to move on, and fails on any other, naming the page. It also says how its login returns to the relying party: by a server redirect, or by its page’s own navigation.

    • lib/pages/kanidm-login.page.ts: Kanidm’s form#login steps, the username (/ui/login/begin), the TOTP code (/ui/login/totp) and the password (/ui/login/pw); it returns by redirect.

    • lib/pages/keycloak-login.page.ts: form#kc-form-login (the username, unless Keycloak shows the one it knows, and the password), then form#kc-otp-login-form; it returns by redirect.

    • lib/pages/zitadel-login.page.ts: Login V2’s test ids, username-text-input, password-text-input and code-text-input, each submitted by submit-button, a step waiting for the URL to change or ZITADEL’s error; it returns by its page’s navigation.

  • The pinned browser. lib/identity/pinned-browser.ts's launchPinnedChromium(upstream, alsoPinned) first verifies the upstream’s leaf against the devstack CA from the broker with Node’s TLS, then launches Chromium with that leaf’s SPKI pinned, beside the ingress leaf’s when asked. It is a leaf pin because Chromium’s list matches any presented certificate, chained or not, and the CA certificate is public. ignoreHTTPSErrors is never used.

  • The shared walks (lib/identity/upstream-ui.ts).

    • signInThroughUpstream is the real redirect chain at one of canopy-web’s origins: a Chromium pinned to the upstream’s and the ingress’s leaves goes /login, Continue, canopy-web’s 303 to the upstream’s pages (the page object, with the broker’s UI credentials), the upstream’s return to the callback (by redirect or navigation, as the page object says), and the handoff that lands the worker signed in. A planted Strict probe shows the return same-site at canopy-web’s origin and cross-site at the other, and at both the handoff’s own navigation carries the SameSite=Strict session cookie.

    • expectFreshness signs in through the stand-in four times: through the login pages; again, where the SSO session answers with no login page and the same auth_time; with prompt=login, which shows the login pages and yields a later, current auth_time; and with a max_age the session has outlived. The broker redeems each code and verifies its id_token, and the id_token echoes the nonce. The last step is the spec’s to state: reauthenticates (Kanidm’s and Keycloak’s login), or answers-from-the-session with the earlier auth_time (ZITADEL’s, zitadel/zitadel#12258, tracked by #2906).

  • The specs.

    • identity-kanidm-ui.spec.ts: an unpinned Chromium refuses Kanidm’s certificate. jane.auditor.snap signs in through Kanidm’s pages from a stand-in prompt=login query; the callback request carries the stand-in’s state and a code. The worker sign-in runs at each origin (jane.supervisor.snap at canopy-web’s, canopy.admin at the cross-site one). The callback is read from its request because the upstream’s redirect to canopy-web’s origin is not routed, and its page does not load: that browser pins the upstream’s leaf alone, so the ingress fails its TLS.

    • identity-keycloak-ui.spec.ts and identity-zitadel-ui.spec.ts: the unpinned refusal; the worker sign-in at each origin; expectFreshness for jane.auditor.snap; a throwaway account with a password and no second factor (createPasswordOnlyAccount, deleted afterwards), which Keycloak refuses ("credential setup required") and Login V2 sends to set up a second factor, the relying party never reached; and jane.chip-worker’s sign-out through canopy-web, which goes through the upstream’s end-session endpoint back to /login.

  • Running them. cargo xtask e2e --no-refresh — --project identity-plane runs the project against the devstack’s upstream, and cargo xtask e2e prints which upstream that is. cargo xtask identity matrix --all --e2e runs it on each upstream in turn (Local Development › the identity matrix).

Targeted runs (#1852)

cargo xtask e2e                                                    # the battery
cargo xtask e2e --devstack-profile snap-only                       # SNAP-only iteration; whole-lane gate skipped
cargo xtask e2e --no-refresh -- specs/intake.spec.ts               # one spec; --no-deps + auth/setup.ts added for you
cargo xtask e2e --no-refresh -- specs/journey-snap-lifecycle.spec.ts --project journey
cargo xtask e2e --no-refresh -- --grep "dashboard"                 # the pattern is OR'ed with "authenticate as"
cargo xtask e2e --no-refresh --capture -- --project demo-review    # capture sweeps are opt-in, never in the battery
cargo xtask docs screenshots                                       # passes --capture itself

Two rules key on the selection, not on "are there trailing args":

  • A positional spec path implies --no-deps: a file filter binds only the selected projects while each project’s dependencies run unfiltered, so one journey spec used to drag the suite in behind it. auth/setup.ts is added to the filter so auth-setup still mints the storage state no run’s container starts with, and --project=auth-setup only when you narrowed --project yourself and left it out. Spell specs as the container sees them (specs/<name>.spec.ts, optionally :<line>); a leading tests/e2e/ is stripped (#2077). A run that selected nothing but the logins fails, naming the selection.

  • A selection naming the journey lane (a journey-*.spec.ts, --project journey) requires the test-clock build and carries the zero-skip contract: skipped is not an acceptable terminal state for a journey spec you named.

CAUTION
--project is Playwright’s one variadic option — a spec path written after it is read as a second project name. Put positional spec paths first.

Devstack fault injection (/test/fault, #1325)

Services built with canopy-api/test-fault serve an unauthenticated /test/fault (GET reads, POST sets { "latency_ms": … } and/or { "status": … }, DELETE clears), applied by middleware on the /v1 router only — /livez, /readyz and /test/* stay healthy under injection. Compile-stripped like /test/clock (ADR-033 §5). Playwright drives it through tests/e2e/lib/fault.ts (withFaults(ctx, {…​}, body), always clearing in a finally); the fault project runs after the journey lane because the spec is process-global. Build with CANOPY_CARGO_FEATURES=canopy-api/test-clock,canopy-api/test-fault cargo xtask dev refresh; specs/fault-injection.spec.ts is the controlled-failure proof for the worker dashboard’s degraded arms, and specs/fault-determine-outlives-the-bff.spec.ts proves a determination canopy-web stopped waiting for still reaches the application (#3202): it holds canopy-snap’s router, so the determine is in flight when canopy-web gives up. specs/fault-write-paths.spec.ts is the write side (#1596): an intake section save that meets a failing canopy-applications keeps what the worker typed, shows the failure in the row, and saves on the next click; and a case page whose upstream is down answers 500, not the 404 of a case that does not exist; and a notice download whose upstream is down answers 502 with an error page, never a PDF, as does a document download, which the test uploads and waits for the content scan to clear; and a SNAP process-page write action whose pre-read fails answers 502, not the 404 of an unknown application and not a success redirect; and a case action whose upstream is down says it failed and never sends the redirect that reports a recorded action.

CI vs local

Locally, git push runs signatures, cargo xtask test --unit and git-lfs (What git push runs), and nothing else is asked of anyone. GitLab CI runs the whole battery on the dhs-aws-autoscaler-docker-4xlarge runner on every merge-train car that changes a code input, tags and schedules; a branch push with no merge request runs nothing (#3245; CI is the gate).

The car is one job running the developer's commands (#3354, the plan). car runs on one VM, in three steps, and stops at its first failing line:

  1. The precompilation lints (.lints in .gitlab-ci.yml): cargo fmt --check, then every gate validate runs before the devstack, each the verb a developer types (cargo xtask spdx-lint, cargo xtask policy audit, cargo deny check, …​). None compiles the workspace; a convention break fails in minutes.

  2. One compile, then the stack. cargo build --profile car --workspace --all-targets with BATTERY_FEATURES (the battery's one feature set, #3343), the CLI's own cargo build -p canopy-cli --bin canopy into target/car-cli/ (#3414) and the portal's dx build; cargo xtask dev start then packages that build instead of compiling, refusing a staged canopy that links sqlx (it is newer than the tree and carries the test surface, local-dev.adoc#devstack-binaries), after an earlier job's stack is cleared (the 4xlarge reuses VMs) and the devstack Kanidm is built from the registry's inline cache the release job pushes (#3355).

  3. The lanes against that stack, cheapest first: cargo xtask test --unit --cargo-profile car (as tester), cargo xtask test --integration (the job joins the compose network and runs from its own target/), clippy, the private rustdoc pass and the doctests, feature-builds, api-docs, cargo xtask e2e and cargo xtask identity matrix.

Nothing is pushed to a registry: only the release job pushes. The runner's /builds is a volume, not the same path on the VM, so the job's before_script binds it at its VM path and works from there: the daemon's bind mounts find the checkout, and every cargo line sees one workspace path, so the one build is reused. A failed car keeps every stack container's log in test-results/stack-logs/, an artifact only developers can download.

A merge request's own pipeline runs lint (the same .lints block), antora and, when a code input changed, docs; its car is manual (allow_failure: true, so it never holds the pipeline open), because GitLab adds a merge request to the train only once that pipeline has finished, and the train runs the car anyway. Start it by hand for an early answer. A change to no code input runs lint and antora alone: the docs-only path (The docs-only path). ci-config-lint pins the shape: the car's first rule admits a train car with only the code inputs attached, its merge-request rule is manual, every job that needs it carries the same anchor, no gating job retries, may fail or declares a services: entry (but the docs jobs' diagram renderer, #2630), and every job runs on the 4xlarge. A lanes.rs test holds the .lints block to validate's gates and BATTERY_FEATURES to its constant. Every Docker Hub image the pipeline pulls comes through the Dependency Proxy of canopy's own group (CANOPY_HUB). On a tag and a schedule the release job needs the car, so it starts only once the battery of that commit is green: it builds the release set, smoke-tests it and pushes its images (Deployment Guide › Release, rollback, recovery).

Every gating job runs on one declared image, Dockerfile.ci: the pinned toolchain with rust-toolchain.toml's components and target, the system packages the stages use, the sha256-pinned tools (nextest, cargo-deny, cargo-machete, cargo-llvm-cov) and an unprivileged tester, whom the unit lane runs as (root reads a mode-000 file, so a permission test would assert nothing). No job installs anything. The image is named by its content address (CI_IMAGE_TAG, the first 12 hex of the sha256 of Dockerfile.ci then rust-toolchain.toml, which ci-config-lint checks), and the ci-image job rebuilds and pushes it when either file changes. To run a stage in the CI environment locally: docker build -f Dockerfile.ci -t canopy-ci ., then run it with the checkout mounted.

Stage Job What it runs

.pre

ci-image

when Dockerfile.ci or rust-toolchain.toml changes, and on schedules: builds and pushes the CI image under its content address

check

lint

a merge request's own pipeline, and a car that changes no code input (every other car runs the same block first): .lints, docs, SPDX, the in-process audits and the build gates (deny, machete, quality-budgets, ci-config-lint, the policy audits and the rest), less policy-drift

check

docs

a merge request's own pipeline, when a code input changed: the private-items rustdoc pass and the doctests, with BATTERY_FEATURES

check

antora

every merge request's pipeline and every car: the Antora site builds, as pages builds it

check

sast, secret_detection, dependency_scanning

GitLab's security templates

build

car

when a code input changed (*code-inputs): a train car, tags and schedules, manual on a merge request's own pipeline, never main: the lints, the one compile, dev start, then every lane against that stack (above); the only job that compiles the workspace

test

coverage

a schedule on main: cargo xtask coverage

test

policy-drift

a schedule on main: cargo xtask policy drift --jurisdiction georgia, the packs against the live upstream sources; never on a merge-train car, since a source changes without a commit

promote

sbom, pages

the release's cargo SBOM on tags; the Antora site on main

The seed harness (#450)

Both cargo xtask seed and cargo xtask e2e route through xtask::cmd::seed::run with one default (DEFAULT_HOUSEHOLDS = 50, xtask/src/cmd/seed.rs). Flags: --seed <u64>, --households <n>, --jurisdiction <slug> (default georgia; a pack under target/config/ or fixtures/config/). Without --seed the run picks a random seed and stamps it, with the household count, into test-results/seed/last.txt; xtask e2e always re-seeds: --seed/--households win over CANOPY_SEED/CANOPY_HOUSEHOLDS, which win over the captured values, which win over DEFAULT_HOUSEHOLDS (xtask/src/cmd/e2e.rs). Specs import predicates from the hand-written tests/e2e/lib/fixtures.ts, never from the generated seed.ts. Journeys that need a process-global gated clock use the canopy_test_lib::journey step primitives on the test-clock build (ADR-033).

cargo xtask seed                                     # random seed, captured to last.txt
cargo xtask e2e --no-refresh                         # re-seeds with the captured seed and household count
cargo xtask seed --seed 17234982347 --households 50  # replay an exact failure, then: cargo xtask e2e --no-refresh -- --grep 'CAPS'

Test-writing idioms

  • Decimal in test JSON: string values ("1200.00"), never floats — rust_decimal serializes via the workspace-wide serde-str feature.

  • Test dates: NaiveDate::from_ymd_opt(2026, 1, 1).expect("valid test date").

  • Naming: snake_case describing the property asserted, not the endpoint called — three_non_qualifying_months_exhausted.

  • A decided case with a chosen benefit period (e2e): decideInteractively (an interactive determine, then awaitDetermined on canopy-applications' projection, #3202) decides the application, and determineWithOrder pins the benefit period, in tests/e2e/lib/given/determine.ts; arrangeRenewalDueSoon composes both. An order never decides an application (#3202). Policy numbers are read at runtime from the pack’s jurisdiction.toml under target/config/ or fixtures/config/ (resolveConfig().jurisdiction, tests/e2e/lib/given/config.ts), never written as literals in a spec.

Typed clients and contracts crates

Prefer the per-service typed clients (crates/canopy-test-lib/src/clients/) over hand-rolled reqwest: each wraps the contracts-crate DTOs, so a wire change breaks compilation, not runtime, and carries the bearer .with_token(token) hands it, minted by canopy_test_lib::tokens (the token broker). Drop to TestClient::new(…​) and .get/.post for negative-case assertions. TestClient::with_retry(RetryPolicy) routes get / post_json / delete through canopy_api::retry::retry_request with a single Idempotency-Key on POST; PATCH/PUT are not retry-wrapped (crates/canopy-api/src/retry.rs). Every JSON-over-HTTP operation family lives in a crates/canopy-contracts-<service>/ crate, one per service family: pure DTOs (no axum, no sqlx) with symmetric Serialize + Deserialize, a paths module carrying the FULL post-mount path constants (canopy_contracts_eligibility::paths::DETERMINE = "/v1/eligibility/determine"; routers strip /v1 at boot), and a tests/roundtrip.rs whose proptest blocks serialize → deserialize → prop_assert_eq! every DTO with bounded generators.

Multi-replica, fault injection and chaos

  • MultiReplicaFixture::spawn(service, n).await (crates/canopy-test-lib/src/multi_replica.rs) brings up N processes of a pre-built service binary (cargo build first — spawn does not build), each on a free 127.0.0.1 port with a unique CANOPY_MQ_REPLICA_ID and a shared fresh CANOPY_MQ_QUEUE_PREFIX; base_url_for(i), kill_replica(i), every replica killed on drop. canopy_mq::subscriber::queue_prefix() applies the prefix to replica queues, DLQs and the DLX routing key, so concurrent fixtures share one broker. The binary is the one in the profile directory of the running test's own build (target/<profile>/), found by looking upward from the test executable, because cargo does not promise where under that directory a test executable goes. services/canopy-security/tests/replica_binary_test.rs holds that answer to the path cargo itself names for the binary.

  • evil_proxy(target_url, EvilLayer) (crates/canopy-test-lib/src/evil.rs) starts an Axum reverse proxy on 127.0.0.1:0 whose EvilLayer composes with_latency_jitter(range), with_failure_rate(p) (synthesised 503s), drop_connection_after(n) (a 502 with x-evil-proxy: connection-dropped, not a severed socket) and tamper_payload(f) — for circuit-breakers, retry budgets, deserialisation hardening and outbox catch-up. Its jitter and failure draws are seeded (#1590): from with_seed(n), else CANOPY_FAULT_SEED, else a fresh seed. The proxy prints the seed and a cargo nextest command that replays the test under it when it starts and again when the test fails. Each request draws from the seed and its arrival index, so a seed repeats the schedule of a test that sends its requests in a fixed order.

  • The chaos module spawns a production component IN the test process, pointed at controlled endpoints, because events fired inside devstack containers are unobservable from the test: spawn_outbox_drainer_for_chaos(pool, broker_url) (devstack-required). New contract: the chaos-observability runbook; strategy: ADR-020.

  • The invariant tests in crates/canopy-test-lib/tests/multi_replica_test.rs and evil_proxy_test.rs are #[ignore]d — opt in against a running devstack with cargo nextest run --run-ignored only -p canopy-test-lib --test <name>.

  • canopy-mq under transport faults (crates/canopy-mq/tests/reconnect_test/contested.rs, #1592): a subscriber re-attaches after a graceful broker close and after a severance, recovers from a reconnect that was accepted and never answered, and the outbox drainer catches up after a severance. Each dials the fault layer's rabbitmq mirror (the fault layer). The three subscriber tests read the consumer's connection name from the broker before and after, so a fault that did nothing fails; the drainer test requires that nothing drained while the mirror was cut. The fault lane runs them (cargo xtask test --fault), one at a time (nextest group mq-fault-mirror), since they share the mirror. The same lane and group also run the multi-replica tests (crates/canopy-test-lib/tests/multi_replica_test.rs), which start extra replicas of canopy-security, canopy-eligibility and canopy-web as host processes beside the devstack's own and check one invariant each across them. The same lane and group run the three broker-restart tests (reconnect_test/broker.rs), which restart, stop and replace the devstack's RabbitMQ container and then wait until every service is consuming again.

  • A canopy-db pool with more callers than connections (crates/canopy-db/tests/db_test/pool_contention.rs, #1598, #3486): over six cells of pool size by contenders, as many callers are lent a connection as the pool has and every other one times out at the 5 s acquire bound. Two latencies are gated: a caller that is lent a connection gets it in under 1 s, and a timeout is reported within 250 ms of the bound. Each cell's latencies go to test-results/pool-contention.json (a car artifact). What a caller of a service sees is pinned beside it: canopy-rules' evaluation list, its one-connection pool held, answers 503 with Retry-After: 1 and code db_pool_exhausted, and 200 once the connection is back (a_route_whose_pool_is_held_full_answers_503_with_retry_after_then_recovers).

  • A canopy-db pool under transport faults (crates/canopy-db/tests/db_test/contested.rs, #1593), through the fault layer's postgres mirror: an acquire across a cut mirror fails by the pool's bound (at once with a reset through the host's published port); an acquire nothing answers times out at the pool's five-second bound; a statement on a cut connection fails and the server lets its transaction go; and a commit whose answer is lost returns an error although the row is committed, so an error from a commit does not mean "not committed". The fault lane runs them; nextest group db-fault-mirror.

Contested-environment doctrine (ADR-020 Amendment 1)

A test that puts a component under a fault follows ADR-020 Amendment 1. In short:

  • Deterministic adversity. Force the condition with a barrier, a fault schedule or a severed proxy. Never run load and hope to hit it.

  • Two paths. A graceful protocol close and a TCP severance are different failures. Every MQ surface is tested under both, and the call site says why it uses the lever it uses.

  • Levers. In-process (EvilLayer, the in-tree mock routers, per-service mocks, crash armers) for tampering; the transport proxy for severance (the devstack's fault layer, canopy_test_lib::toxiproxy); the compile-stripped fault features for faults inside a service.

  • Seed and replay. Every random draw is pinned by an environment variable, and a failure prints the command that replays it.

  • Arbitration. A failure is GREEN (the fixture is wrong: fix it, never make it easier), RED (a real defect, with a seeded reproduction) or CANNOT-RUN (the fault layer's owner). "Transient" or "environmental" is never a final answer. The chaos runbook says how to reach and record a verdict and how to replay a failure under its seed.

  • Non-vacuous oracles. A reconnect is shown by a connection whose name differs from the one captured before the cut. A barrier's size comes from the application's own constant, never a round number.

  • Honest claims. A gate says in code what it cannot prove.

The never-easier checklist (blocking in review)

A change to a test in the battery is refused in review when either of these is true:

  1. It widens an assertion to fit a timeout. A timeout budget is a ceiling on the fixture, not a tolerance on what is asserted.

  2. It changes a serialization or an envelope, unless the behaviour under test requires it and the MR description says so.

The one exception to either rule is an amendment to the plan the test belongs to, made before the change and naming the breach.

Identity: receivers, senders and the contract tests

  • An in-process router (a handler or route test over an AppState) takes its receiver from canopy_test_lib::identity: offline_receiver(service) refuses every token, for a state whose tests send none, and devstack_receiver(service) verifies the broker’s tokens against the devstack. A handler test that holds no token builds the Principal with test_principal (canopy-auth’s test-helpers feature, which canopy-test-lib’s library enables). A router whose requests call live peers sends through devstack_sender(client), and one that sends nothing through idle_sender(client). A call to a stub receiver carries a FixedBearer, and a stub that scripts the sender’s one retry answers bearer_rejected() (canopy-test-lib).

  • The identity contract tests (services/<service>/tests/receiver_contract_test.rs, in appeals, applications, caps, eligibility, enrollment, notices, renewals, reporting, snap, verification and wic) pin the receiver’s refusals ahead of every route, against the devstack: no bearer is 401 token_missing; another receiver’s token is 401 token_rejected; X-Canopy-Actor is 400 actor_header_retired; a cast worker lacking the route’s role is 403 required_role_missing; and, where the service has a portal route, the portal on a non-portal route is 403 portal_on_non_portal_route. Each also pins the admissions of a few of its own routes. The codes are the receiver’s (crates/canopy-auth/src/identity_receiver/layer.rs, denial.rs).

Identity: the mock upstream issuer (crates/canopy-test-lib/src/mock_issuer.rs)

MockIssuer::spawn() (or MockIssuer::builder()) serves an OIDC discovery document, a JWKS and a userinfo endpoint from a loopback axum server: the upstream canopy-identity’s key source, id_token validator and userinfo client meet in the canopy-identity suites and the perf substrate, with no devstack. It serves no token or introspection endpoint; discovery still advertises the authorization_endpoint and token_endpoint an upstream profile reads.

  • The builder sets the advertised issuer (a discovery document naming another issuer).

  • The keys. The JWKS serves the committed RSA, P-256, P-384 and Ed25519 fixture keys, each with and without a JWK alg (MockKey); serve_keys serves a subset (a rotation).

  • Minting. mint(alg, key, payload) signs any JSON payload under any asymmetric header alg (RS256/384/512, PS256/384/512, ES256/384, EdDSA; an HS* alg panics) with the kid of key and the fixture key that fits alg, so mismatched alg/key pairs are included; mint_raw signs a header and payload exactly as written. mint_template first adds iss and an exp five minutes out.

  • Scripting. Discovery’s jwks_uri and userinfo_endpoint can be replaced or omitted (Advertised); either document can serve a raw body, an Age header or a DocumentFault (503, a redirect, a delay, a body past 64 KiB); userinfo answers a scripted status, Content-Type and body after an optional delay. Each records the requests it received.

  • Counters. discovery_calls and jwks_calls prove a path made no call; discovery_requested and jwks_requested await one without sleeping.

crates/canopy-test-lib/tests/upstream_keys_test.rs, upstream_id_token_test.rs and upstream_userinfo_test.rs are the reference uses.

Identity: the canopy-identity token broker (crates/canopy-test-lib/src/identity_broker.rs)

TokenBroker gets a test canopy-identity’s tokens the way production does (ADR-049 §14, Amendment 11): it signs a devstack cast person in at the devstack’s upstream with its headless driver (upstream::UpstreamDriver, ADR-049 Amendment 26), federates as canopy-web with canopy-web’s devstack key, mints delegation tokens from that session, and mints system tokens with a client’s own key. The Rust battery takes every token from it, through the process-wide helpers below.

  • Configuration. TokenBroker::from_env() reads the eight CANOPY_TEST__* keys of BrokerConfig::from_env (canopy-test-lib). The host renderer writes them to .ports.env with paths relative to the workspace root: the bring-up’s .devstack/idp/kanidm.json and kanidm-ca.pem, .devstack/identity/keys and the cache .devstack/identity/broker-cache. The compose in-network runner reads a copy that cargo xtask test installs into the volume canopy_identity_inputs before each run, since it mounts no workspace and CI’s daemon sees no job files; its cache is the volume canopy_identity_broker_cache. validate-in-network reads the inputs over its mounted workspace and keeps its cache in the container (Validate In-Network › the token broker).

  • Calls. session(person), delegation(person, target, &narrowing), stepped_up(person, target) (a sign-in at most 300 s old, inside the 600 s a security-admin write or device approval accepts), system(client, target, scope), cli(person, target) (canopy-cli’s delegation, below), approve_device(person, &user_code) and forget(person). A person is its cast name; jane.unscoped is refused at federation (missing_primary_programs), the refusal fixture.

  • The vendor specs' calls (ADR-049 Amendment 26; the private browser module). create_password_only_account() makes a throwaway account with a password and no second factor at Keycloak or ZITADEL (Kanidm has none: it refuses to commit a password-only credential), granted canopy’s caseworker role and SNAP on ZITADEL, so its second factor is all it lacks; delete_account(id) deletes it. redeem(code, verifier, redirect_uri) redeems a stand-in relying party’s code as canopy-web and returns its id_token’s auth_time and nonce, verified by the suites' independent oracle.

  • A browser’s steps (ADR-049 Amendment 24). upstream_sign_in(person) gives the person’s sign-in at the upstream (an UpstreamSession), and authorise_query(&session, query) the upstream’s answer to a relying party’s own authorization query, so a test reads the code a signed-in browser would be redirected with. upstream() names the upstream’s kind, origin, authorization endpoint (the one discovery advertises) and scopes, canopy-web’s client, registered redirects (each canopy-web origin’s callback, the primary first, which provisioning records in the credentials file; registered_redirect() reads the primary) and CA. ui_credentials(person) gives what the upstream’s own login pages ask (the password and a TOTP code with at least 15 s left in its step), stamped as a sign-in, so the next sign-in of that person waits out the spacing and no code is presented twice.

  • Shared sessions. Every broker on one cache directory shares a person’s session, in any process: one owner-only entry per person, read and written only under an exclusive lock on its file. A session is reused while its freshness reaches 120 s ahead, else renewed (the upstream’s refresh reissues the id_token, every preset profile’s renewal evidence), else replaced, the person signed in no sooner than 30 s after its last sign-in so no TOTP code is presented twice. A delegation refused session_ended (a revocation or re-link the entry cannot see) reopens once; one refused session_stale renews once.

  • canopy-cli sessions. cli(person, target) mints canopy-cli’s delegation from the person’s device session, opened with production grants as canopy-cli and canopy-web open one: canopy-cli’s begin_login, the broker’s device approval (the person’s step-up sign-in, then the approval naming its web session as the approver, as approve_device does), and complete_login; each token is then a refresh (DeviceClient::token). The device client reaches every endpoint under the public issuer identifier, which canopy-web’s edge serves, trusting the devstack CA and reaching the issuer’s host at CANOPY_TEST__WEB_ADDR, resolved on each call. Each person’s device store is cli/<person> under the cache, so every broker on the cache, in any process, mints from the one session, each refresh under the store’s own lock. A session that is gone, ended (LoginRequired, or a refusal naming session_ended) or stale is replaced by one login under the person’s cache entry lock; a broker that finds it replaced once it holds the lock mints from that one, so brokers asking at once share one login. A stale session is replaced, not awaited: the broker keeps no native record, so nothing renews it once its 900 s freshness lapses. The approval’s step-up sign-in is spaced from the person’s every other sign-in, so a login right after a web-session sign-in waits out the 30 s. A target canopy-cli has no edge to is refused (DeviceError::NoEdge) with nothing sent.

  • Process-wide helpers. canopy_test_lib::tokens mints through one broker per process, built from BrokerConfig::from_env by the first helper called; a failed build is retried by the next call. The broker’s HTTP clients keep each connection on the runtime that opened it, so the holder serves the one runtime nextest gives each test process. Each helper answers Result<String, BrokerError>:

    • worker(person, target) — canopy-web’s unnarrowed delegation from the person’s web session;

    • stepped_up(person, target) — the same from a sign-in at most 300 s old;

    • system(client, target) — the client’s system token, its purpose’s every scope;

    • portal(target, scope) — canopy-portal’s system token with one scope (Some) or its purpose’s every scope (None, as the portal’s sender asks);

    • cli(person, target) — canopy-cli’s delegation from the person’s device session.

      tokens::or_skip holds the same five answering Option: a miss is reported through skip_or_panic, naming the helper, its arguments and the broker’s error with its causes, before the None, so let Some(token) = tokens::or_skip::worker(…).await else { return; }; is the reporting spelling. Call the helpers qualified (tokens::worker(…)), the spelling the test-lanes-lint loud-miss check reads. cast(username) maps a pre-switch test username to its cast person (the same name, but admin is canopy.admin; applicant.test has none and takes portal). system_caller(target) names the client the helper mints for under a system() arm: the first in the call graph’s caller order, canopy-web and the portal excluded, holding a System or Both edge (None for appeals, notices, reporting and wic). bearer_sub and bearer_iss read a minted token’s sub and iss unverified, for an attribution assertion (a user’s canopy subject, or a system token’s client id), and mint_applicant_claim signs the portal’s applicant ownership claim with the devstack key.

  • Choosing the helper, by the target route’s admission (its canopy_auth::delegated constant or handler constant), in this order: a worker acting is worker(cast(U), target) where canopy-web holds a delegation edge to the target, else cli(cast(U), target); a call under a system() arm is system(system_caller(target), target), under system_from(&[X]) system(X, target); a route with no system arm takes worker or cli, by the actor its row lists, for the cast person holding its role set (CASEWORKER_WRITER_ROLES and CASEWORKER_OR_ABOVE_ROLES jane.caseworker, CASE_READER_ROLES jane.qc, WORKER_READER_ROLES and AUDIT_READER_ROLES jane.auditor, SUPERVISOR_VIEW_ROLES jane.supervisor, admin jane.admin, quality_control qc.reviewer, data_steward data.steward, fti_auditor fti.auditor, studio_admin jane.studio, security_admin sec.admin); the portal’s scoped calls are portal(target, scope). A token the issuer will not mint (no edge) becomes two assertions: the broker reports the refusal, and the receiver refuses the nearest mintable token. No test holds a token past a minute: a delegation lives 300 s, a system token 600 s, and a re-mint is cheap because the broker reuses its sessions.

  • Seed links. link_cast() links every cast person but sec.admin (LINKING_ADMIN) to its realm id, the subject the seed keys its data on, where its pair does not already open as it, and forgets the cached sessions it re-links; LinkReport::linked names them. The devstack’s bring-up runs it (Local Development › seed links), so a cast worker’s delegation sub is its realm id. crates/canopy-test-lib/tests/devstack_identity_test.rs proves both and that a second run writes nothing.

  • Right after a bring-up. The issuer’s first signing key signs 60 s after canopy-security boots, and until then every delegation and system grant answers 503 temporarily_unavailable. The broker retries those for up to 90 s, a second apart, so its first call after a bring-up can take a minute. The federation grant is retried the same way, and so is a system-token call that waited on another caller’s failed acquisition, which its own may not repeat.

crates/canopy-test-lib/tests/identity_broker_test.rs is the reference use: every cast session, a delegation and a system token validated by IdentityTokenValidator over the devstack JWKS, eight brokers sharing one session, a renewal in place, a revoked session replaced, UI credentials that sign in through Kanidm and are spaced from the next sign-in, and a relying party’s query authorised to a code that exchanges. crates/canopy-test-lib/tests/broker_cli_test.rs is the canopy-cli one: a cast caseworker’s tokens::cli token admitted by GET /v1/persons/{id}/assets (a canopy-cli-only row), and a revoked device session replaced by one login shared by four brokers asking at once, its approval spaced from the web-session sign-in before it, then reused by another broker and the process-wide one for other targets.

The token broker service (tools/canopy-token-broker)

The e2e and k6 harnesses cannot link canopy-test-lib, so the broker reaches them over HTTP (ADR-049 Amendment 24). cargo xtask e2e brings it up for every run: auth-setup and the given helpers take every e2e token from it (Signing the battery in). canopy_token_broker::router(plane) serves a Plane, which TokenBroker implements and the router’s tests stand in for. The canopy-token-broker binary builds a TokenBroker from the eight CANOPY_TEST__* keys and serves on port 8099 (PORT). Requests are JSON with unknown fields refused, capped at 16 KiB (BODY_LIMIT).

Every k6 profile takes its tokens from it through tests/k6/lib/identity.js's per-VU createTokenCache, and cargo xtask perf brings it up for every run: smoke, load, stress and soak call applications, enrollment, persons and rules with system('canopy-eligibility', target), one caller for every target in place of system_caller's per-target pick, since canopy-eligibility holds a System or Both edge to each and every route they call admits a system token (perf).

Route Body 200

POST /v1/tokens/delegation

{person, target, roles?, programs?}; each list joined by spaces for Narrowing::parse

{token, token_type: "Bearer", expires_at}

POST /v1/tokens/stepped-up

{person, target}

as above

POST /v1/tokens/system

{client, target, scope?}

as above

POST /v1/tokens/cli

{person, target}; canopy-cli’s delegation from the person’s device session

as above

POST /v1/upstream/authorise

{person, query}

{code, state}

POST /v1/upstream/ui-credentials

{person}

{username, password, totp, totp_valid_until}

POST /v1/upstream/accounts

—

201 {id, username, password}: a throwaway account with no second factor (ADR-049 Amendment 26); Kanidm has none (500 broker_failed)

DELETE /v1/upstream/accounts/{id}

—

204. Only an account this broker made, else 404 unknown_account, nothing sent; a delete the upstream refuses keeps the account the broker’s, so it can be retried

POST /v1/upstream/redeem

{code, code_verifier, redirect_uri}; a stand-in relying party’s code, redeemed as canopy-web

{auth_time, nonce} from the id_token the oracle verified, each null when absent

GET /v1/upstream

—

{kind, origin, authorization_endpoint, scopes, client_id, redirect_uris, ca_pem}, all public; redirect_uris are canopy-web’s registered redirects, the primary first

GET /healthz

—

{status: "ok"}

expires_at is the token’s exp, read from its payload; a token whose exp cannot be read is 502 malformed, the token itself never answered. Authorise keeps one upstream sign-in per cast person. A kept sign-in the upstream answers AuthenticationRequired is replaced by one more sign-in (spaced) and the query asked once more. A fresh sign-in gets no retry, and neither does a prompt=login query, which no kept sign-in satisfies.

An error body is {error, detail, reason?}. detail is a fixed sentence per class, never a failure’s own text. reason is public: an RFC 6749 error, a canopy refusal, rate_limited, status_<n>, the upstream’s denied or no_id_token. PlaneError::from(BrokerError) classifies by an exhaustive match, with no wildcard arm, into the broker’s, the issuer’s and the upstream’s error enums:

Status error From

400

invalid_request

Malformed JSON, an unknown field, target or client, a malformed narrowing (Narrowing::parse), or a body without a JSON content type

404

unknown_person

A person outside the cast

404

unknown_account

A delete naming an account this broker did not make

413

payload_too_large

A body past 16 KiB

502

refused

A federation refusal (a canopy refusal, invalid_client, another OAuth error, a 429, another status); a delegation or system refusal (invalid_scope included); a canopy-cli device refusal (no_edge for a target canopy-cli has no edge to, nothing sent; denied, expired, session_stale, subject_suspended, or the issuer’s refusal); the upstream’s denial or status; no id_token; the upstream refusing an authorisation

502

malformed

An unreadable answer from the issuer or the upstream, or a redeemed id_token the oracle does not verify

502

unreachable

A transport failure, an over-cap or undecodable answer, or the broker’s HTTP client failing to build

502

consent_requested, authentication_required

The upstream’s other answers to an authorisation

503

unavailable

The issuer still unavailable after the broker’s 90 s retry

500

broker_failed

Configuration, credentials, keys, the cache, signing; a canopy-cli login the broker could not complete, or its device store or key

tools/canopy-token-broker/tests/devstack_test.rs serves the real router on loopback over the devstack’s broker. Its delegation and system tokens validate at their receivers, a relying party’s query authorises to a code that exchanges, and an unknown person is 404.

Observability assertions (crates/canopy-test-lib/src/observability.rs)

SpanCapture::install_scoped() installs a scoped tracing subscriber; assert_span_emitted(name), assert_span_field(span, field, value), drain().

An armed capture (#1276, #1361) is a SpanCapture::install_global(), which sees every thread and runtime in the process, dumped only when an assertion is about to fail: observability::dump_armed_capture(capture, header, context) writes the header, the caller’s context lines and the drained timeline to stderr in one write, and nextest keeps a failing test’s stderr. A report-only number from a test goes through canopy_test_lib::measure! (Ephemeral schemas and the post-battery sweep shows the record shape), never a bare eprintln!.

IMPORTANT
Tests using SpanCapture MUST use #[tokio::test(flavor = "current_thread")]: tracing::subscriber::set_default is thread-local, so on a work-stealing runtime spawned tasks do not see the subscriber and the test flakes under nextest.

SpanCapture proves what was emitted into tracing, not what reaches a log line: it does not reproduce the production filter or the JSON formatter’s span-field join, which serialises the current span and the span list onto every event unless both joins are off (#1908). A "must NOT appear in a log line" assertion runs the real json_layer over a capturing writer and asserts on the bytes — no_query_string_reaches_an_emitted_log_line_at_debug in crates/canopy-common/src/telemetry.rs is the pattern.

Time (crates/canopy-test-lib/src/time.rs, canopy_common::clock)

  • pause(), advance(Duration) and run_paused_advancing(fut, step) drive tokio’s paused clock — pair with #[tokio::test(start_paused = true)]. run_paused_advancing steps the clock whenever the future yields, so retry loops and backoffs composed from tokio::time::sleep complete without wall time.

  • Production date/time comes from canopy_common::clock (now(), today(), legal_today(tz), DecisionClock); under the test-clock feature, clock::test_clock::advance(delta) and the devstack /test/clock endpoint move it for journeys (ADR-033). The gated clock is process-global, so clock-driven journeys run in isolation; a journey that advances the clock and then renders the supervisor dashboard first calls POST /v1/renewals/caseload-rollup/refresh (#1218).

  • A service stamps legal dates in the loaded pack’s timezone (clock::legal_today(tz)), so a test takes "today" from canopy_test_lib::legal_today() or pins as_of — never from Utc::now().date_naive() or clock::today(), which run a day ahead from 00:00 UTC until the jurisdiction’s midnight, and a month ahead on the first (#2523) — and names no timezone: a local time of day is legal_instant(day, time) (legal_noon(day) for a mid-day seed, legal_rfc3339 for a request body), never a fixed UTC hour or offset, which lands on the next day in a zone far enough east of UTC. After steering a service’s gated clock, read it back (GET /test/clock) and date through legal_date_at(instant); month_boundary_instant gives an instant at which the two calendars sit in different months. cargo xtask test-lanes-lint refuses the UTC date, literal zones and a fixed UTC time or offset (and_utc, Utc.with_ymd_and_hms and the other Utc constructors, and_local_timezone(Utc), FixedOffset::west_opt) in services/*/tests/ and crates/canopy-test-lib/src/, though not a fixed instant written as a string; a test that mirrors a comparison made in UTC, or builds an in-process service configured with a fixed zone, takes an entry with a written reason and its site count in compliance/test-utc-today-allowlist.toml.

  • A devstack test that orders an instant of its own against one the stack stamped (a column a statement sets from now(), an event envelope a service container stamps with its process clock through canopy_mq::EventEnvelope::new) reads that instant from canopy_test_lib::db_now(&pool), the database’s SELECT now(), never from the host’s Utc::now() (#3138, #3139). Under Docker Desktop (Windows, macOS) the containers run in a VM whose clock can lag the host’s by tens of milliseconds, so a host instant read before an action can land after the stamp the action made; every container in the VM, the databases included, reads the VM’s one clock. On a Linux host the two agree, so the host form passes there and can fail only on Docker Desktop.

  • Never sleep to wait for expiry, and never assert an elapsed-time upper bound within ~3× of the expected duration — under battery load correct code runs 2–3× slower, so that is a scheduler race, not a property (#1904). Assert a shape instead: an attempt count, the typed timeout error, a captured warn!, a concurrency high-water mark — or move the test to paused time. A surviving bound is a coarse backstop and says so (the services/canopy-eligibility/tests/orchestrator_dispatch_test.rs form). Lower bounds need no such care.

Goldenfiles, snapshots and frozen vectors

  • assert_matches_golden(actual, golden_path) (crates/canopy-test-lib/src/goldenfile.rs) pins structured text; set UPDATE_GOLDEN=1 to rewrite a golden (refused when CI=1 is also set). Pin where the output IS the contract — notice text, report CSV layout — and pin rendered TEXT, not PDF bytes (#1673): RenderEngine::render_text / canopy_typst::engine::document_text; PDF bytes get only a %PDF- magic or size-floor check.

  • insta::assert_yaml_snapshot!(value) for deep structured values; cargo insta review / accept; snapshots live beside the test.

  • BYTE-level protocol surfaces (canonicalisation, hash preimages, manifests, signatures) use the frozen KAT corpus in crates/canopy-chain/tests/vectors/ (#1246): vectors are seeded from OUTSIDE the implementation (the RFC 8785 data plus a committed second-implementation derivation), the generator refuses overwrite, VECTOR_CORPUS_SHA256 forces a visible diff, and changing a vector means bumping that surface’s protocol version plus an ADR-014 amendment.

Scanner-path and saga suites

  • Scanner (ADR-042): CANOPY_TEST__CLAMD_ADDR (crates/canopy-test-lib/src/config.rs) reaches the devstack clamd; real-clamd rows are required in the in-network lane, and deterministic protocol coverage runs against an in-process fake clamd in crates/canopy-scanner-clamd/tests/.

  • Finalize saga (ADR-038): services/canopy-applications/tests/finalize_acceptance_test.rs proves the criteria against an ephemeral schema and a receipt-modelling mock persons service — commit/response-separated fault knobs, two-Notify barriers for deterministic interleavings, DB-time backdating for lease aging, and PII-free-log assertions via SpanCapture.

Coverage gate

cargo xtask coverage [--threshold <pct>] [--baseline] [--integration] (xtask/src/cmd/coverage.rs) gates unit-lane line coverage: cargo llvm-cov nextest --workspace --features <BATTERY_FEATURES> --lib --bins (#3343) filtered by UNIT_FILTER, run with CANOPY_TEST_INFRA=required so a stray infra test fails loudly. The floor is DEFAULT_THRESHOLD; its measurement is committed as coverage-baseline.toml, refreshed together by --baseline in the CI image (host measurements drift). --integration measures the infra lane informationally — no floor, no CI job. Install once: rustup component add llvm-tools-preview && cargo install cargo-llvm-cov cargo-nextest.

Mutation testing

cargo xtask mutants [--smoke | --iterate | --baseline] (xtask/src/cmd/mutants.rs, #466) runs cargo-mutants over the unit lane, the same lane the coverage gate measures, with CANOPY_TEST_INFRA=required. cargo-mutants appends the lane to each nextest test run it spawns as one filterset, (kind(lib) | kind(bin) | kind(proc-macro)) & (UNIT_FILTER), rather than --lib --bins: it names the mutated package explicitly, and cargo refuses --lib for a package with no library target (exit 101), which cargo-mutants would score as caught for every mutant of a bin-only service. .cargo/mutants.toml selects nextest and sets gitignore = true.

Every mode runs two cargo-mutants passes (#2230). canopy-portal’s test build needs the #1988 test features, and cargo-mutants 25.3.1 passes --features to every per-package run, where cargo refuses a feature of a member the run did not select. So the workspace pass mutates every package but the portal, with no features, into mutants.out/. The canopy-portal pass mutates the portal alone (--package canopy-portal --features canopy-portal/server,canopy-portal/preview) into mutants-portal/mutants.out/. Each pass names its whole exclude set on the command line, because cargo-mutants' --exclude replaces the config’s exclude_globs rather than adding to them: the workspace pass leaves out tests/, xtask/, crates/canopy-test-lib/ and the portal, and the portal pass leaves out tests/. On gitignore = true: cargo-mutants builds every job in a scratch copy of the source tree (not target/, by default, so each job starts from a cold build), and gitignored files stay out of that copy, .env.local and its tokens included.

The xtask also passes --no-tests=warn: cargo-mutants tests each mutant against its own package only, and a package with no unit-lane test would otherwise exit 4, which cargo-mutants scores as caught. With the flag those mutants count as missed, which is what they are. Install once: cargo install cargo-mutants --locked.

Both run modes are local and manual. --smoke runs shard 0/20 of each pass, the quick developer check. The full run is a maintainer on-demand action measured in days (about 22,700 mutants, the portal’s 1,100 among them). An interrupted full run resumes with --iterate, which skips the mutants already caught or unviable in each pass’s output. Use it only on the tree that produced that output: --iterate cannot be combined with --smoke, because cargo-mutants takes the shard after the skip.

After a run, the gate reads both passes' missed.txt as one list; a name carries its file path, so one baseline holds both. The run fails on any missed mutant not accepted in mutants-baseline.toml, on an accepted entry with an empty reason, or on a missing baseline. Only cargo-mutants exits 0 (all caught) and 2 (missed) reach that comparison. Any other exit fails the run straight away, so a partial run never reports clean: a timeout (3), a failing unmutated tree (4), a usage or runtime error (1), a diff-filter error (5, 6), an internal error (70), or a signal kill. Unviable mutants never count.

To refresh the baseline, run cargo xtask mutants --baseline locally on the pinned toolchain after a complete full run. It rewrites mutants-baseline.toml from both passes' missed.txt without running mutants: it keeps the reason of each still-missed entry, drops entries no longer missed, and adds new ones (in source order, among the kept ones) with an empty reason for the maintainer to fill in. It also records the scope, the date and the cargo-mutants, nextest and rustc versions. After --smoke or an interrupted run it would drop every entry the partial run never reached. Each entry is keyed by its cargo-mutants name (file:line:col: description), so entries go stale when code above them moves. Refresh with --baseline; never hand-edit line numbers. A full run without a baseline still proceeds, since it is the population run. It fails at the end with the instructions, and --smoke refuses to start until the baseline exists.

mutants is never part of validate or any pipeline.

Running on Windows

The #466 population run on a Windows host met four failure modes that give false results, and one that is unexplained (#2507).

NASM

cargo-mutants builds one package at a time, which loses the prebuilt-nasm feature of aws-lc-sys that the workspace-wide build turns on. On a host with no NASM installed, every mutant in canopy-auth and canopy-signing then fails to build and is scored unviable. Set AWS_LC_SYS_PREBUILT_NASM=1 for the run.

Disk

each job's scratch build directory grows to about 66 GB. When the disk fills, workers die quietly and their mutants are mis-scored. Point TMP and TEMP at a drive with room for every job, and delete the cargo-mutants-*.tmp directories a killed run leaves behind.

Resuming

--iterate skips only caught and unviable mutants, so each restart retests every mutant already recorded as missed. To avoid that, append the missed names to previously_caught.txt in each pass's output before restarting. The complete missed list is then those names plus the new missed.txt; merge the two before --baseline, which reads missed.txt alone.

Memory

a build that runs out of memory (memory allocation of N bytes failed, failed to mmap) is scored unviable or caught. Search the job logs for those messages and retest only the affected mutants with cargo-mutants' --re.

Known issue

over several days in long-lived scratch directories, canopy-web's unit tests became about five times slower. The cause was not found; fresh scratch directories restored the speed.

Invariant gates

All run inside validate (the stage names above).

  • cargo xtask rules check compiles every configuration layer’s decisions with zen-engine and evaluates the paired fixture under crates/canopy-test-lib/fixtures/rulesets/; rules lint-inputs bans numeric literals in JDM expressions (ADR-011); rules processing-days checks the SNAP processing clocks agree (#1759).

  • cargo xtask policy audit validates citations.toml against jurisdiction.toml and the federal rulesets (ADR-011).

  • cargo xtask scenarios audit validates the scenario inventory (ADR-031 §3): schema, every binding resolves, every covered journey pairs a walkthrough, no orphan journey- spec; a fenced row reports *partial, and every blocked_by entry must be a #NNN issue ref. --online also checks each fenced issue is open via glab. Uncovered is a burndown report, never a failure.

  • cargo xtask call-graph check fails on any difference between the compiled call graph (canopy_auth::identity_policy::edges(), ADR-049 §4), the census of peer settings (cargo xtask call-graph census) and the graph’s generated table in the authorization inventory (#2644): an observed pair that is not compiled, an observed sender that is no compiled client, a compiled pair nothing observes, or table drift either way. No allowlist.

  • cargo xtask delegated-routes check fails on any difference between canopy_auth::delegated_routes() (ADR-049 Amendment 15) and its generated table in the authorization inventory (#2802), either way or out of order, and on a listed route its service does not register: a syn census of every receiving service’s .route(…) calls, through the contract path constants and each router’s methods, with a floor on each service’s resolved registrations. It lists, never failing, each registration whose path it cannot resolve.

  • cargo xtask api-docs fails on OpenAPI drift between the live services' /api-doc/openapi.json and the snapshots in docs/modules/ROOT/openapi/; --update accepts the change. Each service's the_served_openapi_spec_is_the_committed_snapshot unit test makes the same comparison in process, so the unit lane catches drift before a push; cargo xtask api-docs --offline --update regenerates the snapshots with no devstack (#3340).

  • validate’s docs stage requires the four mandatory pages (architecture, services, security, local-dev) to exist, carry real prose and no canopy:placeholder sentinel (MANDATORY_DOCS and xtask/src/doc_content.rs, #2990).

See also

Edit this page · default