Plan: canopy-mq Lapin Auto-Reconnect (Issue #313)
Status
| Step | Description | Status |
|---|---|---|
1 |
New |
Done (2026-04-25) — landed in MR !124 |
2 |
Rewrite |
Done (2026-04-25) — landed in MR !124 |
3 |
Bounded in-memory publish queue. |
Done (2026-04-25) — landed in MR !124 |
4 |
Rewrite |
Done (2026-04-25) — landed in MR !124 |
5 |
Update |
Done (2026-04-25) — landed in MR !124 |
6 |
Integration test |
Done (2026-04-25) — landed in MR !124 |
7 |
Plan + docs sync. Update |
Done (2026-04-25) — landed in MR !124 |
Branch: fix/canopy-mq-lapin-auto-reconnect
Labels: type::bug, priority::high, program::infrastructure, service::shared-crates, workflow::ready
Context
When the RabbitMQ container restarts (crash, OOM, planned upgrade, docker compose restart rabbitmq), every canopy- service that holds a lapin::Connection / Channel via canopy-mq enters a *permanently-broken state. lapin correctly detects the drop, but Publisher::publish() and Subscriber::subscribe_inner both hold a Channel handle constructed once at boot. After the disconnect:
-
Publishes fail with
AMQP error: invalid channel state: Error (basic.publish)and the service never reconnects. -
Subscriber consume loops exit silently when
consumer.next()returnsNone(connection closed) — the spawned tokio task dies and the queue stops being drained. -
Cross-service event flows (SNAP → TSNAP, TANF → TMA, TANF → Medicaid Express Lane, FTI breach detection per ADR-014 §7) silently stop. In production this would manifest as lost events.
MR !79 sidestepped the issue in CI by preventing unnecessary RabbitMQ container recreation, but the underlying fragility remains — any operational restart triggers the cascade. Filed as priority::high type::bug workflow::needs-spec issue #313 with detailed acceptance criteria. RCA trail: TSNAP/TMA/ELE E2E tests have been flaky on pre-push hooks since 2026-04-18; this bug is the likely root cause.
This plan delivers automatic reconnection across the canopy-mq crate with the smallest possible blast radius — the public Publisher / Subscriber API stays unchanged so the 25 Extension<Publisher> call sites across services don’t move.
Scope
In scope:
-
Auto-reconnect with exponential backoff inside
canopy-mq(Connection-level + Channel-level recovery). -
Bounded in-memory publish queue (default 10 000 events) so events are not silently dropped during a brief broker outage.
-
Subscriber consume-loop reattach after channel/connection error.
-
One integration test covering publish + subscribe across a
docker restart rabbitmqcycle. -
Public
Publisher/SubscriberAPI stays Clone-friendly and unchanged for callers — internal swap only.
Out of scope:
-
Persistent outbox for at-least-once durability across process crash. The issue says this is "a separate ADR-worthy design"; agree. The bounded in-memory queue is the interim fix — events delivered during normal operation, events buffered during a broker restart that lasts seconds-to-minutes; events lost only if the service process itself crashes while events are buffered. That last case stays a known limitation until an outbox table is designed.
-
Dead-letter handling for messages the subscriber can’t process (already separate concern).
-
RabbitMQ HA cluster / mirrored queues (operational, not application-layer).
-
Backpressure on producers when the buffer is filling — overflow is dropped + logged + counted (Prometheus counter
canopy_mq_publish_buffer_overflows_total); this is documented as a known cap not a bug. -
Changing any service’s
main.rs— by design.
Dependencies
-
crates/canopy-mq/src/lib.rs—connect()becomes a private helper ofConnectionManager; the public surface addsConnectionManagerand trims directConnectionexposure. -
crates/canopy-mq/src/publisher.rs—Publisherrewrites to useConnectionManager. Publicnew(channel: Channel)constructor stays for the test harness path; newfrom_manager(manager: Arc<ConnectionManager>)is the production path. -
crates/canopy-mq/src/subscriber.rs—subscribe_innerouter-loops;is_fatal_channel_errorhelper added. -
crates/canopy-mq/src/connection.rs— new file withConnectionManager. -
crates/canopy-api/src/bootstrap.rs— internal swap fromconnect + create_channel + create_channeltoConnectionManager::new. PublicBootstrapResult.publisher/.subscribershape unchanged. -
crates/canopy-mq/Cargo.toml— no new deps.tokioalready pulled (RwLock, Mutex). lapin’s existingConnection::status()is sufficient — no new lapin features. -
crates/canopy-mq/tests/reconnect_test.rs— new integration test.
No service-side code changes. No schema migrations.
Design
Why no public-API changes
25 Extension<Publisher> call sites and ~73 publisher.publish().await callers exist across the workspace. Changing the public signature would mean touching every service. Instead, swap internals: Publisher keeps its Clone derive and identical method shape; the inner state changes from Channel to ConnectionManager + RwLock<Channel> + Mutex<VecDeque>.
Connection state machine
┌─ Connected ◄───────┐
│ │ │
Disconnect │ │ publish() │ reconnect succeeds
detected ────────┼───────┤ │
│ │ │
▼ ▼ │
Reconnecting ────► attempt ──┘
▲ │
│ │ attempt fails
└────────────────┘ (backoff 100ms, 200ms, 400ms, … capped at 30s)
ConnectionManager::reconnect() is idempotent and single-flight: a tokio::sync::Mutex<()> guards the reconnect critical section so concurrent publish errors don’t all spawn parallel reconnect attempts. The first caller does the work; subsequent callers .await the same future, then re-check status before returning.
Trust-but-verify status check (post-implementation finding): during integration testing with docker compose restart rabbitmq we discovered that lapin::Connection::status().connected() can lag behind reality — for several seconds after the broker drops the connection, the status flag still reports Connected. If reconnect() short-circuited solely on that flag, the second caller (e.g. a flush-loop tick after a publish failure) would see "already connected" and return Ok without doing the actual reconnect. Fix: reconnect() reads the status, and if it claims connected, performs a probe create_channel call. Only if the probe succeeds do we treat the connection as live and return early; otherwise fall through to a fresh Connection::connect. This is the load-bearing detail that makes the publish + flush-loop path actually drain after a broker bounce.
Publisher with buffer
pub struct Publisher {
manager: Arc<ConnectionManager>,
channel: Arc<RwLock<Channel>>, // current channel, swapped on reconnect
buffer: Arc<Mutex<VecDeque<EventEnvelope>>>,
buffer_max: usize,
}
impl Publisher {
pub async fn publish(&self, envelope: &EventEnvelope) -> Result<(), PublishError> {
validate_payload(&envelope.payload)?; // unchanged
if !self.manager.is_connected() {
return self.enqueue(envelope.clone()).await;
}
match self.try_publish_now(envelope).await {
Ok(()) => Ok(()),
Err(PublishError::Amqp(_)) => {
// Lazy reconnect, retry once.
self.manager.reconnect().await;
self.swap_channel().await;
match self.try_publish_now(envelope).await {
Ok(()) => Ok(()),
Err(_) => self.enqueue(envelope.clone()).await,
}
}
Err(other) => Err(other), // serialization, restricted-field — not retryable
}
}
async fn enqueue(&self, env: EventEnvelope) -> Result<(), PublishError> {
let mut buf = self.buffer.lock().await;
if buf.len() >= self.buffer_max {
metrics::counter!("canopy_mq_publish_buffer_overflows_total").increment(1);
return Err(PublishError::BufferFull);
}
buf.push_back(env);
metrics::gauge!("canopy_mq_publish_buffer_depth").set(buf.len() as f64);
Ok(())
}
}
A separate flush_buffer_task spawned at Publisher::from_manager() time:
loop {
if manager.is_connected() {
let mut buf = self.buffer.lock().await;
while let Some(env) = buf.pop_front() {
// Drain in arrival order. On error, push back front and break.
if try_publish_now(&channel, &env).await.is_err() {
buf.push_front(env);
break;
}
}
drop(buf);
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
Subscriber re-attach
async fn subscribe_inner(...) -> Result<JoinHandle<()>, lapin::Error> {
let manager = self.manager.clone();
let queue_name = queue_name.to_string();
let routing_keys: Vec<String> = routing_keys.iter().map(|s| s.to_string()).collect();
let queue_options = queue_options;
let handle = tokio::spawn(async move {
loop {
let consumer = match attach_consumer(&manager, &queue_name, &routing_keys, queue_options).await {
Ok(c) => c,
Err(e) => {
error!(error = %e, "subscriber attach failed; backing off");
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
};
run_consumer_loop(consumer, &handler).await;
// Loop end means the consumer stream dropped — reconnect and re-attach.
warn!(queue = %queue_name, "consumer stream ended — re-attaching");
}
});
Ok(handle)
}
attach_consumer re-declares the queue + re-binds routing keys + calls basic_consume. RabbitMQ persists durable queues across restart, but routing-key bindings can drift if anything cleared metadata; redeclaring is cheap and idempotent.
Backoff schedule
100 ms → 200 ms → 400 ms → 800 ms → 1.6 s → 3.2 s → 6.4 s → 12.8 s → 25.6 s → 30 s (cap), then steady-state 30 s thereafter. Indefinite attempts. Logged at INFO with attempt and backoff_ms fields per acceptance criteria #5.
Why RwLock<Channel> instead of arc-swap
arc-swap would be ~5 % faster on the publish hot path but requires a new workspace dep. tokio::sync::RwLock is already pulled. Publishes are per-API-call (low rate — eligibility determinations, application submits, notice generations), not per-message-stream — RwLock contention is invisible at this rate. If profiling later shows publish lock contention, switching to arc-swap is a one-line dep + 5-line internal change.
Buffer overflow choice
Bounded buffer overflow returns Err(PublishError::BufferFull) rather than silently dropping. This matches the issue’s AC #3 "preferred — no lost events" while staying honest about the limit. For the worst case (broker outage > buffer-fill time), callers see an explicit error and can log it; today’s behaviour is silent drop, which is strictly worse for compliance posture. Reasonable buffer-full caller behaviour: log at WARN and continue. The compliance-sensitive flows (fti.audit_chain.breach_detected, determination.completed) are bounded in volume — 10 000 events is hours of headroom.
Test architecture for restart-survival
The integration test in crates/canopy-mq/tests/reconnect_test.rs runs against the devstack RabbitMQ container.
async fn restart_rabbitmq_container() {
Command::new("docker")
.args(["compose", "-f", "docker-compose.yml", "restart", "rabbitmq"])
.status()
.expect("docker compose restart");
// Wait for healthy
for _ in 0..30 {
if let Ok(c) = canopy_mq::test_connect().await { drop(c); return; }
tokio::time::sleep(Duration::from_secs(1)).await;
}
panic!("rabbitmq did not come back up");
}
A test-process-level lock (advisory pg lock or a sentinel queue with name like canopy.restart-test-lock) prevents sibling tests from running while the broker is down. Tests are tagged #[ignore] by default and run only via cargo nextest run -p canopy-mq --test reconnect_test --run-ignored only to avoid breaking the default test suite for any developer who doesn’t have devstack up.
Files Touched
| Category | Files |
|---|---|
New module |
|
Refactored |
|
Bootstrap (internal swap) |
|
New test |
|
Docs |
|
Plan |
|
No service-side main.rs changes. No schema migrations. No new dependencies.
Verification
Per-step
-
cargo nextest run -p canopy-mq— existing 13 unit tests all green (no regressions). -
cargo nextest run -p canopy-mq --test reconnect_test --run-ignored only— three new restart-survival tests pass. -
cargo xtask validate— full battery green.
End-to-end
-
cargo xtask dev start— devstack up, wait for all healthy. -
Publish a SNAP determination via API:
curl -X POST http://localhost:43839/v1/determine …— confirmtanf-tmaqueue depth increments. -
docker compose restart rabbitmq— wait for healthy. -
Publish another SNAP determination — confirm queue depth increments AGAIN (today this would silently fail; fix should make it work).
-
Inspect canopy-tanf logs for
consumer stream ended — re-attachingand a subsequentsubscriber started— confirm reconnect happened automatically. -
cargo xtask e2e— flaky TSNAP/TMA/ELE tests should now consistently pass on pre-push hooks.
Potential Improvements
(out of scope; future GitLab issues per ADR-013)
-
Persistent outbox table for at-least-once durability across process crash. ADR-worthy design.
-
arc-swap for publisher hot-path — premature; the existing
RwLock<Channel>is invisible at the per-API-call publish rate. Revisit only if profiling shows lock contention. Deferred indefinitely. -
Configurable buffer-full strategy: drop-newest vs drop-oldest vs block (currently drop-newest with WARN).
-
Backpressure at the publish call site when buffer depth crosses a threshold (e.g. return Err(BufferLow) at 80 % capacity so callers can shed load).
-
Subscriber-side ack-on-buffer-flush semantics for unprocessed deliveries during a reconnect window — buffer is publish-side only; subscribers ack on delivery and the broker handles redelivery on reconnect. Deferred indefinitely.
Tracked follow-ups (filed 2026-05-04 during PI sweep):