Chaos Observability Contracts: Adding a New Contract

For a contributor adding a chaos observability contract: a test in crates/canopy-test-lib/tests/evil_proxy_test.rs asserting that production code emits a specific structured tracing::Event under fault injection. The test spawns the production component in the test process through the canopy_test_lib::chaos harness, wraps its upstream with EvilLayer (or points at a real broker for protocols evil_proxy cannot wrap, such as AMQP), and asserts with SpanCapture that events with a specific target: fired. ADR-020 records why in-process fixtures won over OTEL and log scraping.

The contracts that exist today:

Test target: Production code Runs

inbox_dedup_at_100_percent_failure

retry

crates/canopy-api/src/retry.rs

#[ignore] — needs the devstack

eligibility_circuit_breaker

circuit_breaker

crates/canopy-api/src/circuit_breaker.rs

every sweep

outbox_catches_up

outbox

crates/canopy-mq/src/outbox_drainer.rs

#[ignore] — needs the devstack

Preconditions — the thread-local subscriber

SpanCapture::install_scoped (crates/canopy-test-lib/src/observability.rs) uses tracing::subscriber::set_default, which is thread-local. Three consequences:

  1. A test using SpanCapture MUST be #[tokio::test(flavor = "current_thread")]: on a multi-threaded runtime, work-stealing moves tasks onto threads that never see the subscriber and the assertions fail silently under nextest.

  2. Production components inside devstack containers are unobservable — the OutboxDrainer each service’s bootstrap spawns (crates/canopy-api/src/bootstrap.rs) or canopy-eligibility’s program CircuitBreaker emits in another process. There is no cross-process tracing capture today.

  3. The chaos harness side-steps that by spawning the production component IN the test process, pointed at a controlled endpoint: same constructor, same code, same emit sites, executed where the subscriber can see them.

