Event-Delivery Protocol
Canopy’s benefit pipelines (adverse actions, continued benefits, assessments) are event-driven, and a lost event is a lost legal obligation. This page is the protocol every load-bearing producer and consumer follows. Substrate changes shipped in #1088 (durable topology) and #1089 (parked-state inbox + versioning + the binding-first gate); the crate mechanics live in canopy-mq.
The contract at a glance
-
Envelope. Every event is an
EventEnvelope(crates/canopy-mq/src/envelope.rs):id(UUID v7),timestamp(UTC),source_service,event_type(the dot-delimited AMQP routing key),schema_version(default 1;CURRENT_SCHEMA_VERSION),payload(schema-less JSON, interpreted byevent_type), optionaltrace_context(W3C TraceContext) and optionalprograms(the publisher’s program-scope assertion, #1519). -
Exchanges and queues. Producers publish to the
canopy.eventstopic exchange (EVENTS_EXCHANGE,crates/canopy-mq/src/lib.rs); dead letters go to thecanopy.dlqdirect exchange (DLX_EXCHANGE,crates/canopy-mq/src/subscriber.rs); the devstack broker parks unroutable publishes in the durablecanopy.unroutedqueue (devstack/rabbitmq/definitions.json). Subscriber queues are namedcanopy-<service>.*. -
Outbox and inbox. Producers write
event_outboxin the domain transaction and the in-process drainer publishes it; consumers record every delivery inevent_inbox. Both tables are single-sourced incrates/canopy-mq/outbox-migrations/and generated into every service (ADR-039); the schema is described once, on the data-models index, not here. -
Knobs. Retention of published outbox rows is
CANOPY_MQ_OUTBOX_RETENTION_DAYS(default 7,outbox_drainer.rs); the inbox’s is the per-serviceinbox_retention_dayssetting (below); the unpark scan interval isCANOPY_MQ_UNPARK_INTERVAL_SECS(default 60,subscriber.rs). The fullCANOPY_MQ_*set with defaults is the Event bus table of the configuration reference.
Inbox retention (#2470)
This is the one home of the event_inbox retention.
-
What is kept. A processed inbox row is what lets a redelivered envelope be acked without re-running its handler; the retention is how long that holds. A service keeps a processed row for
inbox_retention_daysdays after itsprocessed_at(the shared baseline setting,CANOPY_<SERVICE>__INBOX_RETENTION_DAYSorconfig/<service>/*.yaml; default 7, the window the inbox migration documents). A zero, negative or non-numeric value fails the boot. -
What is never deleted. A row with
processed_atNULL: a delivery whose handler failed (it waits for its retry or an operator’s replay) and a parked delivery (it waits for the unpark scanner), whatever their age. A row parked and later processed is processed, and ages out like any other. -
Who deletes. Every service that boots through canopy-api’s bootstrap runs the inbox janitor (
canopy_mq::InboxDrainer,crates/canopy-mq/src/inbox_drainer.rs) on its own pool. It passes once an hour, the first an hour after boot, deleting at most 1,000 rows per statement until a batch comes back short. Each batch takes its rowsFOR UPDATE SKIP LOCKEDin aMATERIALIZEDCTE, so a backlog is never one giantDELETE, a batch is at most its size whatever the plan (#2568), and replicas' janitors split the rows. It stops on the shutdown signal: a draining replica starts no new batch, and a batch in flight lands whole or not at all. It registers that signal listener only when its first hour ends: a listener takes over the signal’s default action, so one registered during boot, before the service’s own handler, would leave a SIGTERM there unanswered by the service. A failed pass is warned and retried next hour. -
The gate.
cargo xtask outbox-migrationsrefuses a service that ownsevent_inbox(itsmigrations/carries20260516000000_create_event_inbox.sql) but whosemaindoes not boot throughcanopy_api::bootstrap_withorcanopy_api::bootstrap_requiring, and a bootstrap that no longer spawns the janitor.
Durable topology (#1088)
-
Subscriber queues are durable by default; the outbox drainer publishes
delivery_mode=2— the persistence chain is end-to-end. -
The devstack broker keeps its state in a compose volume with a pinned hostname; unroutable publishes land in the durable
canopy.unroutedcapture queue via an alternate-exchange policy instead of being discarded. Production brokers must be provisioned equivalently (production-gap register).
The parked-state inbox (#1089)
A load-bearing handler faces three distinct non-success cases, and each has exactly one correct disposition:
| Case | Disposition | Mechanism |
|---|---|---|
Malformed payload on a load-bearing key |
DLQ — never warn-and-ack (that silently discards a legal event) |
return |
Delivery this binary cannot INTERPRET (unknown event type during a
rolling deploy; |
Park — durable, self-recovering |
return |
Legitimately not-for-us (e.g. another program’s event) |
Ack (a considered skip, usually with a |
return |
The subscriber classifies the database’s own refusals the same way (#2964). A refusal of the delivery’s data, a data exception (SQLSTATE class 22) or an integrity violation (class 23), fails identically on every retry, so it is never requeued uncounted. If the inbox itself refuses the envelope (a NUL its JSONB or TEXT cannot hold), whether at the insert or at the park of a newer-schema envelope, the delivery goes to the DLQ at once: the attempt counter lives in the row that cannot be written. If the commit refuses a handler’s writes (a deferred constraint), the failure counts an attempt like a handler error, and the delivery is dead-lettered once its attempts are spent. An error text holding a NUL (a handler failure’s or an unpark failure’s) is stored with U+FFFD in its place. Infrastructure failures (pool, connection, serialization) are still requeued without counting.
Parking rolls back the handler transaction (never committing partial
domain writes), upserts the inbox row with parked_at/park_reason/
queue_name, and ACKs the broker — the inbox row is the durable copy.
Every subscriber runs an unpark scanner
(CANOPY_MQ_UNPARK_INTERVAL_SECS, default 60s) that re-offers parked
rows to the CURRENT binary, so a later deploy that understands the event
processes it with no operator action. canopy_mq::run_unpark_pass is
the on-demand surface for tests and operator tooling. Real handler
failures during an unpark attempt keep the row parked with
attempts/last_error bumped — there is no broker delivery left to
DLQ, so the row itself is the operator signal:
-- Operator triage: parked backlog per queue
SELECT queue_name, count(*), min(enqueued_at)
FROM event_inbox
WHERE parked_at IS NOT NULL AND processed_at IS NULL
GROUP BY queue_name;
The same count is exported as the canopy_mq_inbox_parked gauge
(label queue_name = the physical, prefixed queue), sampled by each
subscriber’s unpark scanner after every pass (#1748) — the inbox
counterpart of the outbox drainer’s canopy_mq_outbox_parked, which
aggregates event_outbox only and never sees a subscriber park. Zero is
recorded too, so the series lowers as rows are processed; a failed
sample is logged and the previous reading stands. It is the metric
surface for an indefinite park class such as a mass_change_cola
approval held against a continuously-recertified household (#1635).
The inbox also serializes concurrent deliveries of one event: the
classify step takes a row lock (FOR UPDATE), so two replicas can never
double-run a committed-but-unprocessed row (#1089; previously possible
via the InFlightRetry path). The inbox schema is single-sourced with
the outbox (ADR-039): canonical files in crates/canopy-mq/outbox-migrations/,
distributed by cargo xtask outbox-migrations --write, parity-gated in
the battery.
Envelope schema versioning (#1089)
EventEnvelope.schema_version (default 1 for pre-#1089 envelopes). The
compatibility rule is additive within a version: consumers tolerate
unknown payload fields; a change that cannot be expressed additively
bumps CURRENT_SCHEMA_VERSION, and older consumers park
(ParkEvent::needs_schema) instead of misinterpreting. Removing or
re-meaning a field without a bump is a correctness defect.
Binding-first deployment (#1089)
An MR that ADDS routing keys to a queue (the consumer/topology half)
lands and deploys BEFORE the MR that emits them (producer activation).
The adverse-action and continued-benefits work split its MRs this way. The tree-level half is
mechanically gated: cargo xtask mq-topology (the mq-topology stage of
cargo xtask validate) fails
when a published key has no in-tree non-wildcard consumer and no entry
in xtask/mq-topology-allow.toml — the allowlist is the honest register
of today’s unbound keys, each with a reason, and goes stale-checked in
the same gate (an entry whose key gains a consumer must be removed).
The canopy-security # audit binding is deliberately excluded from
"consumer" — it would make the gate vacuous.
The same gate cross-checks the PRODUCER half (#1122): every key
published from a service’s tree must match that service’s
topic-permission write regex in devstack/rabbitmq/definitions.json
(failure — the broker would refuse the publish with ACCESS_REFUSED, the
#1102 incident class), a key published only from shared-crate code must
be writable by at least one principal (also a failure), and a decomposable ACL branch
whose key is neither published, subscribed, nor present as a source
literal is flagged stale (advisory).
The publish scanner resolves three key-argument shapes: string
literals, contracts-crate pub const paths, and — since #1272 — a
local variable assigned from a match over consts/literals (the
medicaid ELE grant dispatch shape, whose granted/extended keys
previously hid as an uncounted "dynamic" site and shipped without ACL
coverage). Since #2408 it also reads keys through a publish helper: a
free function in the same file that passes one of its parameters as the
envelope’s key, or to another such helper’s key parameter
(canopy-enrollment’s stage_snap_scoped and publish_snap_scoped).
The helper’s own envelope stays a dynamic site. A call site’s key
resolves when it is a dotted literal or a pub const; any other
argument, and a call inside a macro’s tokens, is not resolved (the
former counts as a dynamic site). A genuinely opaque key expression (format!, a computed
value) counts as a skipped dynamic site, and a dispatch with any
opaque ARM records what it can resolve but stays in the dynamic tally
too — the lint prints the count so a rising number is visible in
review, and a partially-resolvable match can never hide a key more
silently than a fully-dynamic site does.
Queue migration procedure
Renaming a queue or changing its properties on a live broker:
-
Declare the NEW queue (versioned name, e.g.
<queue>.v2) + bindings — consumer MR, deployed first. -
Let producers continue publishing (topic routing delivers to both).
-
Drain the OLD queue to zero depth with no in-flight deliveries (
rabbitmqctl list_queues name messages messages_unacknowledged). -
Unbind, then delete the old queue. Its DLQ is retained until empty and triaged — never deleted with content.
-
Rollback = re-bind the old queue (never deleted before the new one is proven under load).
Property changes on the SAME name (e.g. #1088’s transient→durable) ride the subscriber’s one-time self-heal: PRECONDITION_FAILED → if-empty delete → redeclare. A mismatched queue still holding messages fails loudly for operator action.
Provenance
source_service on the envelope is labeling; the broker principal is
the authentication (#1093). Every service connects with its own
RabbitMQ user (canopy-<service>, devstack creds public by design —
Kerckhoffs; production injects real secrets at deploy) carrying:
-
resource permissions scoped to
canopy.events,canopy.dlq, and the service’s owncanopy-<service>.*queues (write oncanopy.dlqis required by the broker’s declare-time check on queues carryingx-dead-letter-exchange), and -
a topic-permission write regex on
canopy.eventsenumerating exactly the routing keys the service’s tree publishes (^$for publish-only-nothing services) — the broker refuses a forged foreign key at publish time, regardless of whatsource_serviceclaims. Adding a service’s first/new event key means widening its ACL indevstack/rabbitmq/definitions.jsonin the same MR. The matrix was derived from thecargo xtask mq-topology --verbosepublish map and is hand-maintained; drift is now statically gated by the samemq-topologybattery stage (#1122 — a published key its principal cannot write fails the lint before it can fail at the broker), withacl_test.rsproving the broker-side enforcement live.
The DLX residual: canopy.dlq is a direct exchange, so topic ACLs do not
apply there. A service could inject into a neighbor’s DLQ, and while it
cannot read a neighbor’s EXISTING queue, it could bind its own queue to
the shared DLX with a neighbor’s routing key and siphon FUTURE dead
letters. Per-service DLX exchanges are the hardening if that residual
ever matters.
Consequently source_service stays diagnostic — consumers must still
never branch authorization on it (the principal, not the label, is the
guarantee). One recorded carve-out (#1519): the envelope’s programs
field is the AUTHORITATIVE program-scope assertion for the audit-row
programs column — the publisher is the authority on which programs its
own event concerns (the same trust model as programs_requested on
application rows), and the audit store validates the vocabulary and
derives from the routing key when the field is absent. Payload-embedded
program labels remain diagnostic; the store never reads them. Replay never publishes (#1118): a service's admin replay parks the
unprocessed inbox row for the queue recorded on it, and that queue's
unpark scanner re-offers the row to the running binary's handler in
process, within CANOPY_MQ_UNPARK_INTERVAL_SECS (default 60 s). So a
consumer can replay an event whose routing key belongs to another
service, which its broker principal could never re-publish, and no other
consumer sees the event again. The canopy admin principal is not part
of the replay path. The dead-letter copy of a replayed event is left
alone; if it is later shovelled back, it is acked as already processed.
A replayed row whose handler keeps failing stays parked and is retried
once per scanner pass, with attempts and last_error showing each
failure; it has no attempt budget. The report's failed bucket holds
rows that could not be re-offered: no queue is recorded on the row, or
its stored payload does not deserialise.