Plan: canopy-mq Lapin Auto-Reconnect (Issue #313)

Status

Step Description Status

1

New ConnectionManager in crates/canopy-mq/src/connection.rs. Wraps Arc<RwLock<Connection>>. Public current_channel() returns a fresh Channel (creates one if the pooled one is dead). reconnect() (called on demand from publish/subscribe error paths) re-runs Connection::connect with exponential backoff (100 ms → 30 s, indefinite retries — bounded backoff, unbounded attempts) and stores the new Connection. Public status() proxies to the lapin ConnectionStatus. Clone derive (the inner is Arc).

Done (2026-04-25) — landed in MR !124

2

Rewrite Publisher to hold Arc<ConnectionManager> + Arc<RwLock<Channel>>. Public API (new(channel) → from_manager(manager); publish(envelope) unchanged signature) and Clone preserved. Inside publish: take read lock, call basic_publish. On error: drop the read lock, take a write lock, ask the manager to reconnect, swap the channel, retry basic_publish once. After two consecutive failures the envelope is enqueued in the buffer (Step 3) — caller still gets Ok(()). Add new variants: PublishError::BufferFull.

Done (2026-04-25) — landed in MR !124

3

Bounded in-memory publish queue. Publisher grows an Arc<tokio::sync::Mutex<VecDeque<EventEnvelope>>> with max_buffered_events (default 10 000, CANOPY_MQ_BUFFER_MAX env override). When publish is called and the connection is in Reconnecting / Closed / Error state, the envelope is pushed into the queue and Ok(()) returns to the caller — no lost events during outages within the buffer’s window. A background task spawned by from_manager() drains the queue whenever connection_status.is_connected(), in arrival order, with the same retry-on-error path. Queue overflow returns PublishError::BufferFull so callers can decide (today: log and continue — bounded loss is preferable to OOM). Bounded loss is explicitly not at-least-once durability; the issue’s "out of scope: persistent outbox is a separate ADR-worthy design" stays intact.

Done (2026-04-25) — landed in MR !124

4

Rewrite Subscriber::subscribe_inner to outer-loop the consume body. The spawned task becomes: loop { (channel, mut consumer) = manager.recreate_subscriber_channel(queue_name, routing_keys, queue_options).await?; while let Some(delivery_result) = consumer.next().await { … existing handler/ack/nack logic … }; warn!("consume stream ended — reconnecting subscriber"); }. The inner Err(e) case for delivery_result (subscriber.rs:163-165) gets a fatal-error filter — is_fatal_channel_error(&e) returns true on InvalidChannelState / IOError, breaks the inner loop to trigger reconnect; everything else (including non-fatal AMQP errors) just logs and continues. The consume-stream-end case (while let exits because next() returned None) also triggers the outer reconnect. After reconnect, queue_declare + queue_bind are re-run before basic_consume, since RabbitMQ may have lost the queue if it was non-durable / restart cleared metadata.

Done (2026-04-25) — landed in MR !124

5

Update BootstrapResult in crates/canopy-api/src/bootstrap.rs: instead of holding publisher: Publisher and subscriber: Subscriber directly, hold an Arc<ConnectionManager> and construct Publisher + Subscriber from it. The existing boot.publisher and boot.subscriber fields stay (shape is the same Publisher / Subscriber types) — services don’t change. Bootstrap’s internal logic changes: the one-time connect() + 2× create_channel() becomes ConnectionManager::new(url).await? + manager.publisher() + manager.subscriber(). The 25 Extension<Publisher> call sites stay untouched. No changes to any service’s main.rs — that’s the entire point of this design.

Done (2026-04-25) — landed in MR !124

6

Integration test crates/canopy-mq/tests/reconnect_test.rs. Devstack-gated (skip if infrastructure_available() returns false). Three scenarios: (a) publish-survives-restart: publish event A → docker compose restart rabbitmq (via std::process::Command) → wait for healthy → publish event B → assert subscriber received both. (b) subscriber-survives-restart: spawn subscriber → publish A → restart RabbitMQ → publish B → assert subscriber’s handler fired for A and B. (c) buffer-flushes-after-reconnect: publish 5 events while broker is down → start broker → assert all 5 are delivered. Each test serialises with a pg_advisory_xact_lock-style global lock on a sentinel queue, since docker restart rabbitmq would otherwise trash sibling tests. Tests tagged #[ignore] by default; opt-in via cargo nextest run --test reconnect_test --run-ignored only.

Done (2026-04-25) — landed in MR !124

7

Plan + docs sync. Update docs/modules/ROOT/pages/services.md canopy-mq section with the new ConnectionManager + reconnect semantics. CHANGELOG entry under == Unreleased / === Fixed (this is a bug fix, not a feature). Roadmap row added. Plan file moves to docs/modules/ROOT/pages/plans/archive/ after MR merges (per ADR-013).

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() returns None (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 rabbitmq cycle.

  • Public Publisher / Subscriber API 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 of ConnectionManager; the public surface adds ConnectionManager and trims direct Connection exposure.

  • crates/canopy-mq/src/publisher.rs — Publisher rewrites to use ConnectionManager. Public new(channel: Channel) constructor stays for the test harness path; new from_manager(manager: Arc<ConnectionManager>) is the production path.

  • crates/canopy-mq/src/subscriber.rs — subscribe_inner outer-loops; is_fatal_channel_error helper added.

  • crates/canopy-mq/src/connection.rs — new file with ConnectionManager.

  • crates/canopy-api/src/bootstrap.rs — internal swap from connect + create_channel + create_channel to ConnectionManager::new. Public BootstrapResult.publisher / .subscriber shape unchanged.

  • crates/canopy-mq/Cargo.toml — no new deps. tokio already pulled (RwLock, Mutex). lapin’s existing Connection::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

crates/canopy-mq/src/connection.rs

Refactored

crates/canopy-mq/src/lib.rs, crates/canopy-mq/src/publisher.rs, crates/canopy-mq/src/subscriber.rs

Bootstrap (internal swap)

crates/canopy-api/src/bootstrap.rs

New test

crates/canopy-mq/tests/reconnect_test.rs

Docs

docs/modules/ROOT/pages/services.md (canopy-mq section), docs/modules/ROOT/pages/roadmap.adoc, CHANGELOG.adoc

Plan

docs/modules/ROOT/pages/plans/canopy-mq-lapin-auto-reconnect.adoc

No service-side main.rs changes. No schema migrations. No new dependencies.

Verification

Per-step

  1. cargo nextest run -p canopy-mq — existing 13 unit tests all green (no regressions).

  2. cargo nextest run -p canopy-mq --test reconnect_test --run-ignored only — three new restart-survival tests pass.

  3. cargo xtask validate — full battery green.

End-to-end

  1. cargo xtask dev start — devstack up, wait for all healthy.

  2. Publish a SNAP determination via API: curl -X POST http://localhost:43839/v1/determine …​ — confirm tanf-tma queue depth increments.

  3. docker compose restart rabbitmq — wait for healthy.

  4. Publish another SNAP determination — confirm queue depth increments AGAIN (today this would silently fail; fix should make it work).

  5. Inspect canopy-tanf logs for consumer stream ended — re-attaching and a subsequent subscriber started — confirm reconnect happened automatically.

  6. 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):

  • #388 — Persistent outbox table for at-least-once durability

  • #389 — Configurable buffer-full strategy (drop-newest / drop-oldest / block)

  • #390 — Backpressure signal when publish buffer crosses threshold

Errata

(none)

Edit this page · default