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 |
|---|---|---|---|
|
|
|
|
|
|
|
every sweep |
|
|
|
|
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:
-
A test using
SpanCaptureMUST 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. -
Production components inside devstack containers are unobservable — the
OutboxDrainereach service’s bootstrap spawns (crates/canopy-api/src/bootstrap.rs) or canopy-eligibility’s programCircuitBreakeremits in another process. There is no cross-process tracing capture today. -
The
chaosharness 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
-
Add a
target:to the production emit sites. In the module (saycrates/canopy-mq/src/inbox_drainer.rs) addtarget: "<name>"to everytracing::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"); -
Make the failure path emit.
?propagation is the usual reason a failure emits nothing.matchthe fallible call’sResultso the failure arm emits under the sametarget:as the success path — the shape of the outbox drainer’sdrain_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 */ } } } -
If the component is not yet harness-spawnable, add a helper.
canopy_test_lib::chaosprovidesspawn_outbox_drainer_for_chaos(pool, broker_url) → Result<ChaosOutboxHandle>(chaos/outbox.rs). A component the test can construct directly needs no helper:eligibility_circuit_breakerbuilds itsCircuitBreakerand anevil_proxyinline. To add one (sayspawn_inbox_drainer_for_chaos):-
Check the production constructor is test-friendly (injectable, clone-friendly, async).
OutboxDrainer::spawnwas; if yours needs production changes to be testable, that is a separate scope — discuss before adding. -
Take an
EvilLayer(HTTP) or abroker_url(AMQP and other non-HTTP). For HTTP, serve the upstream from a mock (crate::mock::spawn_router), wrap it withevil_proxy, and construct the component against the proxy’surl. For AMQP, take the URL directly, aschaos/outbox.rsdoes; the test passes a real devstack URL. -
Return a
Chaos<X>Handleholding the component plus anyMockHandleandEvilProxyHandleas_-prefixed fields, so theirDropimpls (each aborts its server task) run with the handle. -
Re-export from
crates/canopy-test-lib/src/lib.rsbeside the existing harness re-exports, and state the thread-local constraint in the helper’s module rustdoc.
-
-
Write the test in
evil_proxy_test.rsas#[tokio::test(flavor = "current_thread")]: installSpanCapture::install_scopedBEFORE 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 withcapture.assert_span_emitted("<target>")— orassert_span_fieldwhen the contract names fields, aseligibility_circuit_breakerdoes, 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 checkinfrastructure_available().awaitearly; a fully in-process test runs in the regular sweep with no gate. -
Record it.
CHANGELOG.adocunder=== Added: thetarget: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 |
"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(=...)'
-
Copy the command from the failed run's output and run it as printed.
CANOPY_FAULT_SEEDpins the latency and failure draws of every proxy the test starts. -
A test that fixes its own seed with
EvilLayer::with_seedignores the variable; its schedule is already the same on every run. -
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; thecurrent_threadflavor is required forSpanCapture. -
Asserting on container events. Code running inside a devstack container is invisible to
SpanCaptureeven when the test drives it over HTTP; the in-process spawn is the only workaround. -
Transient AMQP failure injection.
evil_proxyis 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 firestarget: "outbox"on spawn" contract works through the standard harness.
References
-
Plan: cross-process chaos observability harness — phase 1 (\#480)
-
crates/canopy-test-lib/src/chaos/mod.rs— module rustdoc with the canonical use shape. -
Testing › Observability assertions — the
SpanCaptureAPI.
eligibility_circuit_breaker; the JWKS contract went with canopy-auth’s JWKS provider when the services stopped trusting Keycloak directly (ADR-049).