Steps

  1. Add a target: to the production emit sites. In the module (say crates/canopy-mq/src/inbox_drainer.rs) add target: "<name>" to every tracing::info! / warn! / error! that names an invariant the test should assert. Use a stable name an operator would grep:

    info!(target: "inbox", drainer_id = %cfg.drainer_id, "inbox drainer started");
  2. Make the failure path emit. ? propagation is the usual reason a failure emits nothing. match the fallible call’s Result so the failure arm emits under the same target: as the success path — the shape of the outbox drainer’s drain_loop (crates/canopy-mq/src/outbox_drainer.rs, \#482), abridged:

    info!(target: "outbox", tick_ms = tick.as_millis() as u64, "outbox drainer started");
    loop {
        tokio::time::sleep(tick).await;
        match drain_once(&pool, &manager, &cfg).await {
            Ok(_) => { /* debug-level tick stats */ }
            Err(e) => {
                warn!(target: "outbox", error = %e, "outbox drain iteration failed; retrying next tick");
                /* reconnect */
            }
        }
    }
  3. If the component is not yet harness-spawnable, add a helper. canopy_test_lib::chaos provides spawn_outbox_drainer_for_chaos(pool, broker_url) → Result<ChaosOutboxHandle> (chaos/outbox.rs). A component the test can construct directly needs no helper: eligibility_circuit_breaker builds its CircuitBreaker and an evil_proxy inline. To add one (say spawn_inbox_drainer_for_chaos):

    1. Check the production constructor is test-friendly (injectable, clone-friendly, async). OutboxDrainer::spawn was; if yours needs production changes to be testable, that is a separate scope — discuss before adding.

    2. Take an EvilLayer (HTTP) or a broker_url (AMQP and other non-HTTP). For HTTP, serve the upstream from a mock (crate::mock::spawn_router), wrap it with evil_proxy, and construct the component against the proxy’s url. For AMQP, take the URL directly, as chaos/outbox.rs does; the test passes a real devstack URL.

    3. Return a Chaos<X>Handle holding the component plus any MockHandle and EvilProxyHandle as _-prefixed fields, so their Drop impls (each aborts its server task) run with the handle.

    4. Re-export from crates/canopy-test-lib/src/lib.rs beside the existing harness re-exports, and state the thread-local constraint in the helper’s module rustdoc.

  4. Write the test in evil_proxy_test.rs as #[tokio::test(flavor = "current_thread")]: install SpanCapture::install_scoped BEFORE the helper spawns anything; drive a fail phase (the helper’s error path and the production failure-path emit), then a recover phase (the success-path emit); finish with capture.assert_span_emitted("<target>") — or assert_span_field when the contract names fields, as eligibility_circuit_breaker does, the reference shape for a fully in-process contract. If the test needs the devstack (a real broker), gate it with #[ignore = "chaos: requires devstack + opt-in via cargo nextest run --run-ignored only"] and check infrastructure_available().await early; a fully in-process test runs in the regular sweep with no gate.

  5. Record it. CHANGELOG.adoc under === Added: the target: and its emit sites, the fail-then-recover cycle the test drives, the determinism result from Verify, and the transient-failure paths left out of scope (the \#482 entry is the canonical wording for the AMQP-transparent-EvilLayer gap).

Verify — determinism

for i in $(seq 1 20); do cargo nextest run -p canopy-test-lib <test_name>; done   # add --run-ignored only for a gated test

Any failure means the test depends on timing, the network or the scheduler. Investigate; never retry until green — the first critical rule of the testing standard. Before merging, outbox_catches_up was verified 20/20 at about 120 ms (CHANGELOG.adoc, #482).

When a fault test fails — arbitration

A failure of a test that runs under a fault gets exactly one of three verdicts (ADR-020 Amendment 1). Record the verdict and its evidence on the issue or the MR that answers the failure.

Verdict It means What follows

GREEN

The product behaved correctly and the fixture is wrong: it asserts something the product does not promise, or its own setup is at fault.

Fix the fixture. The fix may not make the battery easier (the never-easier checklist): no assertion is widened to fit a timeout, and no serialization or envelope changes.

RED

The product is wrong.

File the defect with a seeded reproduction (below). A RED without one is not finished: the fault schedule that showed the defect must be replayable by whoever fixes it.

CANNOT-RUN

The fault could not be applied, so the test proved nothing either way: the proxy did not start, the lever is missing, the fault layer itself failed.

It is a failure, not a skip. It goes to whoever owns the fault layer that failed (for evil_proxy, crates/canopy-test-lib), as an issue.

"Transient" and "environmental" are not verdicts. A failure that does not recur is still one of the three; rerunning until it passes decides nothing. Load is never the cause of a test failure.

Capacity. A failure may be put down to a fixture's capacity (a timeout budget, a pool size, a queue bound the fixture sets) only as a recorded GREEN: the record says which ceiling was wrong, what the application's own constant is, and why the new value follows from it. Without that record the failure is RED.

Replaying a failure under its seed

evil_proxy prints its fault seed and a replay command to stderr when it starts, and again when the test that holds it fails:

evil_proxy: the test failed under fault seed 77; replay: CANOPY_FAULT_SEED=77 cargo nextest run --run-ignored all -E 'binary_id(=canopy-test-lib) & test(=...)'
  1. Copy the command from the failed run's output and run it as printed. CANOPY_FAULT_SEED pins the latency and failure draws of every proxy the test starts.

  2. A test that fixes its own seed with EvilLayer::with_seed ignores the variable; its schedule is already the same on every run.

  3. Paste the command into the defect. That is the seeded reproduction a RED verdict needs.

The seed fixes what each request draws, by its place in the arrival order. It does not fix the order in which concurrent requests arrive, so a test that sends requests concurrently may need several runs under the seed to show the failure again. That is a property of the test to record, not a reason to call the failure transient.

Pitfalls

  • Asserting on a target that does not exist yet. The test fails with a dump of every captured signal. Add the target: in the same MR or land the production change first — never merge a test that is structurally impossible to satisfy; that is the trap these contracts exist to close.

  • Multi-threaded runtime. #[tokio::test] defaults to multi-thread; the current_thread flavor is required for SpanCapture.

  • Asserting on container events. Code running inside a devstack container is invisible to SpanCapture even when the test drives it over HTTP; the in-process spawn is the only workaround.

  • Transient AMQP failure injection. evil_proxy is JSON-only and cannot intercept AMQP, so a contract such as "the drainer recovers from publish failures" needs an AMQP-transparent EvilLayer that is not yet scoped; the "drainer fires target: "outbox" on spawn" contract works through the standard harness.

References

NOTE
History — \#462 (retry), \#481 (JWKS) and \#482 (outbox) shipped the first contracts in 2026-05; \#1860 moved the breaker contract in-process as eligibility_circuit_breaker; the JWKS contract went with canopy-auth’s JWKS provider when the services stopped trusting Keycloak directly (ADR-049).
Edit this page · default