Plan: cross-process chaos observability harness — phase 1 (#480, epic &50)

Status: Done (2026-05-19) — !333
Successor: Phase 2 — contested-environment parity (epic &80)

NOTE

Split out of docs/modules/ROOT/pages/plans/cross-process-chaos-observability-harness.adoc on 2026-09-16 so the live plan carries phase 2 alone. The sections below are the phase-1 text as written (its Status table was back-filled on 2026-08-25), with three mechanical changes: workstation-absolute paths made repo-relative, agent-memory notes removed, and two crate paths repointed to their crates/ homes.

Context — the larger picture

Phase-1-era diagnosis (2026-05). Line anchors in the phase-1 sections below are as of 54b0fbd1 (2026-05-19) — grep by name against today’s tree.

Three of the four chaos tests then in flight (jwks_rotation and outbox_catches_up in crates/canopy-test-lib/tests/evil_proxy_test.rs, plus the multi_replica_test.rs suite) named invariants the SpanCapture primitive could not observe. SpanCapture::install_scoped at crates/canopy-test-lib/src/observability.rs:120-130 uses tracing::subscriber::set_default, which is thread-local in the test process. Production code emitting events inside devstack containers (canopy-auth’s JwksProvider refresh task, canopy-mq’s OutboxDrainer running inside each service) is invisible to the test process’s subscriber — the chaos tests today are "fixture landed" rather than "invariant proven" (the diagnosis that drove #469 + #470, both now closed as duplicates under epic &50).

#462 (retry middleware, merged via MR !332) closed the in-process retry contract. The remaining three contracts (#481 JWKS, #482 outbox, multi-replica work) needed a harness primitive that lets them run production components in the test process so SpanCapture can see their events — all three have since shipped (see "Out of scope" below).

Strategy decision (ADR-020)

Three candidates evaluated:

  1. In-process production fixtures — instantiate JwksProvider and OutboxDrainer directly in the test process pointed at EvilLayer-wrapped endpoints. SpanCapture observes spans because they fire on the same current_thread runtime as the test.

  2. OTEL export — devstack has no trace receiver today (canopy-common/src/telemetry.rs:42 documents this); container-to-test routing complexity; heavy dep tree (opentelemetry-proto). Rejected.

  3. Log scraping via Docker API — brittle (log-shape coupling), eventually-consistent polling, container-name coupling, new bollard dep. Rejected.

Decision: in-process production fixtures. Zero new infrastructure, zero new container plumbing, zero production-code changes. Production constructors are already test-friendly. ADR-020 documents the decision + the thread-local-subscriber constraint.

Plan-file location

This canonical plan at docs/modules/ROOT/pages/plans/cross-process-chaos-observability-harness.adoc is the durable artifact per ADR-013. Linked from docs/modules/ROOT/nav.adoc under ** Infrastructure. Implementation begins only after this commit + ADR-020 + nav entries land on the feature branch (Step 1).

Status — phase 1: the harness (#480, shipped)

Step Description Status

1

Land canonical plan + ADR-020 + nav entry. This commit. REWRITE this canonical .adoc to match the reviewed design (replaces an earlier stale draft on the feature branch). Write docs/modules/ROOT/pages/adrs/adr-020-cross-process-chaos-observability.adoc. Add 2 entries to docs/modules/ROOT/nav.adoc: one ADR row after ADR-019, one plan row under ** Infrastructure after the canopy-api retry middleware entry. AsciiDoc passthroughs #[...] around any Rust attribute references so they don’t collide with AsciiDoc …​ mark syntax.

Done (2026-05-18) — e99b1b2f

2

crates/canopy-test-lib/Cargo.toml (~2 lines). Add to [dependencies]: canopy-auth = { workspace = true }, canopy-mq = { workspace = true }. No serial_test, no lapin (helper’s Result return type uses anyhow::Error via .map_err(anyhow::Error::from); anyhow is already a dep). Cycle check: cargo build -p canopy-test-lib clean (canopy-auth + canopy-mq dev-depend on canopy-test-lib; dev-deps don’t propagate to normal-dep cycle detection).

Done (2026-05-19) — 54b0fbd1

3

crates/canopy-test-lib/src/mock.rs::spawn_mock_jwks (NEW, ~30 LOC). Modeled on spawn_mock_persons at mock.rs:165-209. Serves a static canonical Keycloak realm JWKS document at /protocol/openid-connect/certs — a single RS256 public key payload baked into the helper as a string literal. No keypair generation, no JWT issuance. Returns MockHandle. The fixed key shape is enough for JwksProvider::refresh() to parse and cache; consumers that need to issue JWTs against the mock add their own signing helpers in #481.

Done (2026-05-19) — 54b0fbd1

4

crates/canopy-test-lib/src/chaos/mod.rs (NEW, ~80 LOC). Module entry. Re-exports spawn_jwks_provider_for_chaos, spawn_outbox_drainer_for_chaos, ChaosJwksHandle, ChaosOutboxHandle. Module rustdoc spells out the thread-local-subscriber constraint with a #[tokio::test(flavor = "current_thread")] requirement + canonical use shape.

Done (2026-05-19) — 54b0fbd1

5

crates/canopy-test-lib/src/chaos/jwks.rs (NEW, ~120 LOC inc. tests). See "Harness API surface" below for the full signature. No background refresh task — JwksProvider::start_refresh_task is fire-and-forget (jwks.rs:91-102 discards the JoinHandle); tests drive provider.refresh().await manually for deterministic timing.

Done (2026-05-19) — 54b0fbd1

6

crates/canopy-test-lib/src/chaos/outbox.rs (NEW, ~100 LOC inc. tests). See "Harness API surface" below. Rustdoc documents: OutboxDrainer has no Drop / abort (outbox_drainer.rs:174 — private join handles); spawned tasks live until the test runtime drops. ConnectionManager::new connects immediately — pass a REAL broker URL. Transient-failure injection requires AMQP-transparent EvilLayer (evil_proxy is JSON-only) — tracked in #482. The info!("outbox drainer started") event fires immediately on spawn (BEFORE the first tick sleep) — observable in SpanCapture without any tick env-var manipulation.

Done (2026-05-19) — 54b0fbd1

7

crates/canopy-test-lib/src/lib.rs — pub mod chaos; next to existing pub mod observability; + re-exports.

Done (2026-05-19) — 54b0fbd1

8

4 unit tests across chaos::jwks::tests + chaos::outbox::tests (all #[tokio::test(flavor = "current_thread")]):

  • jwks_helper_returns_provider_usable_for_refresh (in-process, no devstack): EvilLayer::new() zero-failure passthrough; assert handle.provider.refresh().await returns Ok(()).

  • jwks_helper_emits_jwks_refreshed_event_under_in_process_subscriber (in-process, no devstack): install SpanCapture::install_scoped, drive provider.refresh().await, assert SpanCapture saw "JWKS refreshed" event (existing info! at jwks.rs:81). Pins the architectural invariant.

  • jwks_helper_returns_err_when_upstream_fails (in-process, no devstack): EvilLayer::new().with_failure_rate(1.0), provider.refresh().await returns Err. No tracing assertion (refresh() doesn’t emit on failure — #481’s scope).

  • outbox_helper_emits_drainer_started_event_under_in_process_subscriber (devstack-gated, #[ignore]): if !infrastructure_available().await { return; }; private fn amqp_url() reads CANOPY_TEST__RABBITMQ_URL (pattern from outbox_drainer_test.rs:22-30); private fn pg_url() reads CANOPY_PORT_POSTGRES_5432 and constructs postgres://canopy:canopy@localhost:{port}/canopy_persons (pattern from outbox_drainer_test.rs:35,52); install SpanCapture; call helper; sleep 50ms; assert SpanCapture saw "outbox drainer started" at outbox_drainer.rs:213. Marked #[ignore = "chaos: requires devstack + opt-in via cargo nextest run --run-ignored only"] matching existing chaos pattern.

Done (2026-05-19) — 54b0fbd1

9

CHANGELOG.adoc — entry under === Added. Template in "CHANGELOG entry template" below.

Done (2026-05-19) — 54b0fbd1

10

Docs: (a) Shared Crates — new "canopy-test-lib chaos helpers" subsection under canopy-test-lib. (b) Testing — paragraph near the existing SpanCapture-thread-local note.

Done (2026-05-19) — 54b0fbd1 (landed in the then-canonical .claude/docs directory; content migrated to the Antora pages cited here)

11

Precommit Q1-Q8 + validate + push + MR. cargo fmt --all + cargo clippy --all-targets --workspace --locked — -D warnings clean per Coding Conventions (zero #[allow(clippy::*)]). cargo xtask validate clean. Push flow operator’s choice.

Done (2026-05-19) — 54b0fbd1 merged; #480 closed; epic &50 closed via #483 (runbook, 1a41ab99)

Issue: https://gitlab.com/gadhs/application/eligibility/canopy/-/issues/480
Epic: &50 — Chaos observability contracts
Branch: feature/cross-process-chaos-harness
Labels: priority::medium, service::shared-crates, program::infrastructure, type::feature, workflow::done

Harness API surface

crates/canopy-test-lib/src/chaos/jwks.rs

pub struct ChaosJwksHandle {
    pub provider: canopy_auth::JwksProvider,
    pub mock_url: String,
    _mock_handle: crate::mock::MockHandle,        // Drop aborts axum
    _evil_handle: crate::evil::EvilProxyHandle,   // Drop aborts proxy
}

pub async fn spawn_jwks_provider_for_chaos(
    evil_layer: crate::evil::EvilLayer,
) -> ChaosJwksHandle {
    let mock = crate::mock::spawn_mock_jwks().await;
    let upstream_url = format!("http://{}", mock.addr);
    let evil = crate::evil::evil_proxy(&upstream_url, evil_layer);
    let discovery = canopy_auth::OidcDiscovery {
        issuer: "https://chaos-harness.test/realms/canopy".to_string(),
        jwks_uri: format!("{}/protocol/openid-connect/certs", evil.url),
        ..Default::default()
    };
    let provider = canopy_auth::JwksProvider::from_discovery(&discovery)
        .expect("from_discovery infallible for caller-built URL");
    ChaosJwksHandle {
        provider,
        mock_url: evil.url.clone(),
        _mock_handle: mock,
        _evil_handle: evil,
    }
}

The issuer is set to a stable mock value (https://chaos-harness.test/realms/canopy). Returning a provider with issuer: "" would be a footgun — JwksProvider::validate_token checks the JWT’s iss claim against this value. Tests that only exercise refresh() won’t notice, but a hypothetical consumer using validate_token would get confusing failures.

crates/canopy-test-lib/src/chaos/outbox.rs

pub struct ChaosOutboxHandle {
    _drainer: canopy_mq::OutboxDrainer,
}

pub async fn spawn_outbox_drainer_for_chaos(
    pool: sqlx::PgPool,
    broker_url: &str,
) -> Result<ChaosOutboxHandle, anyhow::Error> {
    let manager = canopy_mq::ConnectionManager::new(broker_url)
        .await
        .map_err(anyhow::Error::from)?;
    let drainer = canopy_mq::OutboxDrainer::spawn(pool, manager);
    Ok(ChaosOutboxHandle { _drainer: drainer })
}

Critical files

  • docs/modules/ROOT/pages/plans/cross-process-chaos-observability-harness.adoc (the plan file at the time; REWRITE in Step 1)

  • docs/modules/ROOT/pages/adrs/adr-020-cross-process-chaos-observability.adoc (NEW, Step 1)

  • docs/modules/ROOT/nav.adoc (+ 2 entries, Step 1)

  • crates/canopy-test-lib/Cargo.toml (+ canopy-auth, canopy-mq normal-deps)

  • crates/canopy-test-lib/src/chaos/mod.rs (NEW)

  • crates/canopy-test-lib/src/chaos/jwks.rs (NEW)

  • crates/canopy-test-lib/src/chaos/outbox.rs (NEW)

  • crates/canopy-test-lib/src/mock.rs (+ spawn_mock_jwks)

  • crates/canopy-test-lib/src/lib.rs (+ pub mod chaos;)

  • CHANGELOG.adoc

  • Shared Crates (docs/modules/ROOT/pages/shared-crates.adoc)

  • Testing (docs/modules/ROOT/pages/testing.adoc)

CHANGELOG entry template

* *Cross-process chaos observability harness — `canopy_test_lib::chaos`
  module (\#480 + ADR-020).* NEW module + 2 helper functions that spawn
  production `JwksProvider` and `OutboxDrainer` in the test process
  pointed at `EvilLayer`-wrapped endpoints. Unblocks the three chaos
  contracts (\#481 JWKS, \#482 outbox, multi-replica work) that were
  previously architecturally blind: `SpanCapture::install_scoped` uses
  `tracing::subscriber::set_default` which is thread-local in the test
  process and could not observe events fired inside devstack containers.
  In-process fixtures sidestep the cross-process problem entirely while
  exercising the same production constructors.
  `spawn_jwks_provider_for_chaos(EvilLayer) -> ChaosJwksHandle` spawns
  a canonical-shape JWKS mock under the supplied `EvilLayer`, constructs
  `JwksProvider::from_discovery` with a stable mock issuer.
  `spawn_outbox_drainer_for_chaos(pool, broker_url) -> Result<ChaosOutboxHandle, anyhow::Error>`
  spawns `OutboxDrainer` against the supplied broker URL — chaos tests
  point at a real broker (devstack) and observe the `info!("outbox drainer started")`
  emit at `outbox_drainer.rs:213` immediately on spawn. Transient-failure
  injection requires AMQP-transparent EvilLayer (tracked in \#482).
  4 unit tests: 3 in-process JWKS tests + 1 devstack-gated outbox test
  marked `+\#[ignore]+` per existing chaos pattern. ADR-020 documents
  the strategy decision + the thread-local-subscriber constraint. Zero
  production-code changes. `shared-crates.adoc` +
  `testing.adoc` updated. Closes \#480.

Verification

  1. cargo nextest run -p canopy-test-lib chaos::jwks — 3 JWKS unit tests pass (in-process only).

  2. cargo nextest run -p canopy-test-lib --run-ignored only chaos::outbox — outbox test passes when devstack up; skips cleanly when down.

  3. cargo nextest run -p canopy-test-lib — full crate green.

  4. cargo build -p canopy-test-lib — no cycle.

  5. cargo fmt --all — --check + cargo clippy --all-targets --workspace --locked — -D warnings clean (zero #[allow]).

  6. cargo xtask validate clean.

Project-specific gotchas

  • SPDX header on every new .rs file line 1.

  • #![warn(missing_docs)] on canopy-test-lib (lib.rs:3) — every pub symbol in chaos:: needs ///.

  • Clippy -D warnings — zero #[allow(clippy::*)] carve-outs.

  • nextest only: never cargo test.

  • No Q1-Q8 in commit messages.

  • Commit title ≤72 chars, prefix ^(feat|fix|chore|refactor|docs|test|ci):.

  • Thread-local subscriber constraint — chaos tests using the harness MUST use #[tokio::test(flavor = "current_thread")]. Documented in module rustdoc + ADR-020 + Testing.

Documentation updates

  • CHANGELOG.adoc — entry under === Added.

  • Shared Crates — new canopy-test-lib chaos helpers subsection.

  • Testing — chaos-helpers paragraph + thread-local-subscriber callout.

Out of scope (separate issues / future MRs — all since shipped)

  • JWKS chaos contract rewrite — #481, closed (target: "jwks" emit sites landed in crates/canopy-auth/src/jwks.rs).

  • Outbox chaos contract rewrite — #482, closed (target: "outbox" emit sites landed in crates/canopy-mq/src/outbox_drainer.rs). Its AMQP-transparent fault-injection residue is now phase 2’s U3/U4.

  • Durable docs + runbook — #483, closed (1a41ab99; the chaos runbook).

  • Multi-replica chaos rewrite — superseded: owned by phase 2 (U14, epic &80) in the phase-2 plan.

Reuses existing patterns

  • canopy_test_lib::mock::spawn_router (mock.rs:51) + spawn_mock_persons (mock.rs:165-209) — axum mock shape, MockHandle abort-on-Drop.

  • canopy_test_lib::evil::{EvilLayer, evil_proxy, EvilProxyHandle} (evil.rs) — fault-injection layer + handle that aborts on Drop.

  • canopy_test_lib::observability::SpanCapture::install_scoped (observability.rs:120).

  • canopy_test_lib::infrastructure_available (infrastructure.rs:14) — devstack-presence gate.

  • canopy_auth::JwksProvider::from_discovery (jwks.rs:50) + OidcDiscovery (discovery.rs:70, derive(Default)).

  • canopy_mq::ConnectionManager::new (connection.rs:49, async, returns Result<_, lapin::Error>).

  • canopy_mq::OutboxDrainer::spawn(PgPool, ConnectionManager) (outbox_drainer.rs:183).

  • CANOPY_TEST__RABBITMQ_URL + private fn amqp_url() pattern (crates/canopy-mq/tests/outbox_drainer_test.rs:22-30).

  • CANOPY_PORT_POSTGRES_5432 + private fn pg_url() pattern (outbox_drainer_test.rs:35,52).

Edit this page · default