Skip to main content

subc_daemon/
router.rs

1use std::{
2    collections::HashMap,
3    error::Error,
4    fmt,
5    sync::{
6        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
7        Arc, Mutex,
8    },
9    time::{Duration, Instant},
10};
11
12use subc_protocol::{error_codes, ErrorBody, Flags, FrameType, Priority};
13use tokio::sync::{mpsc, Notify};
14use tracing::{debug, warn};
15
16use crate::{
17    control::ControlHandler,
18    forwarding::{
19        principal_label, CloseReason, ConnectionCloseReceiver, DataRoute, DataRouteState,
20        ForwardingError, ForwardingTable, RouteBinding, RouteRelease, UndeliveredFrame,
21    },
22    registry::ConnectionId,
23    DaemonCounters, Frame, FrameBuildError,
24};
25
26/// One queued outbound frame plus the instant it entered the writer queue.
27///
28/// The stamp exists for the reply-path half of slow-control diagnosis: a
29/// handler can finish in microseconds while the reply sits in this queue
30/// waiting for the writer task to be scheduled, and without a per-item stamp
31/// that wait is invisible to every other timing point (the client's round
32/// trip is the only witness, and it cannot say which side ate the time).
33/// Constructed exclusively inside [`FrameSink`] so no caller can forget it.
34#[derive(Debug)]
35pub struct OutboundFrame {
36    pub frame: Frame,
37    pub enqueued_at: std::time::Instant,
38    pub(crate) flushed: Option<tokio::sync::oneshot::Sender<()>>,
39    /// This frame's share of the connection's queued-byte count. Dropping the
40    /// frame (after the writer has written it, or when the queue itself is
41    /// dropped with the frame still in it) gives the bytes back. `None` only for
42    /// frames built outside a [`FrameSink`], which exist in tests alone.
43    pub(crate) charge: Option<EgressCharge>,
44}
45
46impl OutboundFrame {
47    fn charged(frame: Frame, charge: EgressCharge) -> Self {
48        Self {
49            frame,
50            enqueued_at: charge.enqueued_at,
51            flushed: None,
52            charge: Some(charge),
53        }
54    }
55}
56
57/// Bytes a frame occupies in the connection's egress queue for budget
58/// purposes: the fixed envelope header plus the body.
59fn queued_frame_bytes(frame: &Frame) -> usize {
60    subc_protocol::HEADER_LEN + frame.body.len()
61}
62
63/// A point-in-time view of one connection's egress queue, for diagnosing why a
64/// frame did not fit.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) struct EgressBacklog {
67    pub queued_bytes: usize,
68    pub queued_frames: usize,
69    /// Now minus the enqueue time of the frame the writer most recently took
70    /// off the queue (the frame it is writing, or has just written), or, if
71    /// the writer has taken nothing since the queue was last empty, of the
72    /// frame that made the queue non-empty. While the writer is blocked on a
73    /// frame this is exactly the oldest frame's age; between frames it can be
74    /// one frame older than the true head. `None` when nothing is queued.
75    pub oldest_age: Option<Duration>,
76}
77
78/// Queued-byte accounting shared by every clone of one connection's
79/// [`FrameSink`] and by every frame that sink has admitted. Its per-frame
80/// accounting uses atomics: this is on the path of every frame a module sends
81/// to a client, so it takes no lock per frame.
82#[derive(Debug)]
83struct EgressAccounting {
84    // Shared by the connection's sink clones so even an invalid data frame
85    // spends the one opportunity to present a claim after authentication.
86    ingress_seen: AtomicBool,
87    ingress_terminal: AtomicBool,
88    egress_terminal: AtomicBool,
89    egress_stopped: Notify,
90    byte_budget: usize,
91    queued_bytes: AtomicUsize,
92    queued_frames: AtomicUsize,
93    /// Origin for the nanosecond timestamps in `oldest_enqueued_nanos`.
94    time_base: Instant,
95    /// Enqueue time, as nanoseconds after `time_base` plus one, of the frame
96    /// described by [`EgressBacklog::oldest_age`]; 0 means none.
97    oldest_enqueued_nanos: AtomicU64,
98    /// Awaited senders currently parked on `freed`. A release only pays for a
99    /// notification when this is non-zero.
100    waiters: AtomicUsize,
101    /// Woken when a charged frame releases its bytes while a sender waits, so
102    /// the awaited send can re-check for room.
103    freed: Notify,
104    client_delivery_closed: AtomicBool,
105    client_delivery_stopped: Notify,
106    #[cfg(test)]
107    retire_after_reserve: AtomicBool,
108}
109
110impl EgressAccounting {
111    fn new(byte_budget: usize) -> Self {
112        Self {
113            ingress_seen: AtomicBool::new(false),
114            ingress_terminal: AtomicBool::new(false),
115            egress_terminal: AtomicBool::new(false),
116            egress_stopped: Notify::new(),
117            byte_budget,
118            queued_bytes: AtomicUsize::new(0),
119            queued_frames: AtomicUsize::new(0),
120            time_base: tokio::time::Instant::now().into_std(),
121            oldest_enqueued_nanos: AtomicU64::new(0),
122            waiters: AtomicUsize::new(0),
123            freed: Notify::new(),
124            client_delivery_closed: AtomicBool::new(false),
125            client_delivery_stopped: Notify::new(),
126            #[cfg(test)]
127            retire_after_reserve: AtomicBool::new(false),
128        }
129    }
130
131    fn stamp(&self, at: Instant) -> u64 {
132        (at.saturating_duration_since(self.time_base).as_nanos() as u64).saturating_add(1)
133    }
134
135    /// Charge `bytes` if they fit in the budget. A frame larger than the whole
136    /// budget (bodies may be up to 64 MiB) is still admitted into an EMPTY
137    /// queue, since it could otherwise never be sent at all; it simply has the
138    /// queue to itself until it is written.
139    fn try_charge(self: &Arc<Self>, bytes: usize) -> Option<EgressCharge> {
140        // SeqCst pairs with `release`: either this load sees bytes a release
141        // just freed, or that release sees this sender counted in `waiters`.
142        let mut current = self.queued_bytes.load(Ordering::SeqCst);
143        loop {
144            if current != 0 && current.saturating_add(bytes) > self.byte_budget {
145                return None;
146            }
147            match self.queued_bytes.compare_exchange_weak(
148                current,
149                current + bytes,
150                Ordering::SeqCst,
151                Ordering::SeqCst,
152            ) {
153                Ok(_) => return Some(self.record(bytes)),
154                Err(actual) => current = actual,
155            }
156        }
157    }
158
159    /// Charge `bytes` regardless of the budget. Used only for a frame whose
160    /// queue slot was reserved in advance, which must be sendable.
161    fn charge_unconditionally(self: &Arc<Self>, bytes: usize) -> EgressCharge {
162        self.queued_bytes.fetch_add(bytes, Ordering::SeqCst);
163        self.record(bytes)
164    }
165
166    fn record(self: &Arc<Self>, bytes: usize) -> EgressCharge {
167        let enqueued_at = tokio::time::Instant::now().into_std();
168        let stamp = self.stamp(enqueued_at);
169        if self.queued_frames.fetch_add(1, Ordering::AcqRel) == 0 {
170            // This frame made the queue non-empty, so it is the head until the
171            // writer takes something.
172            self.oldest_enqueued_nanos.store(stamp, Ordering::Release);
173        }
174        EgressCharge {
175            accounting: Arc::clone(self),
176            bytes,
177            stamp,
178            enqueued_at,
179        }
180    }
181
182    /// The writer has taken the frame stamped `stamp` off the queue.
183    fn taken_by_writer(&self, stamp: u64) {
184        self.oldest_enqueued_nanos.store(stamp, Ordering::Release);
185    }
186
187    fn release(&self, bytes: usize, stamp: u64) {
188        self.queued_bytes.fetch_sub(bytes, Ordering::SeqCst);
189        if self.queued_frames.fetch_sub(1, Ordering::AcqRel) == 1 {
190            // The queue drained. Clear the marker only if it still names this
191            // frame, so a frame admitted in the meantime keeps its stamp.
192            let _ = self.oldest_enqueued_nanos.compare_exchange(
193                stamp,
194                0,
195                Ordering::AcqRel,
196                Ordering::Acquire,
197            );
198        }
199        if self.waiters.load(Ordering::SeqCst) != 0 {
200            self.freed.notify_waiters();
201        }
202    }
203
204    fn backlog(&self) -> EgressBacklog {
205        let queued_frames = self.queued_frames.load(Ordering::Acquire);
206        let stamp = self.oldest_enqueued_nanos.load(Ordering::Acquire);
207        let oldest_age = (queued_frames != 0 && stamp != 0).then(|| {
208            let enqueued = self.time_base + Duration::from_nanos(stamp - 1);
209            tokio::time::Instant::from_std(enqueued).elapsed()
210        });
211        EgressBacklog {
212            queued_bytes: self.queued_bytes.load(Ordering::Acquire),
213            queued_frames,
214            oldest_age,
215        }
216    }
217}
218
219/// One admitted frame's claim on its connection's egress byte budget,
220/// returned when the frame is dropped.
221#[derive(Debug)]
222pub(crate) struct EgressCharge {
223    accounting: Arc<EgressAccounting>,
224    bytes: usize,
225    stamp: u64,
226    enqueued_at: Instant,
227}
228
229impl EgressCharge {
230    /// Called by the connection writer when it takes this frame off the queue,
231    /// so the backlog's oldest-age figure follows the writer.
232    pub(crate) fn taken_by_writer(&self) {
233        self.accounting.taken_by_writer(self.stamp);
234    }
235}
236
237impl Drop for EgressCharge {
238    fn drop(&mut self) {
239        self.accounting.release(self.bytes, self.stamp);
240    }
241}
242
243/// A queue slot reserved ahead of time (a pending `route.open` holds one until
244/// its module answers). Sending through it never waits and never fails for
245/// lack of room: the slot is already held, and its frame is charged to the
246/// byte count outside the budget check. At most
247/// `MAX_PENDING_ROUTE_OPENS_PER_CONNECTION` such frames exist per connection.
248#[derive(Debug)]
249pub(crate) struct EgressPermit {
250    permit: mpsc::OwnedPermit<OutboundFrame>,
251    accounting: Arc<EgressAccounting>,
252}
253
254impl EgressPermit {
255    /// Enqueue `frame` in the reserved slot. Returns true when the connection's
256    /// writer had already gone away or egress was retired, so the frame will
257    /// never be written.
258    pub(crate) fn send(self, frame: Frame) -> bool {
259        if self.accounting.egress_terminal.load(Ordering::Acquire) {
260            return true;
261        }
262        let charge = self
263            .accounting
264            .charge_unconditionally(queued_frame_bytes(&frame));
265        let sender = self.permit.send(OutboundFrame::charged(frame, charge));
266        sender.is_closed()
267    }
268}
269
270/// An `OutboundFrame` is a stamped `Frame`; deref keeps every existing frame
271/// read (headers, bodies, assertions) working on queued items unchanged.
272impl std::ops::Deref for OutboundFrame {
273    type Target = Frame;
274
275    fn deref(&self) -> &Frame {
276        &self.frame
277    }
278}
279
280/// Shared tracing-capture helpers for timing-observability tests across
281/// modules (router dispatch, server reply path). Test-only.
282#[cfg(test)]
283pub(crate) mod test_log {
284    use std::{
285        io::Write,
286        sync::{Arc, Mutex, OnceLock},
287    };
288
289    #[derive(Clone)]
290    struct TestLogWriter(Arc<Mutex<Vec<u8>>>);
291
292    impl Write for TestLogWriter {
293        fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
294            self.0
295                .lock()
296                .expect("test log capture is not poisoned")
297                .extend(buffer);
298            Ok(buffer.len())
299        }
300
301        fn flush(&mut self) -> std::io::Result<()> {
302            Ok(())
303        }
304    }
305
306    pub(crate) fn log_capture(
307        level: tracing::Level,
308    ) -> (Arc<Mutex<Vec<u8>>>, tracing::dispatcher::DefaultGuard) {
309        // tracing-core's single-dispatch fast path registers callsites using
310        // the emitting thread's default subscriber. A parallel test with no
311        // subscriber can therefore cache `never` for a callsite this capture
312        // needs. Keep a second dispatch alive so registration considers all
313        // live subscribers instead. This registry is never installed as a
314        // default: each test still records only into its own thread's writer.
315        static INTEREST_ANCHOR: OnceLock<tracing::Dispatch> = OnceLock::new();
316        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
317        let output = Arc::new(Mutex::new(Vec::new()));
318        let writer = Arc::clone(&output);
319        let subscriber = tracing_subscriber::fmt()
320            .with_max_level(level)
321            .with_ansi(false)
322            .without_time()
323            .with_target(false)
324            .with_writer(move || TestLogWriter(Arc::clone(&writer)))
325            .finish();
326        let guard = tracing::subscriber::set_default(subscriber);
327        (output, guard)
328    }
329
330    pub(crate) fn captured_logs(output: &Arc<Mutex<Vec<u8>>>) -> String {
331        String::from_utf8(
332            output
333                .lock()
334                .expect("test log capture is not poisoned")
335                .clone(),
336        )
337        .expect("tracing output is UTF-8")
338    }
339
340    #[cfg(test)]
341    mod tests {
342        use super::*;
343
344        fn emit_capture_probe(source: &str) {
345            tracing::error!(source, "parallel capture probe");
346        }
347
348        #[test]
349        fn parallel_callsite_registration_keeps_the_test_capture_enabled() {
350            let (output, _guard) = log_capture(tracing::Level::ERROR);
351            // First register the very same callsite on a thread without a
352            // default subscriber, while the test's capture remains live.
353            std::thread::spawn(|| emit_capture_probe("other-thread"))
354                .join()
355                .expect("unsubscribed thread exits");
356            emit_capture_probe("captured-thread");
357
358            let logs = captured_logs(&output);
359            assert!(
360                logs.contains("captured-thread"),
361                "capture was disabled: {logs}"
362            );
363            assert!(!logs.contains("other-thread"), "capture leaked: {logs}");
364        }
365    }
366}
367
368/// Cheaply cloneable handle to one connection's bounded outbound frame queue.
369///
370/// Backends emit responses, streaming frames, and future PUSH frames through this
371/// single path. The queue is bounded twice: by queued BYTES (the budget that
372/// matters for memory and for how long a slow reader may pause), and by the
373/// `mpsc` channel's frame count (a backstop). The socket layer owns the sole
374/// receiver/writer.
375#[derive(Debug, Clone)]
376pub struct FrameSink {
377    tx: mpsc::Sender<OutboundFrame>,
378    accounting: Arc<EgressAccounting>,
379}
380
381impl FrameSink {
382    pub(crate) fn terminate_ingress(&self) {
383        self.accounting
384            .ingress_terminal
385            .store(true, Ordering::Release);
386    }
387
388    pub(crate) fn ingress_terminal(&self) -> bool {
389        self.accounting.ingress_terminal.load(Ordering::Acquire)
390    }
391
392    // Retirement fences every sink clone and reserved permit synchronously,
393    // including senders already waiting for bytes or a queue slot.
394    pub(crate) fn terminate_egress(&self) {
395        self.accounting
396            .egress_terminal
397            .store(true, Ordering::Release);
398        self.accounting.egress_stopped.notify_waiters();
399        self.accounting.freed.notify_waiters();
400    }
401
402    pub(crate) fn egress_terminal(&self) -> bool {
403        self.accounting.egress_terminal.load(Ordering::Acquire)
404    }
405
406    pub(crate) fn first_ingress_frame(&self) -> bool {
407        !self.accounting.ingress_seen.swap(true, Ordering::Relaxed)
408    }
409    /// A sink with the standard per-connection byte budget
410    /// ([`crate::server::CONNECTION_EGRESS_BYTE_BUDGET`]); the frame-count bound
411    /// is whatever capacity `tx`'s channel was created with.
412    pub fn new(tx: mpsc::Sender<OutboundFrame>) -> Self {
413        Self::with_byte_budget(tx, crate::server::CONNECTION_EGRESS_BYTE_BUDGET)
414    }
415
416    pub(crate) fn with_byte_budget(tx: mpsc::Sender<OutboundFrame>, byte_budget: usize) -> Self {
417        Self {
418            tx,
419            accounting: Arc::new(EgressAccounting::new(byte_budget)),
420        }
421    }
422
423    /// Wait until the frame's bytes fit the budget, then charge them. Awaited
424    /// senders (control replies, error replies, shutdown notices) are never
425    /// refused by the byte budget: they wait for the writer to free bytes, just
426    /// as they wait for a free slot, which is the same backpressure they had
427    /// when the queue was bounded by frame count alone. Returns `None` if the
428    /// writer goes away or egress is retired while waiting.
429    async fn charge_waiting(&self, bytes: usize) -> Option<EgressCharge> {
430        if self.egress_terminal() {
431            return None;
432        }
433        if let Some(charge) = self.accounting.try_charge(bytes) {
434            return Some(charge);
435        }
436        // Counted as a waiter for as long as this future is parked, including
437        // when it is cancelled, so releases notify only while someone waits.
438        struct Waiting<'a>(&'a AtomicUsize);
439        impl Drop for Waiting<'_> {
440            fn drop(&mut self) {
441                self.0.fetch_sub(1, Ordering::SeqCst);
442            }
443        }
444        self.accounting.waiters.fetch_add(1, Ordering::SeqCst);
445        let _waiting = Waiting(&self.accounting.waiters);
446        loop {
447            let freed = self.accounting.freed.notified();
448            tokio::pin!(freed);
449            // Register interest before checking, so a release that happens
450            // between the check and the await still wakes this sender.
451            freed.as_mut().enable();
452            if self.egress_terminal() {
453                return None;
454            }
455            if let Some(charge) = self.accounting.try_charge(bytes) {
456                return Some(charge);
457            }
458            tokio::select! {
459                _ = &mut freed => {}
460                _ = self.tx.closed() => return None,
461            }
462        }
463    }
464
465    // Queue admission must recheck retirement after waiting for a frame slot,
466    // including when the bytes were charged before retirement began. Ordinary
467    // sends silently discard retired traffic; flush callers must not report it
468    // as queued or written.
469    async fn send_outbound(&self, outbound: OutboundFrame) -> Result<bool, RouterError> {
470        let stopped = self.accounting.egress_stopped.notified();
471        tokio::pin!(stopped);
472        stopped.as_mut().enable();
473        if self.egress_terminal() {
474            return Ok(false);
475        }
476        let header = &outbound.frame.header;
477        let closed = || {
478            RouterError::backend_with_epoch(
479                header.channel,
480                header.epoch,
481                header.corr,
482                "connection writer closed",
483            )
484        };
485        let permit = tokio::select! {
486            biased;
487            _ = &mut stopped => return Ok(false),
488            permit = self.tx.reserve() => permit.map_err(|_| closed())?,
489        };
490        if self.egress_terminal() {
491            return Ok(false);
492        }
493        permit.send(outbound);
494        Ok(true)
495    }
496
497    pub async fn send(&self, frame: Frame) -> Result<(), RouterError> {
498        if self.egress_terminal() {
499            return Ok(());
500        }
501        let channel = frame.header.channel;
502        let epoch = frame.header.epoch;
503        let corr = frame.header.corr;
504        let closed =
505            || RouterError::backend_with_epoch(channel, epoch, corr, "connection writer closed");
506        let Some(charge) = self.charge_waiting(queued_frame_bytes(&frame)).await else {
507            return if self.egress_terminal() {
508                Ok(())
509            } else {
510                Err(closed())
511            };
512        };
513        self.send_outbound(OutboundFrame::charged(frame, charge))
514            .await
515            .map(|_| ())
516    }
517
518    /// Shutdown notices must leave the socket writer before an idle daemon exits.
519    /// Queue admission alone does not prove this; the writer acknowledges flush.
520    ///
521    /// The local endpoint uses it the same way for its clients-only refusal: the
522    /// connection closes right after the refusal is sent, so the writer must
523    /// flush it first.
524    pub async fn send_flushed(&self, frame: Frame) -> Result<(), RouterError> {
525        self.send_flushed_notifying_enqueue(frame, || {}).await
526    }
527
528    /// Notify the caller after queue admission, before waiting for the writer's
529    /// flush, so cancellation withdraws only requests that could have arrived.
530    pub(crate) async fn send_flushed_notifying_enqueue(
531        &self,
532        frame: Frame,
533        queued: impl FnOnce(),
534    ) -> Result<(), RouterError> {
535        let (tx, rx) = tokio::sync::oneshot::channel();
536        let charge = self
537            .charge_waiting(queued_frame_bytes(&frame))
538            .await
539            .ok_or_else(|| RouterError::backend(0, 0, "connection writer closed"))?;
540        let mut outbound = OutboundFrame::charged(frame, charge);
541        outbound.flushed = Some(tx);
542        if !self.send_outbound(outbound).await? {
543            return Err(RouterError::backend(0, 0, "connection egress retired"));
544        }
545        queued();
546        rx.await
547            .map_err(|_| RouterError::backend(0, 0, "connection flush failed"))
548    }
549
550    pub(crate) async fn reserve_owned(&self) -> Result<EgressPermit, RouterError> {
551        let stopped = self.accounting.egress_stopped.notified();
552        tokio::pin!(stopped);
553        stopped.as_mut().enable();
554        if self.egress_terminal() {
555            return Err(RouterError::backend(0, 0, "connection egress retired"));
556        }
557        let permit = tokio::select! {
558            biased;
559            _ = &mut stopped => return Err(RouterError::backend(0, 0, "connection egress retired")),
560            permit = self.tx.clone().reserve_owned() => permit
561                .map_err(|_| RouterError::backend(0, 0, "connection writer closed"))?,
562        };
563        #[cfg(test)]
564        if self
565            .accounting
566            .retire_after_reserve
567            .swap(false, Ordering::Relaxed)
568        {
569            self.terminate_egress();
570        }
571        if self.egress_terminal() {
572            return Err(RouterError::backend(0, 0, "connection egress retired"));
573        }
574        Ok(EgressPermit {
575            permit,
576            accounting: Arc::clone(&self.accounting),
577        })
578    }
579
580    #[cfg(test)]
581    pub(crate) fn try_reserve_owned(&self) -> Result<EgressPermit, RouterError> {
582        if self.egress_terminal() {
583            return Err(RouterError::backend(0, 0, "connection egress retired"));
584        }
585        let permit = self
586            .tx
587            .clone()
588            .try_reserve_owned()
589            .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
590        Ok(EgressPermit {
591            permit,
592            accounting: Arc::clone(&self.accounting),
593        })
594    }
595
596    pub(crate) fn is_closed(&self) -> bool {
597        self.tx.is_closed()
598    }
599
600    /// What the connection's egress queue holds right now.
601    pub(crate) fn backlog(&self) -> EgressBacklog {
602        self.accounting.backlog()
603    }
604
605    /// Stop module deliveries as soon as the client reader exits, without
606    /// waiting for the socket writer's separate teardown drain grace.
607    pub(crate) fn close_client_delivery(&self) {
608        self.accounting
609            .client_delivery_closed
610            .store(true, Ordering::Release);
611        self.accounting.client_delivery_stopped.notify_waiters();
612    }
613
614    /// A full queue can be a short fanout burst rather than a stopped reader.
615    /// Spend only the grace the atomic backlog age has not already used.
616    async fn send_to_client(&self, frame: Frame) -> Result<(), ClientDeliveryFailure> {
617        if self.egress_terminal() {
618            return Ok(());
619        }
620        let frame_type = frame.header.ty;
621        let flags = frame.header.flags;
622        let stopped = self.accounting.client_delivery_stopped.notified();
623        tokio::pin!(stopped);
624        stopped.as_mut().enable();
625        let failure = |cause, error| ClientDeliveryFailure {
626            diagnosis: ClientDeliveryDiagnosis {
627                frame_type,
628                flags,
629                cause,
630            },
631            error,
632        };
633        let closed = || {
634            RouterError::backend_with_epoch(
635                frame.header.channel,
636                frame.header.epoch,
637                frame.header.corr,
638                "client connection closed",
639            )
640        };
641        if self
642            .accounting
643            .client_delivery_closed
644            .load(Ordering::Acquire)
645        {
646            return Err(failure("client_closed", closed()));
647        }
648        let (frame, error) = match self.try_send_owned(frame) {
649            Ok(()) => return Ok(()),
650            Err(refused) => refused,
651        };
652        if self.is_closed() {
653            return Err(failure("client_closed", error));
654        }
655        let grace = crate::server::CONNECTION_EGRESS_STALL_GRACE;
656        let age = self.backlog().oldest_age.unwrap_or_default();
657        if age > grace {
658            return Err(failure("oldest_frame_older_than_250_ms", error));
659        }
660        let result = tokio::select! {
661            biased;
662            _ = &mut stopped => return Err(failure("client_closed", error)),
663            result = tokio::time::timeout(grace.saturating_sub(age), self.send(frame)) => result,
664        };
665        match result {
666            Ok(Ok(())) => Ok(()),
667            Ok(Err(error)) => Err(failure("client_closed", error)),
668            Err(_) => Err(failure("waited_250_ms_without_room", error)),
669        }
670    }
671
672    /// Enqueue without waiting. Fails when the frame's bytes would take the
673    /// queue past its byte budget, when the channel's frame-count backstop is
674    /// full, or when the writer is gone.
675    pub(crate) fn try_send(&self, frame: Frame) -> Result<(), RouterError> {
676        self.try_send_owned(frame).map_err(|(_, error)| error)
677    }
678
679    fn try_send_owned(&self, frame: Frame) -> Result<(), (Frame, RouterError)> {
680        if self.egress_terminal() {
681            return Ok(());
682        }
683        let channel = frame.header.channel;
684        let epoch = frame.header.epoch;
685        let corr = frame.header.corr;
686        let unavailable = |why: String| {
687            RouterError::backend_with_epoch(
688                channel,
689                epoch,
690                corr,
691                format!("connection writer unavailable: {why}"),
692            )
693        };
694        let bytes = queued_frame_bytes(&frame);
695        let Some(charge) = self.accounting.try_charge(bytes) else {
696            if self.tx.is_closed() {
697                return Err((frame, unavailable("channel closed".to_string())));
698            }
699            return Err((
700                frame,
701                unavailable(format!(
702                    "egress byte budget exhausted ({} queued bytes, frame of {bytes} bytes, budget {})",
703                    self.accounting.queued_bytes.load(Ordering::Acquire),
704                    self.accounting.byte_budget
705                )),
706            ));
707        };
708        // Return the refused frame for a bounded retry; dropping the rest of
709        // the outbound wrapper returns its charge.
710        if self.egress_terminal() {
711            return Ok(());
712        }
713        self.tx
714            .try_send(OutboundFrame::charged(frame, charge))
715            .map_err(|err| {
716                let error = unavailable(err.to_string());
717                (err.into_inner().frame, error)
718            })
719    }
720}
721
722#[derive(Debug)]
723struct ClientDeliveryFailure {
724    diagnosis: ClientDeliveryDiagnosis,
725    error: RouterError,
726}
727
728/// Header facts only: payloads can contain secrets and must never enter logs.
729#[derive(Debug)]
730pub(crate) struct ClientDeliveryDiagnosis {
731    pub frame_type: FrameType,
732    pub flags: Flags,
733    pub cause: &'static str,
734}
735
736impl fmt::Display for ClientDeliveryFailure {
737    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
738        self.error.fmt(f)
739    }
740}
741
742/// Minimum time between two route GOODBYEs the daemon sends one module
743/// connection for one channel in answer to the module's frames on a (channel,
744/// epoch) the daemon holds no route for.
745///
746/// A module that missed a GOODBYE keeps sending on that route (a streaming
747/// module, many frames a second), and every one of those frames lands here. One
748/// answer is enough when it arrives, so answering each frame would only flood
749/// the module's egress queue at the moment it is already behind. Five seconds
750/// is long enough for an answer queued behind a deep backlog to reach the module
751/// and take effect before a second is sent, and short enough that an answer
752/// the queue refused is retried by the next orphan frame well within a minute.
753const ORPHAN_ROUTE_GOODBYE_INTERVAL: Duration = Duration::from_secs(5);
754
755/// Once one connection has this many remembered channels, entries older than
756/// [`ORPHAN_ROUTE_GOODBYE_INTERVAL`] are pruned before another is added. An
757/// expired entry has no effect on rate limiting, so pruning never changes a
758/// decision; it keeps a module that orphaned many channels long ago from
759/// pinning memory for all of them. The map is bounded in any case by the
760/// 16-bit channel space and is dropped whole when the connection ends.
761const ORPHAN_ROUTE_GOODBYE_PRUNE_AT: usize = 256;
762
763/// When each module connection was last sent an orphan-route GOODBYE, per
764/// channel. Shared by the [`Router`] (which consults it) and every
765/// [`RouterConnection`] (which removes its own entry when the connection ends).
766#[derive(Debug, Default)]
767struct OrphanGoodbyeLimiter {
768    last_sent: Mutex<HashMap<ConnectionId, HashMap<u16, tokio::time::Instant>>>,
769}
770
771impl OrphanGoodbyeLimiter {
772    /// True, and the send recorded, when `channel` on `connection_id` has not
773    /// been answered within the interval.
774    fn claim(&self, connection_id: ConnectionId, channel: u16) -> bool {
775        let now = tokio::time::Instant::now();
776        let mut last_sent = self
777            .last_sent
778            .lock()
779            .unwrap_or_else(std::sync::PoisonError::into_inner);
780        let channels = last_sent.entry(connection_id).or_default();
781        if channels.get(&channel).is_some_and(|sent| {
782            now.saturating_duration_since(*sent) < ORPHAN_ROUTE_GOODBYE_INTERVAL
783        }) {
784            return false;
785        }
786        if channels.len() >= ORPHAN_ROUTE_GOODBYE_PRUNE_AT {
787            channels.retain(|_, sent| {
788                now.saturating_duration_since(*sent) < ORPHAN_ROUTE_GOODBYE_INTERVAL
789            });
790        }
791        channels.insert(channel, now);
792        true
793    }
794
795    fn forget_connection(&self, connection_id: ConnectionId) {
796        self.last_sent
797            .lock()
798            .unwrap_or_else(std::sync::PoisonError::into_inner)
799            .remove(&connection_id);
800    }
801}
802
803/// Per-route context shared with backends besides the frame itself.
804#[derive(Debug, Clone)]
805pub struct RouteCtx {
806    pub connection_id: ConnectionId,
807    pub egress: FrameSink,
808}
809
810/// Closed set of data-plane backends for non-zero channels.
811///
812/// Channel 0 is structurally special and remains `Router::control`, not an
813/// enum variant. Static/test backends live in `Router::backends`; the forwarding
814/// backend is selected dynamically only when a per-connection forwarding binding exists.
815#[derive(Debug, Clone)]
816pub enum Backend {
817    Echo(EchoBackend),
818    Forward(ForwardBackend),
819}
820
821impl From<EchoBackend> for Backend {
822    fn from(backend: EchoBackend) -> Self {
823        Self::Echo(backend)
824    }
825}
826
827impl From<ForwardBackend> for Backend {
828    fn from(backend: ForwardBackend) -> Self {
829        Self::Forward(backend)
830    }
831}
832
833impl Backend {
834    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
835        match self {
836            Self::Echo(backend) => backend.handle(ctx, frame).await,
837            Self::Forward(backend) => backend.handle(ctx, frame).await,
838        }
839    }
840}
841
842/// I/O-agnostic splice router keyed by envelope `channel`.
843///
844/// Channel 0 is reserved for subc itself and is always dispatched to the
845/// dedicated control handler. Other channels must be explicitly registered.
846/// Unknown client-originated non-zero channels are translated to canonical JSON `ERROR` frames on
847/// the connection sink so the peer can continue using the same socket. Module-originated frames for
848/// released route channels are logged and dropped as the channel-gone race backstop.
849///
850/// DATA-PLANE BODIES ARE NEVER DECODED HERE, and the consequence is worth stating
851/// because it looks like a guarantee and is not. Additive fields in a request or
852/// response body reach the far side untouched — not because anything permits them,
853/// but because routing reads only the 21-byte header and treats the body as opaque
854/// bytes. That is a performance property, so **nothing prevents it from changing**:
855/// a future reason to inspect a body would convert a wire-transparent path into a
856/// filtering one, and nobody would think of it as a contract change.
857///
858/// So when a peer asks whether subc sees an additive field, the answer is per-path
859/// and this path's zero means WE NEVER LOOK rather than WE LOOK AT EVERYTHING. The
860/// control plane (typed enums at the frame boundary) and the MCP gateway (envelope
861/// unwrap plus a named struct) both narrow; only this one does not.
862pub struct Router {
863    backends: HashMap<u16, Backend>,
864    control: Arc<ControlHandler>,
865    forwarding: Arc<ForwardingTable>,
866    forward_backend: ForwardBackend,
867    counters: DaemonCounters,
868    next_connection_id: AtomicU64,
869    orphan_goodbyes: Arc<OrphanGoodbyeLimiter>,
870}
871
872impl Router {
873    pub fn with_control_handler(control: Arc<ControlHandler>) -> Self {
874        // The handler the router serves is the one a swap must tell when it
875        // promotes a candidate; this is where it first sits behind an `Arc`.
876        control.install_swap_promotion_observer();
877        let forwarding = control.forwarding();
878        let counters = control.counters();
879        Self {
880            backends: HashMap::new(),
881            control,
882            forwarding: Arc::clone(&forwarding),
883            forward_backend: ForwardBackend::new(forwarding),
884            counters,
885            // ConnectionId::LOCAL is 0; real socket ids start at 1 and never collide.
886            next_connection_id: AtomicU64::new(1),
887            orphan_goodbyes: Arc::default(),
888        }
889    }
890
891    /// Install only the inherited-channel service; the supervisor must not own
892    /// this router or retain it after the listeners have stopped serving.
893    pub(crate) fn install_registration_service(self: &Arc<Self>, auth: crate::server::ServerAuth) {
894        self.control
895            .install_registration_service(Arc::downgrade(self), auth);
896    }
897
898    pub fn with_default_self_handler() -> Self {
899        Self::with_control_handler(Arc::new(ControlHandler::default()))
900    }
901
902    pub fn forwarding(&self) -> Arc<ForwardingTable> {
903        Arc::clone(&self.forwarding)
904    }
905
906    pub fn register_backend(
907        &mut self,
908        channel: u16,
909        backend: impl Into<Backend>,
910    ) -> Result<(), RouterError> {
911        self.register_backend_arc(channel, Arc::new(backend.into()))
912    }
913
914    pub(crate) fn register_backend_arc(
915        &mut self,
916        channel: u16,
917        backend: Arc<Backend>,
918    ) -> Result<(), RouterError> {
919        if channel == 0 {
920            return Err(RouterError::ReservedChannelZero);
921        }
922        if self.backends.contains_key(&channel) {
923            return Err(RouterError::DuplicateChannel { channel });
924        }
925        self.backends.insert(channel, backend.as_ref().clone());
926        Ok(())
927    }
928
929    /// Start a connection-scoped routing context. Dropping the guard releases
930    /// any control-plane registrations owned by the connection.
931    fn record_module_frame_drop(&self, connection_id: ConnectionId) -> Result<(), RouterError> {
932        let module_id = self
933            .forwarding
934            .module_id_for_connection(connection_id)
935            .map_err(RouterError::Forwarding)?;
936        self.counters
937            .increment_module_frames_dropped_no_route(module_id.as_deref());
938        Ok(())
939    }
940
941    /// A module sent a non-request frame on a (channel, epoch) the daemon holds
942    /// no route for: most often a route the daemon released whose GOODBYE the
943    /// module never received, so the module still believes it is open and keeps
944    /// sending. Count the drop, and tell the module to let go of exactly that
945    /// (channel, epoch) with a route GOODBYE, at most once per
946    /// [`ORPHAN_ROUTE_GOODBYE_INTERVAL`] per connection and channel.
947    ///
948    /// The answer uses `try_send`: it is a best-effort nudge, and if the queue
949    /// refuses it, the module's next frame on that route after the interval
950    /// asks again. A GOODBYE from the module is not answered, since the module
951    /// is already letting go of the route.
952    fn handle_orphan_module_frame(&self, ctx: &RouteCtx, frame: &Frame) -> Result<(), RouterError> {
953        let channel = frame.header.channel;
954        let epoch = frame.header.epoch;
955        let module_id = self
956            .forwarding
957            .module_id_for_connection(ctx.connection_id)
958            .map_err(RouterError::Forwarding)?;
959        self.counters
960            .increment_module_frames_dropped_no_route(module_id.as_deref());
961        if self
962            .forwarding
963            .module_route_epoch_was_allocated(ctx.connection_id, channel, epoch)
964            .map_err(RouterError::Forwarding)?
965        {
966            self.counters
967                .increment_module_frames_dropped_released_route(module_id.as_deref());
968        }
969        if frame.header.ty == FrameType::Goodbye
970            || !self.orphan_goodbyes.claim(ctx.connection_id, channel)
971        {
972            return Ok(());
973        }
974        let goodbye = Frame::build_with_version(
975            frame.header.ver,
976            FrameType::Goodbye,
977            Flags::new(false, Priority::Passive, false),
978            channel,
979            epoch,
980            0,
981            Vec::new(),
982        )
983        .map_err(RouterError::FrameBuild)?;
984        match ctx.egress.try_send(goodbye) {
985            Ok(()) => {
986                self.counters.increment_module_orphan_route_goodbyes_sent();
987                debug!(
988                    connection_id = ctx.connection_id.get(),
989                    module_id = module_id.as_deref().unwrap_or("unknown"),
990                    channel,
991                    epoch,
992                    "answered module frame on a route the daemon does not hold with a route GOODBYE"
993                );
994            }
995            Err(err) => {
996                self.forwarding.warn_frame_drop(
997                    ctx.connection_id,
998                    channel,
999                    epoch,
1000                    "daemon_to_module",
1001                    if ctx.egress.is_closed() {
1002                        "endpoint_gone"
1003                    } else {
1004                        "egress_budget"
1005                    },
1006                );
1007                debug!(
1008                connection_id = ctx.connection_id.get(),
1009                module_id = module_id.as_deref().unwrap_or("unknown"),
1010                channel,
1011                epoch,
1012                error = %err,
1013                "could not enqueue route GOODBYE for module frame on a route the daemon does not hold; the next such frame retries"
1014                );
1015            }
1016        }
1017        Ok(())
1018    }
1019
1020    pub fn begin_connection(&self) -> RouterConnection {
1021        let raw = self.next_connection_id.fetch_add(1, Ordering::Relaxed);
1022        let id = ConnectionId::new(raw);
1023        let close_receiver = self.forwarding.register_connection_close(id);
1024        RouterConnection {
1025            id,
1026            control_handler: Arc::clone(&self.control),
1027            forwarding: Arc::clone(&self.forwarding),
1028            close_receiver: Some(close_receiver),
1029            orphan_goodbyes: Arc::clone(&self.orphan_goodbyes),
1030        }
1031    }
1032
1033    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
1034        self.control.route_open_target(frame)
1035    }
1036
1037    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
1038        self.control.record_local_connection(connection);
1039    }
1040
1041    /// Reserve an `activity.subscribe` correlation before the reader hands the
1042    /// request to a task; hold the result for the task's lifetime.
1043    pub(crate) fn reserve_activity_subscription(
1044        &self,
1045        ctx: &RouteCtx,
1046        frame: &Frame,
1047    ) -> Option<impl Send + 'static> {
1048        self.control
1049            .reserve_activity_subscription(ctx.connection_id, frame)
1050    }
1051
1052    pub(crate) fn record_captured_peer(
1053        &self,
1054        connection: ConnectionId,
1055        peer: subc_os::local_peer::CapturedPeer,
1056    ) {
1057        self.control.record_captured_peer(connection, peer);
1058    }
1059
1060    pub(crate) fn record_caller_endpoints(
1061        &self,
1062        connection: ConnectionId,
1063        endpoints: Option<(std::net::SocketAddr, std::net::SocketAddr)>,
1064    ) {
1065        self.control.record_caller_endpoints(connection, endpoints);
1066    }
1067
1068    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
1069        self.control.defers_privileged_control(ctx, frame)
1070    }
1071
1072    pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
1073        self.control.defers_config_approval(frame)
1074    }
1075
1076    pub(crate) fn reserve_config_approval(
1077        &self,
1078        ctx: &RouteCtx,
1079        frame: &Frame,
1080    ) -> Result<
1081        Option<crate::config_gate::runtime::ApprovalRequestGuard>,
1082        crate::config_gate::GateError,
1083    > {
1084        self.control.reserve_config_approval(ctx, frame)
1085    }
1086
1087    pub(crate) fn route_open_capacity_refusal(
1088        &self,
1089        ctx: &RouteCtx,
1090        frame: &Frame,
1091        target_module_id: &str,
1092        in_flight: usize,
1093        limit: usize,
1094    ) -> Result<Frame, RouterError> {
1095        self.control
1096            .route_open_capacity_refusal(ctx, frame, target_module_id, in_flight, limit)
1097    }
1098
1099    pub async fn route_for_connection(
1100        &self,
1101        ctx: &RouteCtx,
1102        frame: Frame,
1103    ) -> Result<(), RouterError> {
1104        self.route_for_connection_started(ctx, frame, None).await
1105    }
1106
1107    pub(crate) async fn observe_connection_wait<F: std::future::Future>(
1108        &self,
1109        ctx: &RouteCtx,
1110        kind: &'static str,
1111        future: F,
1112    ) -> F::Output {
1113        self.counters
1114            .observe_reader_wait(
1115                || {
1116                    let module = self
1117                        .forwarding
1118                        .module_id_for_connection(ctx.connection_id)
1119                        .ok()
1120                        .flatten();
1121                    let principal = if module.is_some() { "module" } else { "direct" };
1122                    (
1123                        module.unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
1124                        principal.into(),
1125                    )
1126                },
1127                kind,
1128                future,
1129            )
1130            .await
1131    }
1132
1133    pub(crate) async fn route_for_connection_started(
1134        &self,
1135        ctx: &RouteCtx,
1136        frame: Frame,
1137        dispatch_started_at: Option<Instant>,
1138    ) -> Result<(), RouterError> {
1139        // Embedded callers have no socket reader; mark at their ingress instead.
1140        let first = ctx.egress.first_ingress_frame();
1141        self.route_for_connection_ingress(ctx, frame, dispatch_started_at, first)
1142            .await
1143    }
1144
1145    pub(crate) async fn route_for_connection_ingress(
1146        &self,
1147        ctx: &RouteCtx,
1148        frame: Frame,
1149        dispatch_started_at: Option<Instant>,
1150        first: bool,
1151    ) -> Result<(), RouterError> {
1152        if ctx.egress.ingress_terminal() {
1153            return Ok(());
1154        }
1155        let channel = frame.header.channel;
1156        let epoch = frame.header.epoch;
1157        let corr = frame.header.corr;
1158        if channel == 0 {
1159            debug!(
1160                connection_id = ctx.connection_id.get(),
1161                corr,
1162                frame_type = ?frame.header.ty,
1163                "routing control frame"
1164            );
1165            // The connection loop dispatches every control operation directly
1166            // except `route.open`, activity writes, held config approvals and
1167            // privileged requests. Each
1168            // task passes a timestamp captured before
1169            // spawn, so slow-dispatch timing includes scheduler delay but no
1170            // wait in an application-owned queue.
1171            let dispatch_started_at = (frame.header.ty == FrameType::Request)
1172                .then(|| dispatch_started_at.unwrap_or_else(Instant::now));
1173            // Only review-producing requests need the post-flush receipt hook.
1174            // Probing every response would scan large catalog bodies again.
1175            let review_request = self.control.config_desktop_review_request(&frame);
1176            let responses = self
1177                .control
1178                .handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
1179                .await?;
1180            for response in responses {
1181                let view = if review_request {
1182                    self.control
1183                        .config_desktop_review_response(ctx.connection_id, &response)
1184                        .await
1185                } else {
1186                    None
1187                };
1188                if let Some(view) = view {
1189                    self.observe_connection_wait(
1190                        ctx,
1191                        "reply_egress",
1192                        self.control
1193                            .deliver_config_desktop_review(ctx, response, view),
1194                    )
1195                    .await?;
1196                    continue;
1197                }
1198                self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(response))
1199                    .await?;
1200            }
1201            return Ok(());
1202        }
1203
1204        let data_route = self
1205            .forwarding
1206            .lookup_data_route(ctx.connection_id, channel, epoch)
1207            .map_err(RouterError::Forwarding)?;
1208
1209        match data_route {
1210            DataRoute::Module(DataRouteState::EpochMismatch) => {
1211                self.forwarding.warn_frame_drop(
1212                    ctx.connection_id,
1213                    channel,
1214                    epoch,
1215                    "module_to_client",
1216                    "stale_epoch",
1217                );
1218                if frame.header.ty == FrameType::Request {
1219                    self.counters
1220                        .increment_module_requests_dropped_stale_route();
1221                    let err = RouterError::StaleRouteEpoch {
1222                        channel,
1223                        epoch,
1224                        corr,
1225                    };
1226                    if let Some(error_frame) = err.to_error_frame() {
1227                        self.observe_connection_wait(
1228                            ctx,
1229                            "reply_egress",
1230                            ctx.egress.send(error_frame),
1231                        )
1232                        .await?;
1233                    }
1234                } else {
1235                    self.handle_orphan_module_frame(ctx, &frame)?;
1236                }
1237                debug!(
1238                    connection_id = ctx.connection_id.get(),
1239                    channel, epoch, corr, "dropping module frame for stale route epoch"
1240                );
1241                return Ok(());
1242            }
1243            DataRoute::Module(DataRouteState::Reserved) => {
1244                self.forwarding.warn_frame_drop(
1245                    ctx.connection_id,
1246                    channel,
1247                    epoch,
1248                    "module_to_client",
1249                    "missing_binding",
1250                );
1251                if frame.header.ty == FrameType::Request {
1252                    self.counters
1253                        .increment_module_requests_dropped_stale_route();
1254                    let err = RouterError::UnknownChannel {
1255                        channel,
1256                        epoch,
1257                        corr,
1258                    };
1259                    if let Some(error_frame) = err.to_error_frame() {
1260                        self.observe_connection_wait(
1261                            ctx,
1262                            "reply_egress",
1263                            ctx.egress.send(error_frame),
1264                        )
1265                        .await?;
1266                    }
1267                } else {
1268                    self.record_module_frame_drop(ctx.connection_id)?;
1269                }
1270                debug!(
1271                    connection_id = ctx.connection_id.get(),
1272                    channel, epoch, corr, "dropping module frame for reserved route handle"
1273                );
1274                return Ok(());
1275            }
1276            DataRoute::Module(DataRouteState::Absent) => {
1277                self.forwarding.warn_frame_drop(
1278                    ctx.connection_id,
1279                    channel,
1280                    epoch,
1281                    "module_to_client",
1282                    "unknown_channel",
1283                );
1284                if frame.header.ty == FrameType::Request {
1285                    self.counters
1286                        .increment_module_requests_dropped_stale_route();
1287                    let err = RouterError::UnknownChannel {
1288                        channel,
1289                        epoch,
1290                        corr,
1291                    };
1292                    if let Some(error_frame) = err.to_error_frame() {
1293                        self.observe_connection_wait(
1294                            ctx,
1295                            "reply_egress",
1296                            ctx.egress.send(error_frame),
1297                        )
1298                        .await?;
1299                    }
1300                } else {
1301                    self.handle_orphan_module_frame(ctx, &frame)?;
1302                }
1303                debug!(
1304                    connection_id = ctx.connection_id.get(),
1305                    channel, epoch, corr, "dropping module frame for absent route handle"
1306                );
1307                return Ok(());
1308            }
1309            DataRoute::Module(DataRouteState::Bound(route)) => {
1310                if frame.header.ty == FrameType::Goodbye {
1311                    if let RouteRelease::Removed(target) = self
1312                        .forwarding
1313                        .release_module_route(ctx.connection_id, channel, epoch)
1314                        .map_err(RouterError::Forwarding)?
1315                    {
1316                        let mut goodbye = frame;
1317                        goodbye.header.channel = target.channel;
1318                        goodbye.header.epoch = target.epoch;
1319                        // A module must never be able to make a frame look
1320                        // daemon-authored, so the origin bit is cleared on
1321                        // every module frame relayed to a client.
1322                        goodbye.header.flags = goodbye.header.flags.without_daemon_origin();
1323                        if let Err(err) = self
1324                            .observe_connection_wait(
1325                                ctx,
1326                                "module_to_client",
1327                                target.sink.send_to_client(goodbye),
1328                            )
1329                            .await
1330                        {
1331                            if !target.close_on_delivery_failure() {
1332                                self.forwarding.warn_frame_drop(
1333                                    target.connection_id,
1334                                    target.channel,
1335                                    target.epoch,
1336                                    "module_to_client",
1337                                    err.diagnosis.cause,
1338                                );
1339                            }
1340                            if target.close_on_delivery_failure()
1341                                && self
1342                                    .forwarding
1343                                    .escalate_client_delivery_failure_diagnosed(
1344                                        target.connection_id,
1345                                        target.channel,
1346                                        target.epoch,
1347                                        CloseReason::new(
1348                                            "route_goodbye_delivery_failed",
1349                                            format!(
1350                                                "failed to enqueue route GOODBYE for client channel {}: {err}",
1351                                                target.channel
1352                                            ),
1353                                        ),
1354                                        UndeliveredFrame {
1355                                            module_id: Some(&route.module_id),
1356                                            sink: &target.sink,
1357                                        },
1358                                        Some(&err.diagnosis),
1359                                    )
1360                                    .map_err(RouterError::Forwarding)?
1361                            {
1362                                self.counters.increment_goodbye_relay_client_failed();
1363                            }
1364                        }
1365                    } else {
1366                        self.forwarding.warn_frame_drop(
1367                            ctx.connection_id,
1368                            channel,
1369                            epoch,
1370                            "module_to_client",
1371                            "missing_binding",
1372                        );
1373                    }
1374                    return Ok(());
1375                }
1376
1377                // A request whose client delivery already ended with
1378                // frame_too_large is still running at the module; its frames
1379                // are dropped here until its terminal releases the credit.
1380                if frame.header.ty != FrameType::Request
1381                    && route
1382                        .flow
1383                        .drop_refused_frame(corr, is_terminal_frame(frame.header.ty))
1384                {
1385                    return Ok(());
1386                }
1387
1388                // Accounting allows an oversized frame to occupy an empty queue
1389                // on other send paths. Refuse it at this splice before admission,
1390                // so the next ordinary reply cannot close a multiplexed client.
1391                let bytes = queued_frame_bytes(&frame);
1392                let limit = route.client_sink.accounting.byte_budget;
1393                if bytes > limit {
1394                    let ty = frame.header.ty;
1395                    let flags = frame.header.flags;
1396                    drop(frame);
1397                    return self
1398                        .refuse_oversized_module_frame(ctx, &route, (ty, flags), corr, bytes)
1399                        .await;
1400                }
1401
1402                // A terminal frame ends the request at the module. Its credit
1403                // is retired once the reply is on the client's queue, or once
1404                // the bounded send has failed and the delivery-failure path
1405                // below owns settlement, but not while the reply still waits
1406                // for room: a restart drain must not report quiescence and
1407                // close the route ahead of the final reply.
1408                let releases_credit = is_terminal_frame(frame.header.ty);
1409                let mut frame = frame;
1410                frame.header.channel = route.client_channel;
1411                frame.header.epoch = route.client_epoch;
1412                // Responses, errors, stream data and ends, and reverse
1413                // requests all pass through here. A module must never be able
1414                // to make a frame look daemon-authored, so the origin bit a
1415                // module may have set is cleared; every other flag bit and
1416                // the body travel unchanged.
1417                frame.header.flags = frame.header.flags.without_daemon_origin();
1418                let delivered = self
1419                    .counters
1420                    .observe_reader_wait(
1421                        || (route.module_id.clone(), principal_label(&route.principal)),
1422                        "module_to_client",
1423                        route.client_sink.send_to_client(frame),
1424                    )
1425                    .await;
1426                // On a failure, the credit is retired only after the escalation
1427                // has marked the client closing, so a drain cannot see the
1428                // request finished before the delivery-failure path owns it.
1429                let escalated = match &delivered {
1430                    Ok(()) => Ok(false),
1431                    Err(err) => self.forwarding.escalate_client_delivery_failure_diagnosed(
1432                        route.client_connection_id,
1433                        route.client_channel,
1434                        route.client_epoch,
1435                        CloseReason::new(
1436                            "module_to_client_delivery_failed",
1437                            format!(
1438                                "failed to enqueue module frame for client channel {} corr {corr}: {err}",
1439                                route.client_channel
1440                            ),
1441                        ),
1442                        UndeliveredFrame {
1443                            module_id: Some(&route.module_id),
1444                            sink: &route.client_sink,
1445                        },
1446                        Some(&err.diagnosis),
1447                    ),
1448                };
1449                if releases_credit {
1450                    route.flow.release_corr(corr);
1451                }
1452                if escalated.map_err(RouterError::Forwarding)? {
1453                    self.counters
1454                        .increment_client_egress_close_delivery_failed();
1455                }
1456                return Ok(());
1457            }
1458            DataRoute::Client(DataRouteState::EpochMismatch) => {
1459                self.forwarding.warn_frame_drop(
1460                    ctx.connection_id,
1461                    channel,
1462                    epoch,
1463                    "client_to_module",
1464                    "stale_epoch",
1465                );
1466                if frame.header.ty == FrameType::Request {
1467                    self.counters.increment_client_frames_dropped_stale_route();
1468                    // Dropped before forwarding; a re-bind retry cannot double-execute this request.
1469                    let err = RouterError::StaleRouteEpoch {
1470                        channel,
1471                        epoch,
1472                        corr,
1473                    };
1474                    if let Some(error_frame) = err.to_error_frame() {
1475                        self.observe_connection_wait(
1476                            ctx,
1477                            "reply_egress",
1478                            ctx.egress.send(error_frame),
1479                        )
1480                        .await?;
1481                    }
1482                }
1483                debug!(
1484                    connection_id = ctx.connection_id.get(),
1485                    channel, epoch, corr, "dropping client frame for stale route epoch"
1486                );
1487                return Ok(());
1488            }
1489            DataRoute::Client(DataRouteState::Reserved) => {
1490                self.forwarding.warn_frame_drop(
1491                    ctx.connection_id,
1492                    channel,
1493                    epoch,
1494                    "client_to_module",
1495                    "missing_binding",
1496                );
1497                if frame.header.ty == FrameType::Request {
1498                    let err = RouterError::UnknownChannel {
1499                        channel,
1500                        epoch,
1501                        corr,
1502                    };
1503                    if let Some(error_frame) = err.to_error_frame() {
1504                        self.observe_connection_wait(
1505                            ctx,
1506                            "reply_egress",
1507                            ctx.egress.send(error_frame),
1508                        )
1509                        .await?;
1510                    }
1511                }
1512                return Ok(());
1513            }
1514            DataRoute::Client(DataRouteState::Bound(route)) => {
1515                if frame.header.ty == FrameType::Goodbye {
1516                    let _ = self
1517                        .control
1518                        .handle_route_goodbye(ctx.connection_id, channel, epoch)?;
1519                    return Ok(());
1520                }
1521                return self.forward_backend.handle_bound(frame, route).await;
1522            }
1523            DataRoute::Client(DataRouteState::Absent) => {}
1524        }
1525
1526        if let Some(backend) = self.backends.get(&channel) {
1527            return backend.handle(ctx.clone(), frame).await.inspect_err(|_| {
1528                self.forwarding.warn_frame_drop(
1529                    ctx.connection_id,
1530                    channel,
1531                    epoch,
1532                    "client_to_backend",
1533                    "endpoint_gone",
1534                );
1535            });
1536        }
1537        self.forwarding.warn_frame_drop(
1538            ctx.connection_id,
1539            channel,
1540            epoch,
1541            "client_to_module",
1542            "unknown_channel",
1543        );
1544        if frame.header.ty == FrameType::Request {
1545            let err = RouterError::UnknownChannel {
1546                channel,
1547                epoch,
1548                corr,
1549            };
1550            if let Some(error_frame) = err.to_error_frame() {
1551                self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(error_frame))
1552                    .await?;
1553            }
1554        }
1555        Ok(())
1556    }
1557
1558    async fn refuse_oversized_module_frame(
1559        &self,
1560        ctx: &RouteCtx,
1561        route: &RouteBinding,
1562        header: (FrameType, Flags),
1563        corr: u64,
1564        bytes: usize,
1565    ) -> Result<(), RouterError> {
1566        let (ty, flags) = header;
1567        let limit = route.client_sink.accounting.byte_budget;
1568        if ty == FrameType::Push {
1569            // Deployed Rust clients cannot decode a new route.closed reason.
1570            // Until that vocabulary can be extended compatibly, an oversized
1571            // unsolicited push still closes the connection, with its cause named.
1572            let diagnosis = ClientDeliveryDiagnosis {
1573                frame_type: ty,
1574                flags,
1575                cause: "frame_too_large",
1576            };
1577            if self
1578                .forwarding
1579                .escalate_client_delivery_failure_diagnosed(
1580                    route.client_connection_id,
1581                    route.client_channel,
1582                    route.client_epoch,
1583                    CloseReason::new(
1584                        error_codes::FRAME_TOO_LARGE,
1585                        format!(
1586                            "oversized push: size={bytes} limit={limit} (header plus body bytes)"
1587                        ),
1588                    ),
1589                    UndeliveredFrame {
1590                        module_id: Some(&route.module_id),
1591                        sink: &route.client_sink,
1592                    },
1593                    Some(&diagnosis),
1594                )
1595                .map_err(RouterError::Forwarding)?
1596            {
1597                self.counters
1598                    .increment_client_egress_close_delivery_failed();
1599            }
1600            return Ok(());
1601        }
1602
1603        warn!(
1604            connection_id = route.client_connection_id.get(),
1605            module_id = %route.module_id,
1606            client_principal = %principal_label(&route.principal),
1607            client_channel = route.client_channel,
1608            frame_type = ?ty,
1609            frame_bytes = bytes,
1610            byte_limit = limit,
1611            "refusing oversized module-to-client frame with ERROR frame_too_large"
1612        );
1613        if ty == FrameType::Request {
1614            // A reverse request belongs to the module, not to a waiting client.
1615            // Answer its sender without forwarding any part of it to the client.
1616            let error = frame_too_large_error(
1617                route.module_channel,
1618                route.module_epoch,
1619                corr,
1620                bytes,
1621                limit,
1622            )?;
1623            self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(error))
1624                .await?;
1625        } else {
1626            let terminal = is_terminal_frame(ty);
1627            if !terminal {
1628                // A refused stream chunk ends the request for the client only:
1629                // the module is still running it, so it keeps its credit, its
1630                // later frames are dropped, and the module is asked to stop.
1631                route.flow.refuse_client_delivery(corr);
1632                self.cancel_refused_module_request(route, corr);
1633            }
1634            let error = frame_too_large_error(
1635                route.client_channel,
1636                route.client_epoch,
1637                corr,
1638                bytes,
1639                limit,
1640            )?;
1641            // The replacement shares the reply's bounded burst grace, so a
1642            // stopped client cannot indefinitely stall the module frame reader.
1643            let delivered = self
1644                .counters
1645                .observe_reader_wait(
1646                    || (route.module_id.clone(), principal_label(&route.principal)),
1647                    "module_to_client",
1648                    route.client_sink.send_to_client(error),
1649                )
1650                .await;
1651            let escalated = match &delivered {
1652                Ok(()) => Ok(false),
1653                Err(err) => self.forwarding.escalate_client_delivery_failure_diagnosed(
1654                    route.client_connection_id,
1655                    route.client_channel,
1656                    route.client_epoch,
1657                    CloseReason::new(
1658                        "module_to_client_delivery_failed",
1659                        format!(
1660                            "failed to enqueue frame_too_large for client channel {} corr {corr}: {err}",
1661                            route.client_channel
1662                        ),
1663                    ),
1664                    UndeliveredFrame {
1665                        module_id: Some(&route.module_id),
1666                        sink: &route.client_sink,
1667                    },
1668                    Some(&err.diagnosis),
1669                ),
1670            };
1671            if terminal {
1672                // A refused terminal also ended the request at the module. Its
1673                // credit is retired once the replacement is queued, or once
1674                // its send has failed and the escalation above owns it, as for
1675                // a delivered terminal.
1676                route.flow.release_corr(corr);
1677            }
1678            if escalated.map_err(RouterError::Forwarding)? {
1679                self.counters
1680                    .increment_client_egress_close_delivery_failed();
1681            }
1682        }
1683        Ok(())
1684    }
1685
1686    /// Ask the module to stop a request whose client delivery was refused. The
1687    /// CANCEL is best effort and never waits: the module's own reader must not
1688    /// stall on that module's egress, and the request keeps its credit either
1689    /// way until the module's terminal arrives.
1690    fn cancel_refused_module_request(&self, route: &RouteBinding, corr: u64) {
1691        let cancel = Frame::build_with_version(
1692            route.module_negotiated_ver,
1693            FrameType::Cancel,
1694            Flags::new(false, Priority::Passive, false),
1695            route.module_channel,
1696            route.module_epoch,
1697            corr,
1698            Vec::new(),
1699        );
1700        let sent = cancel.map_err(|err| err.to_string()).and_then(|cancel| {
1701            route
1702                .module_sink
1703                .try_send(cancel)
1704                .map_err(|err| err.to_string())
1705        });
1706        if let Err(error) = sent {
1707            warn!(
1708                module_id = %route.module_id,
1709                module_channel = route.module_channel,
1710                corr,
1711                %error,
1712                "could not send CANCEL for a request whose stream chunk was refused as too large"
1713            );
1714        }
1715    }
1716}
1717
1718impl Default for Router {
1719    fn default() -> Self {
1720        Self::with_default_self_handler()
1721    }
1722}
1723
1724/// Connection-scoped cleanup guard returned by [`Router::begin_connection`].
1725#[must_use]
1726pub struct RouterConnection {
1727    id: ConnectionId,
1728    control_handler: Arc<ControlHandler>,
1729    forwarding: Arc<ForwardingTable>,
1730    close_receiver: Option<ConnectionCloseReceiver>,
1731    orphan_goodbyes: Arc<OrphanGoodbyeLimiter>,
1732}
1733
1734impl RouterConnection {
1735    pub fn id(&self) -> ConnectionId {
1736        self.id
1737    }
1738
1739    pub(crate) fn take_close_receiver(&mut self) -> ConnectionCloseReceiver {
1740        self.close_receiver
1741            .take()
1742            .expect("connection close receiver can only be taken once")
1743    }
1744}
1745
1746impl Drop for RouterConnection {
1747    fn drop(&mut self) {
1748        self.orphan_goodbyes.forget_connection(self.id);
1749        // GOODBYE (explicit) and connection-drop cleanup both call the same
1750        // idempotent deregistration path.
1751        let _ = self.control_handler.cleanup_connection(self.id);
1752        // The read loop and its tasks have ended, but the writer can still
1753        // drain. Keep the connection-to-launch association until pending relays
1754        // and routes are gone.
1755        self.forwarding.unregister_connection_close(self.id);
1756    }
1757}
1758
1759/// Minimal in-memory backend used by tests and early wiring: it emits a
1760/// `RESPONSE` on the same channel/correlation id with the exact same body bytes.
1761#[derive(Debug, Default, Clone, Copy)]
1762pub struct EchoBackend;
1763
1764impl EchoBackend {
1765    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
1766        let response = Frame::build_with_version(
1767            frame.header.ver,
1768            FrameType::Response,
1769            frame.header.flags,
1770            frame.header.channel,
1771            frame.header.epoch,
1772            frame.header.corr,
1773            frame.body,
1774        )
1775        .map_err(RouterError::FrameBuild)?;
1776        ctx.egress.send(response).await
1777    }
1778}
1779
1780/// Data-plane backend that splices client frames to the module connection bound at attach time.
1781#[derive(Debug, Clone)]
1782pub struct ForwardBackend {
1783    forwarding: Arc<ForwardingTable>,
1784}
1785
1786impl ForwardBackend {
1787    pub fn new(forwarding: Arc<ForwardingTable>) -> Self {
1788        Self { forwarding }
1789    }
1790
1791    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
1792        let channel = frame.header.channel;
1793        let corr = frame.header.corr;
1794        let route = match self
1795            .forwarding
1796            .lookup_data_route(ctx.connection_id, channel, frame.header.epoch)
1797            .map_err(RouterError::Forwarding)?
1798        {
1799            DataRoute::Client(DataRouteState::Bound(route)) => route,
1800            DataRoute::Client(_) | DataRoute::Module(_) => {
1801                self.forwarding.warn_frame_drop(
1802                    ctx.connection_id,
1803                    channel,
1804                    frame.header.epoch,
1805                    "client_to_module",
1806                    "missing_binding",
1807                );
1808                return Err(RouterError::UnknownChannel {
1809                    channel,
1810                    epoch: frame.header.epoch,
1811                    corr,
1812                });
1813            }
1814        };
1815        self.handle_bound(frame, route).await
1816    }
1817
1818    pub(crate) async fn handle_bound(
1819        &self,
1820        frame: Frame,
1821        route: Arc<RouteBinding>,
1822    ) -> Result<(), RouterError> {
1823        let channel = frame.header.channel;
1824        let corr = frame.header.corr;
1825        let frame_type = frame.header.ty;
1826
1827        // CANCEL and other non-REQUEST frames bypass the request-credit window;
1828        // the original request's credit is freed only by the module's terminal frame.
1829        let acquired_credit = frame_type == FrameType::Request;
1830        if acquired_credit && route.flow.busy_refusals() {
1831            use crate::forwarding::RequestAdmission;
1832            match self
1833                .forwarding
1834                .try_admit_request(
1835                    &route,
1836                    frame.header.epoch,
1837                    corr,
1838                    frame.header.flags.is_subscription(),
1839                )
1840                .map_err(RouterError::Forwarding)?
1841            {
1842                RequestAdmission::Admitted => {}
1843                RequestAdmission::Busy(detail) => {
1844                    let principal = principal_label(&route.principal);
1845                    let counters = self.forwarding.counters_ref();
1846                    counters.increment_route_busy(&route.module_id, &principal);
1847                    if route.flow.should_warn_busy() {
1848                        warn!(module_id = %route.module_id, client_principal = %principal, client_channel = channel,
1849                            route_epoch = route.client_epoch, ?detail, "request refused: route_busy");
1850                    }
1851                    let error = RouterError::RouteBusy {
1852                        channel,
1853                        epoch: frame.header.epoch,
1854                        corr,
1855                        detail: Box::new(detail),
1856                    };
1857                    let refusal = error
1858                        .to_error_frame()
1859                        .expect("route_busy is a serializable wire error");
1860                    counters
1861                        .observe_reader_wait(
1862                            || (route.module_id.clone(), principal),
1863                            "route_busy_egress",
1864                            route.client_sink.send(refusal),
1865                        )
1866                        .await?;
1867                    return Ok(());
1868                }
1869                RequestAdmission::ModuleReloading => {
1870                    return Err(RouterError::route_error_with_epoch(
1871                        channel,
1872                        frame.header.epoch,
1873                        corr,
1874                        error_codes::MODULE_RELOADING,
1875                        format!("module endpoint for route channel {channel} is reloading"),
1876                    ));
1877                }
1878                RequestAdmission::Stale => {
1879                    return Err(RouterError::StaleRouteEpoch {
1880                        channel,
1881                        epoch: frame.header.epoch,
1882                        corr,
1883                    })
1884                }
1885            }
1886        } else if !route.flow.busy_refusals() {
1887            // A legacy route queues a request that must wait for credit
1888            // instead of parking the connection reader on it.
1889            return self.offer_to_legacy_route(frame, route).await;
1890        }
1891        self.forward_to_module(frame, &route, acquired_credit).await
1892    }
1893
1894    /// Put a client frame on the module's queue. A frame that holds a request
1895    /// credit (`credited`) gives it back if it cannot be queued.
1896    async fn forward_to_module(
1897        &self,
1898        frame: Frame,
1899        route: &RouteBinding,
1900        credited: bool,
1901    ) -> Result<(), RouterError> {
1902        let channel = frame.header.channel;
1903        let corr = frame.header.corr;
1904        let mut frame = frame;
1905        frame.header.channel = route.module_channel;
1906        frame.header.epoch = route.module_epoch;
1907        // The origin bit is the daemon's own signal to clients. A client
1908        // frame carrying it must not reach a module appearing daemon-authored,
1909        // so it is cleared here; every other flag bit travels unchanged.
1910        frame.header.flags = frame.header.flags.without_daemon_origin();
1911        let counters = self.forwarding.counters_ref();
1912        let result = counters
1913            .observe_reader_wait(
1914                || (route.module_id.clone(), principal_label(&route.principal)),
1915                "module_queue",
1916                route.module_sink.send(frame),
1917            )
1918            .await
1919            .map_err(|err| {
1920                self.forwarding.warn_frame_drop(
1921                    route.client_connection_id,
1922                    channel,
1923                    route.client_epoch,
1924                    "client_to_module",
1925                    "endpoint_gone",
1926                );
1927                RouterError::backend_with_epoch(channel, route.client_epoch, corr, err.to_string())
1928            });
1929        if credited && result.is_err() {
1930            route.flow.release_corr(corr);
1931        }
1932        result
1933    }
1934}
1935
1936#[path = "router_legacy_waiting.rs"]
1937mod legacy_waiting;
1938
1939fn is_terminal_frame(frame_type: FrameType) -> bool {
1940    matches!(
1941        frame_type,
1942        FrameType::Response | FrameType::Error | FrameType::StreamEnd
1943    )
1944}
1945
1946/// Typed router errors. Routable failures can be translated to canonical JSON
1947/// `ERROR` frames with [`RouterError::to_error_frame`].
1948#[derive(Debug, Clone, PartialEq, Eq)]
1949pub enum RouterError {
1950    ReservedChannelZero,
1951    DuplicateChannel {
1952        channel: u16,
1953    },
1954    UnknownChannel {
1955        channel: u16,
1956        epoch: u32,
1957        corr: u64,
1958    },
1959    StaleRouteEpoch {
1960        channel: u16,
1961        epoch: u32,
1962        corr: u64,
1963    },
1964    RouteBusy {
1965        channel: u16,
1966        epoch: u32,
1967        corr: u64,
1968        detail: Box<subc_protocol::RouteBusyDetail>,
1969    },
1970    Backend {
1971        channel: u16,
1972        epoch: u32,
1973        corr: u64,
1974        message: String,
1975    },
1976    RouteError {
1977        channel: u16,
1978        epoch: u32,
1979        corr: u64,
1980        code: String,
1981        message: String,
1982    },
1983    FrameBuild(FrameBuildError),
1984    Forwarding(ForwardingError),
1985}
1986
1987impl RouterError {
1988    pub fn backend(channel: u16, corr: u64, message: impl Into<String>) -> Self {
1989        Self::backend_with_epoch(channel, 0, corr, message)
1990    }
1991
1992    pub fn backend_with_epoch(
1993        channel: u16,
1994        epoch: u32,
1995        corr: u64,
1996        message: impl Into<String>,
1997    ) -> Self {
1998        Self::Backend {
1999            channel,
2000            epoch,
2001            corr,
2002            message: message.into(),
2003        }
2004    }
2005
2006    pub fn route_error(
2007        channel: u16,
2008        corr: u64,
2009        code: impl Into<String>,
2010        message: impl Into<String>,
2011    ) -> Self {
2012        Self::route_error_with_epoch(channel, 0, corr, code, message)
2013    }
2014
2015    pub fn route_error_with_epoch(
2016        channel: u16,
2017        epoch: u32,
2018        corr: u64,
2019        code: impl Into<String>,
2020        message: impl Into<String>,
2021    ) -> Self {
2022        Self::RouteError {
2023            channel,
2024            epoch,
2025            corr,
2026            code: code.into(),
2027            message: message.into(),
2028        }
2029    }
2030
2031    /// Translate route failures that belong on the wire into an `ERROR` frame.
2032    pub fn to_error_frame(&self) -> Option<Frame> {
2033        match self {
2034            Self::RouteBusy {
2035                channel,
2036                epoch,
2037                corr,
2038                detail,
2039            } => {
2040                let body = serde_json::to_vec(&ErrorBody {
2041                    code: error_codes::ROUTE_BUSY.into(),
2042                    message: "route has no free request or watch credit; retry on the same route"
2043                        .into(),
2044                    detail: Some(serde_json::to_value(detail).ok()?),
2045                })
2046                .ok()?;
2047                Frame::build(
2048                    FrameType::Error,
2049                    daemon_error_flags(),
2050                    *channel,
2051                    *epoch,
2052                    *corr,
2053                    body,
2054                )
2055                .ok()
2056            }
2057            Self::UnknownChannel {
2058                channel,
2059                epoch,
2060                corr,
2061            } => error_frame(
2062                *channel,
2063                *epoch,
2064                *corr,
2065                error_codes::UNKNOWN_CHANNEL,
2066                format!("unknown channel {channel}"),
2067            ),
2068            Self::StaleRouteEpoch {
2069                channel,
2070                epoch,
2071                corr,
2072            } => error_frame(
2073                *channel,
2074                *epoch,
2075                *corr,
2076                error_codes::STALE_ROUTE_EPOCH,
2077                format!("stale route epoch for channel {channel}"),
2078            ),
2079            Self::Backend {
2080                channel,
2081                epoch,
2082                corr,
2083                message,
2084            } => error_frame(*channel, *epoch, *corr, "backend_error", message.clone()),
2085            Self::RouteError {
2086                channel,
2087                epoch,
2088                corr,
2089                code,
2090                message,
2091            } => error_frame(*channel, *epoch, *corr, code, message.clone()),
2092            Self::ReservedChannelZero
2093            | Self::DuplicateChannel { .. }
2094            | Self::FrameBuild(_)
2095            | Self::Forwarding(_) => None,
2096        }
2097    }
2098}
2099
2100/// Flags for an ERROR frame the daemon authors itself.
2101///
2102/// Bit 6 (`FLAG_DAEMON_ORIGIN`) tells the client the daemon wrote this
2103/// error, never a module. What a code then proves is per code: on a bound
2104/// route the daemon writes `module_reloading`, `unknown_channel` and
2105/// `stale_route_epoch` only before forwarding, so with the bit they mean the
2106/// request was not delivered, while `frame_too_large` replaces a reply the
2107/// module already produced. Every daemon-authored ERROR goes through here;
2108/// frames a module sent keep their own flags with the bit cleared at the
2109/// splice.
2110/// Nothing else about the flags differs: passive priority, not binary, not last.
2111pub(crate) fn daemon_error_flags() -> Flags {
2112    Flags::new(false, Priority::Passive, false).with_daemon_origin()
2113}
2114
2115fn error_frame(channel: u16, epoch: u32, corr: u64, code: &str, message: String) -> Option<Frame> {
2116    let body = serde_json::to_vec(&ErrorBody {
2117        code: code.to_string(),
2118        message,
2119        detail: None,
2120    })
2121    .ok()?;
2122
2123    Frame::build(
2124        FrameType::Error,
2125        daemon_error_flags(),
2126        channel,
2127        epoch,
2128        corr,
2129        body,
2130    )
2131    .ok()
2132}
2133
2134fn frame_too_large_error(
2135    channel: u16,
2136    epoch: u32,
2137    corr: u64,
2138    bytes: usize,
2139    limit: usize,
2140) -> Result<Frame, RouterError> {
2141    let body = serde_json::to_vec(&ErrorBody {
2142        code: error_codes::FRAME_TOO_LARGE.to_string(),
2143        message: format!(
2144            "module frame of {bytes} bytes exceeds client egress limit of {limit} bytes"
2145        ),
2146        detail: Some(serde_json::json!({ "frame_bytes": bytes, "byte_limit": limit })),
2147    })
2148    .expect("serializing a frame size error");
2149    Frame::build(
2150        FrameType::Error,
2151        daemon_error_flags(),
2152        channel,
2153        epoch,
2154        corr,
2155        body,
2156    )
2157    .map_err(RouterError::FrameBuild)
2158}
2159
2160impl fmt::Display for RouterError {
2161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2162        match self {
2163            Self::ReservedChannelZero => write!(f, "channel 0 is reserved for subc"),
2164            Self::DuplicateChannel { channel } => {
2165                write!(f, "backend already registered for channel {channel}")
2166            }
2167            Self::UnknownChannel { channel, corr, .. } => {
2168                write!(f, "unknown channel {channel} for corr {corr}")
2169            }
2170            Self::StaleRouteEpoch { channel, corr, .. } => {
2171                write!(f, "stale route epoch for channel {channel} corr {corr}")
2172            }
2173            Self::RouteBusy { channel, corr, .. } => {
2174                write!(f, "route busy on channel {channel} corr {corr}")
2175            }
2176            Self::Backend {
2177                channel,
2178                corr,
2179                message,
2180                ..
2181            } => write!(
2182                f,
2183                "backend error on channel {channel} corr {corr}: {message}"
2184            ),
2185            Self::RouteError {
2186                channel,
2187                corr,
2188                code,
2189                message,
2190                ..
2191            } => write!(
2192                f,
2193                "route error {code} on channel {channel} corr {corr}: {message}"
2194            ),
2195            Self::FrameBuild(err) => write!(f, "failed to build routed frame: {err}"),
2196            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2197        }
2198    }
2199}
2200
2201impl Error for RouterError {
2202    fn source(&self) -> Option<&(dyn Error + 'static)> {
2203        match self {
2204            Self::FrameBuild(err) => Some(err),
2205            Self::Forwarding(err) => Some(err),
2206            Self::ReservedChannelZero
2207            | Self::DuplicateChannel { .. }
2208            | Self::UnknownChannel { .. }
2209            | Self::StaleRouteEpoch { .. }
2210            | Self::RouteBusy { .. }
2211            | Self::Backend { .. }
2212            | Self::RouteError { .. } => None,
2213        }
2214    }
2215}
2216
2217#[cfg(test)]
2218mod tests {
2219    include!("route_busy_router_tests.rs");
2220    use super::*;
2221    use crate::{
2222        forwarding::RouteBindRelayOutcome,
2223        supervise::{ModuleSpec, RestartPolicy, Supervisor, SupervisorHandle},
2224        ControlHandler, Registry,
2225    };
2226    use std::{
2227        sync::{mpsc as std_mpsc, Arc},
2228        time::Duration,
2229    };
2230    use subc_control::ModuleProtocol;
2231    use subc_protocol::{manifest::Concurrency, ErrorBody, Flags, FrameType, Priority};
2232    use tokio::sync::mpsc;
2233
2234    pub(crate) use crate::router::test_log::{captured_logs, log_capture};
2235
2236    fn logged_millis(logs: &str, field: &str) -> u64 {
2237        logs.split_whitespace()
2238            .find_map(|part| part.strip_prefix(field))
2239            .and_then(|value| value.parse().ok())
2240            .unwrap_or_else(|| panic!("missing numeric {field} in logs: {logs}"))
2241    }
2242
2243    fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
2244        Frame::build(
2245            FrameType::Request,
2246            Flags::new(true, Priority::Interactive, false),
2247            channel,
2248            0,
2249            corr,
2250            body.to_vec(),
2251        )
2252        .unwrap()
2253    }
2254
2255    fn ping(corr: u64) -> Frame {
2256        Frame::build(
2257            FrameType::Ping,
2258            Flags::new(false, Priority::Passive, false),
2259            0,
2260            0,
2261            corr,
2262            Vec::new(),
2263        )
2264        .unwrap()
2265    }
2266
2267    fn route_ctx() -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
2268        let (tx, rx) = mpsc::channel(8);
2269        (
2270            RouteCtx {
2271                connection_id: ConnectionId::LOCAL,
2272                egress: FrameSink::new(tx),
2273            },
2274            rx,
2275        )
2276    }
2277
2278    #[tokio::test]
2279    async fn retirement_egress_all_send_paths_drop_after_fence() {
2280        let (tx, mut rx) = mpsc::channel(8);
2281        let sink = FrameSink::new(tx);
2282        let reserved = sink.reserve_owned().await.unwrap();
2283        let immediate = sink.try_reserve_owned().unwrap();
2284        sink.terminate_egress();
2285        assert!(reserved.send(ping(1)));
2286        assert!(immediate.send(ping(2)));
2287        sink.send(ping(3)).await.unwrap();
2288        sink.try_send(ping(4)).unwrap();
2289        sink.send_to_client(ping(5)).await.unwrap();
2290        let queued = AtomicBool::new(false);
2291        assert!(sink
2292            .send_flushed_notifying_enqueue(ping(6), || queued.store(true, Ordering::Relaxed))
2293            .await
2294            .is_err());
2295        assert!(!queued.load(Ordering::Relaxed));
2296        assert!(sink.send_flushed(ping(7)).await.is_err());
2297        assert!(sink.reserve_owned().await.is_err());
2298        assert!(sink.try_reserve_owned().is_err());
2299        assert!(
2300            rx.try_recv().is_err(),
2301            "retired frames must not enter any writer queue"
2302        );
2303        assert_eq!(sink.backlog().queued_frames, 0);
2304        assert_eq!(sink.backlog().queued_bytes, 0);
2305    }
2306
2307    #[tokio::test]
2308    async fn retirement_egress_reservation_rechecks_after_slot_acquisition() {
2309        let (tx, mut rx) = mpsc::channel(1);
2310        let sink = FrameSink::new(tx);
2311        // Choose retirement after reserve returns its slot, not while waiting
2312        // on egress_stopped, so the final atomic recheck is exercised.
2313        sink.accounting
2314            .retire_after_reserve
2315            .store(true, Ordering::Relaxed);
2316        assert!(
2317            sink.reserve_owned().await.is_err(),
2318            "a slot acquired before retirement must not escape as a live reservation"
2319        );
2320        assert_eq!(
2321            sink.tx.capacity(),
2322            1,
2323            "refusal must release the reserved slot"
2324        );
2325        assert!(rx.try_recv().is_err());
2326    }
2327
2328    #[tokio::test]
2329    async fn retirement_egress_pending_budget_and_slot_sends_stop() {
2330        for budget in [1, usize::MAX] {
2331            let (tx, mut rx) = mpsc::channel(1);
2332            let sink = FrameSink::with_byte_budget(tx, budget);
2333            sink.try_send(ping(1)).unwrap();
2334            let sending = sink.send(ping(2));
2335            tokio::pin!(sending);
2336            assert!(poll_once(sending.as_mut()).await.is_pending());
2337            sink.terminate_egress();
2338            tokio::time::timeout(Duration::from_secs(2), sending)
2339                .await
2340                .unwrap()
2341                .unwrap();
2342            drop(rx.try_recv().unwrap());
2343            assert!(
2344                rx.try_recv().is_err(),
2345                "a send parked before retirement must not enqueue afterward"
2346            );
2347            assert_eq!(sink.backlog().queued_bytes, 0);
2348        }
2349    }
2350
2351    #[tokio::test]
2352    async fn retirement_egress_pending_flush_and_reservation_stop() {
2353        let (tx, mut rx) = mpsc::channel(1);
2354        let sink = FrameSink::new(tx);
2355        sink.try_send(ping(1)).unwrap();
2356        let queued = AtomicBool::new(false);
2357        let sending =
2358            sink.send_flushed_notifying_enqueue(ping(2), || queued.store(true, Ordering::Relaxed));
2359        let reserving = sink.reserve_owned();
2360        tokio::pin!(sending, reserving);
2361        assert!(poll_once(sending.as_mut()).await.is_pending());
2362        assert!(poll_once(reserving.as_mut()).await.is_pending());
2363        sink.terminate_egress();
2364        assert!(tokio::time::timeout(Duration::from_secs(2), sending)
2365            .await
2366            .unwrap()
2367            .is_err());
2368        assert!(tokio::time::timeout(Duration::from_secs(2), reserving)
2369            .await
2370            .unwrap()
2371            .is_err());
2372        assert!(!queued.load(Ordering::Relaxed));
2373        drop(rx.try_recv().unwrap());
2374        assert!(rx.try_recv().is_err());
2375        assert_eq!(sink.backlog().queued_bytes, 0);
2376    }
2377
2378    #[tokio::test]
2379    async fn echo_backend_returns_response_with_byte_identical_body() {
2380        let mut router = Router::with_default_self_handler();
2381        router.register_backend(7, EchoBackend).unwrap();
2382        let (ctx, mut rx) = route_ctx();
2383        let body = b"{not parsed}\0\xff";
2384
2385        router
2386            .route_for_connection(&ctx, request(7, 123, body))
2387            .await
2388            .unwrap();
2389        let response = rx.recv().await.unwrap();
2390
2391        assert_eq!(response.header.ty, FrameType::Response);
2392        assert_eq!(response.header.channel, 7);
2393        assert_eq!(response.header.corr, 123);
2394        assert_eq!(response.body, body);
2395        assert!(rx.try_recv().is_err());
2396    }
2397
2398    #[tokio::test]
2399    async fn unknown_channel_emits_canonical_error_frame() {
2400        let router = Router::with_default_self_handler();
2401        let (ctx, mut rx) = route_ctx();
2402
2403        router
2404            .route_for_connection(&ctx, request(99, 5, b"payload"))
2405            .await
2406            .unwrap();
2407        let error_frame = rx.recv().await.unwrap();
2408
2409        assert_eq!(error_frame.header.ty, FrameType::Error);
2410        assert_eq!(error_frame.header.channel, 99);
2411        assert_eq!(error_frame.header.corr, 5);
2412        let body: ErrorBody = serde_json::from_slice(&error_frame.body).unwrap();
2413        assert_eq!(body.code, "unknown_channel");
2414        assert_eq!(body.message, "unknown channel 99");
2415    }
2416
2417    /// Every ERROR the daemon authors carries the daemon-origin bit, so a
2418    /// client can tell a daemon refusal from a module's reply. Both the
2419    /// unknown-channel and the stale-epoch errors below are received on the
2420    /// client's own egress, not merely built.
2421    #[tokio::test]
2422    async fn daemon_authored_data_plane_errors_carry_daemon_origin() {
2423        let router = Router::with_default_self_handler();
2424        let (ctx, mut rx) = route_ctx();
2425        router
2426            .route_for_connection(&ctx, request(99, 5, b"payload"))
2427            .await
2428            .unwrap();
2429        let unknown = rx.recv().await.unwrap();
2430        assert_eq!(unknown.header.ty, FrameType::Error);
2431        let body: ErrorBody = serde_json::from_slice(&unknown.body).unwrap();
2432        assert_eq!(body.code, "unknown_channel");
2433        assert!(
2434            unknown.header.flags.is_daemon_origin(),
2435            "unknown_channel must carry daemon origin: {:?}",
2436            unknown.header.flags
2437        );
2438
2439        let (
2440            router,
2441            _forwarding,
2442            client_ctx,
2443            mut client_rx,
2444            _module_ctx,
2445            _module_egress_rx,
2446            _module_rx,
2447            pending,
2448        ) = dynamic_route_fixture(true);
2449        let _ = client_rx.recv().await;
2450        router
2451            .route_for_connection(
2452                &client_ctx,
2453                route_frame(
2454                    FrameType::Request,
2455                    pending.client_channel,
2456                    pending.client_epoch + 1,
2457                    702,
2458                ),
2459            )
2460            .await
2461            .unwrap();
2462        let stale = client_rx.recv().await.unwrap();
2463        assert_eq!(stale.header.ty, FrameType::Error);
2464        let body: ErrorBody = serde_json::from_slice(&stale.body).unwrap();
2465        assert_eq!(body.code, "stale_route_epoch");
2466        assert!(
2467            stale.header.flags.is_daemon_origin(),
2468            "stale_route_epoch must carry daemon origin: {:?}",
2469            stale.header.flags
2470        );
2471    }
2472
2473    /// A module ERROR that spoofs a daemon code with the daemon-origin bit
2474    /// set must reach the client with the bit cleared and the body
2475    /// byte-identical: the bit means the daemon wrote the frame, and a module
2476    /// must never be able to claim that.
2477    #[tokio::test]
2478    async fn module_error_with_daemon_bit_is_stripped_before_client_delivery() {
2479        let (
2480            router,
2481            _forwarding,
2482            client_ctx,
2483            mut client_rx,
2484            module_ctx,
2485            _module_egress_rx,
2486            mut module_rx,
2487            pending,
2488        ) = dynamic_route_fixture(true);
2489        let _ = client_rx.recv().await;
2490        // Open flow credit the way a real request would, so the terminal
2491        // error exercises the credit-release path too.
2492        router
2493            .route_for_connection(
2494                &client_ctx,
2495                route_frame(
2496                    FrameType::Request,
2497                    pending.client_channel,
2498                    pending.client_epoch,
2499                    701,
2500                ),
2501            )
2502            .await
2503            .unwrap();
2504        let _ = module_rx.recv().await;
2505
2506        let body = serde_json::to_vec(&ErrorBody::new("module_reloading", "try again")).unwrap();
2507        let spoof = Frame::build(
2508            FrameType::Error,
2509            Flags::new(false, Priority::Interactive, false).with_daemon_origin(),
2510            pending.module_channel,
2511            pending.module_epoch,
2512            701,
2513            body.clone(),
2514        )
2515        .unwrap();
2516        router
2517            .route_for_connection(&module_ctx, spoof)
2518            .await
2519            .unwrap();
2520        let delivered = client_rx.recv().await.unwrap();
2521        assert_eq!(delivered.header.ty, FrameType::Error);
2522        assert_eq!(delivered.header.channel, pending.client_channel);
2523        assert_eq!(delivered.header.epoch, pending.client_epoch);
2524        assert_eq!(delivered.header.corr, 701);
2525        assert!(
2526            !delivered.header.flags.is_daemon_origin(),
2527            "module-set daemon origin must be cleared: {:?}",
2528            delivered.header.flags
2529        );
2530        assert_eq!(delivered.body, body, "the body travels byte-identical");
2531    }
2532
2533    /// Clearing the origin bit strips exactly that bit: priority, LAST and
2534    /// subscription survive the splice unchanged.
2535    #[tokio::test]
2536    async fn module_response_with_daemon_bit_is_stripped_preserving_other_flags() {
2537        use subc_protocol::FLAG_SUBSCRIPTION;
2538        let (
2539            router,
2540            _forwarding,
2541            client_ctx,
2542            mut client_rx,
2543            module_ctx,
2544            _module_egress_rx,
2545            mut module_rx,
2546            pending,
2547        ) = dynamic_route_fixture(true);
2548        let _ = client_rx.recv().await;
2549        router
2550            .route_for_connection(
2551                &client_ctx,
2552                route_frame(
2553                    FrameType::Request,
2554                    pending.client_channel,
2555                    pending.client_epoch,
2556                    701,
2557                ),
2558            )
2559            .await
2560            .unwrap();
2561        let _ = module_rx.recv().await;
2562
2563        let sent_flags = Flags(
2564            Flags::new(true, Priority::Background, true).0
2565                | FLAG_SUBSCRIPTION
2566                | subc_protocol::FLAG_DAEMON_ORIGIN,
2567        );
2568        assert!(sent_flags.is_daemon_origin());
2569        let response = Frame::build(
2570            FrameType::Response,
2571            sent_flags,
2572            pending.module_channel,
2573            pending.module_epoch,
2574            701,
2575            b"route-body".to_vec(),
2576        )
2577        .unwrap();
2578        router
2579            .route_for_connection(&module_ctx, response)
2580            .await
2581            .unwrap();
2582        let delivered = client_rx.recv().await.unwrap();
2583        assert_eq!(delivered.header.ty, FrameType::Response);
2584        assert!(
2585            !delivered.header.flags.is_daemon_origin(),
2586            "module-set daemon origin must be cleared: {:?}",
2587            delivered.header.flags
2588        );
2589        assert!(
2590            delivered.header.flags.is_binary(),
2591            "binary flag must survive: {:?}",
2592            delivered.header.flags
2593        );
2594        assert!(
2595            delivered.header.flags.is_last(),
2596            "LAST flag must survive: {:?}",
2597            delivered.header.flags
2598        );
2599        assert!(
2600            delivered.header.flags.is_subscription(),
2601            "subscription flag must survive: {:?}",
2602            delivered.header.flags
2603        );
2604        assert_eq!(
2605            delivered.header.flags.priority(),
2606            Some(Priority::Background),
2607            "priority must survive"
2608        );
2609    }
2610
2611    /// A client frame carrying the origin bit must not reach the module
2612    /// looking daemon-authored either: the splice clears it symmetrically.
2613    #[tokio::test]
2614    async fn client_frame_with_daemon_bit_is_stripped_before_module_delivery() {
2615        let (
2616            router,
2617            _forwarding,
2618            client_ctx,
2619            mut client_rx,
2620            _module_ctx,
2621            _module_egress_rx,
2622            mut module_rx,
2623            pending,
2624        ) = dynamic_route_fixture(true);
2625        let _ = client_rx.recv().await;
2626        let spoof = Frame::build(
2627            FrameType::Request,
2628            Flags::new(false, Priority::Interactive, false).with_daemon_origin(),
2629            pending.client_channel,
2630            pending.client_epoch,
2631            701,
2632            b"route-body".to_vec(),
2633        )
2634        .unwrap();
2635        router
2636            .route_for_connection(&client_ctx, spoof)
2637            .await
2638            .unwrap();
2639        let delivered = module_rx.recv().await.unwrap();
2640        assert_eq!(delivered.header.ty, FrameType::Request);
2641        assert!(
2642            !delivered.header.flags.is_daemon_origin(),
2643            "client-set daemon origin must be cleared: {:?}",
2644            delivered.header.flags
2645        );
2646    }
2647
2648    #[tokio::test]
2649    async fn channel_zero_uses_control_handler_not_backend_registry() {
2650        let mut router = Router::with_default_self_handler();
2651        router.register_backend(1, EchoBackend).unwrap();
2652        let (ctx, mut rx) = route_ctx();
2653
2654        router.route_for_connection(&ctx, ping(77)).await.unwrap();
2655        let response = rx.recv().await.unwrap();
2656
2657        assert_eq!(response.header.ty, FrameType::Pong);
2658        assert_eq!(response.header.channel, 0);
2659        assert_eq!(response.header.corr, 77);
2660        assert!(response.body.is_empty());
2661    }
2662
2663    #[tokio::test]
2664    async fn slow_control_dispatch_logs_decoded_op_and_elapsed_time() {
2665        let control = Arc::new(
2666            ControlHandler::new(Arc::new(Registry::default()))
2667                .with_control_dispatch_delay(Duration::from_millis(1050)),
2668        );
2669        let router = Router::with_control_handler(control);
2670        let (ctx, mut rx) = route_ctx();
2671        let (output, guard) = log_capture(tracing::Level::WARN);
2672
2673        router
2674            .route_for_connection(&ctx, request(0, 41, br#"{"op":"server.describe"}"#))
2675            .await
2676            .expect("slow request routes");
2677        assert!(rx.recv().await.is_some(), "request receives a response");
2678        drop(guard);
2679
2680        let logs = captured_logs(&output);
2681        assert!(logs.contains("slow control dispatch"));
2682        assert!(logs.contains("op=server.describe"));
2683        assert!(logs.contains("connection_id=0"));
2684        assert!(logs.contains("corr=41"));
2685        assert!(
2686            logged_millis(&logs, "elapsed_ms=") >= 1050,
2687            "elapsed must include the injected handler delay: {logs}"
2688        );
2689    }
2690
2691    #[tokio::test]
2692    async fn fast_control_dispatch_emits_arrival_without_slow_warning() {
2693        let router = Router::with_default_self_handler();
2694        let (ctx, mut rx) = route_ctx();
2695        let (output, guard) = log_capture(tracing::Level::DEBUG);
2696
2697        router
2698            .route_for_connection(&ctx, request(0, 42, br#"{"op":"server.describe"}"#))
2699            .await
2700            .expect("fast request routes");
2701        assert!(rx.recv().await.is_some(), "request receives a response");
2702        drop(guard);
2703
2704        let logs = captured_logs(&output);
2705        assert!(logs.contains("control dispatch op=server.describe connection_id=0 corr=42"));
2706        assert!(!logs.contains("slow control dispatch"));
2707    }
2708
2709    #[tokio::test]
2710    async fn control_dispatch_arrival_is_hidden_at_info() {
2711        let router = Router::with_default_self_handler();
2712        let (ctx, mut rx) = route_ctx();
2713        let (output, guard) = log_capture(tracing::Level::INFO);
2714
2715        router
2716            .route_for_connection(&ctx, request(0, 43, br#"{"op":"server.describe"}"#))
2717            .await
2718            .expect("fast request routes");
2719        assert!(rx.recv().await.is_some(), "request receives a response");
2720        drop(guard);
2721
2722        assert!(
2723            !captured_logs(&output).contains("control dispatch"),
2724            "arrival logging must stay hidden at INFO"
2725        );
2726    }
2727
2728    #[tokio::test]
2729    async fn supervisor_list_logs_contended_snapshot_lock_only() {
2730        let registry = Arc::new(Registry::default());
2731        let handle = SupervisorHandle::new();
2732        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
2733            .with_handle(handle.clone());
2734        let module = supervisor
2735            .supervise_configured(
2736                ModuleSpec {
2737                    script: None,
2738                    carry_containment: false,
2739                    module_id: "held-module".to_string(),
2740                    program: "test-module".into(),
2741                    args: Vec::new(),
2742                    env: Vec::new(),
2743                    reserved: false,
2744                    reserved_prefixes: Vec::new(),
2745                    protocol: ModuleProtocol::Subc,
2746                    overlap: Default::default(),
2747                },
2748                false,
2749            )
2750            .expect("disabled test module is supervised");
2751        let router = Router::with_control_handler(Arc::new(
2752            ControlHandler::new(Arc::clone(&registry)).with_supervisor(handle),
2753        ));
2754        let (ctx, mut rx) = route_ctx();
2755        let (acquired, ready) = std_mpsc::channel();
2756        // Park the disabled supervisor actor before holding its snapshot. The
2757        // detached list reader, not actor startup, must be the lock contender.
2758        tokio::task::yield_now().await;
2759        let holder = module.hold_snapshot_for_test(acquired, Duration::from_millis(400));
2760        ready.recv().expect("holder acquired snapshot lock");
2761        let (output, guard) = log_capture(tracing::Level::WARN);
2762
2763        router
2764            .route_for_connection(&ctx, request(0, 44, br#"{"op":"supervisor.list"}"#))
2765            .await
2766            .expect("list request routes after the lock releases");
2767        assert!(
2768            rx.recv().await.is_some(),
2769            "list request receives a response"
2770        );
2771        holder.join().expect("snapshot holder exits cleanly");
2772        drop(guard);
2773
2774        let logs = captured_logs(&output);
2775        assert!(logs.contains("slow snapshot lock"));
2776        assert!(logs.contains("module_id=held-module"));
2777        assert!(logs.contains("caller=list"));
2778        assert!(
2779            logged_millis(&logs, "waited_ms=") >= 250,
2780            "wait must exceed the slow-lock threshold: {logs}"
2781        );
2782
2783        let (output, guard) = log_capture(tracing::Level::WARN);
2784        router
2785            .route_for_connection(&ctx, request(0, 45, br#"{"op":"supervisor.list"}"#))
2786            .await
2787            .expect("uncontended list request routes");
2788        assert!(
2789            rx.recv().await.is_some(),
2790            "uncontended list receives a response"
2791        );
2792        drop(guard);
2793        assert!(
2794            !captured_logs(&output).contains("slow snapshot lock"),
2795            "uncontended list acquisition must not warn"
2796        );
2797    }
2798
2799    #[tokio::test]
2800    async fn full_module_to_client_sink_requests_client_close_without_erroring_module() {
2801        let forwarding = Arc::new(ForwardingTable::default());
2802        let control = Arc::new(ControlHandler::with_forwarding(
2803            Arc::new(crate::Registry::default()),
2804            Arc::clone(&forwarding),
2805        ));
2806        let router = Router::with_control_handler(control);
2807        let module_connection = ConnectionId::new(10);
2808        let client_connection = ConnectionId::new(20);
2809        let mut close_receiver = forwarding.register_connection_close(client_connection);
2810        let (module_tx, _module_rx) = mpsc::channel(1);
2811        forwarding
2812            .register_module_connection(
2813                module_connection,
2814                "full-sink-provider".to_string(),
2815                1,
2816                Concurrency::ModuleManaged,
2817                FrameSink::new(module_tx),
2818            )
2819            .unwrap();
2820        let (client_tx, mut client_rx) = mpsc::channel(1);
2821        let pending = forwarding
2822            .begin_route_bind_relay_for_test(
2823                client_connection,
2824                FrameSink::new(client_tx),
2825                700,
2826                "full-sink-provider",
2827            )
2828            .unwrap();
2829        forwarding
2830            .complete_pending_relay(
2831                module_connection,
2832                pending.corr,
2833                RouteBindRelayOutcome::Accepted,
2834            )
2835            .unwrap();
2836
2837        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2838        let module_ctx = RouteCtx {
2839            connection_id: module_connection,
2840            egress: FrameSink::new(module_egress_tx),
2841        };
2842        let terminal = Frame::build(
2843            FrameType::Response,
2844            Flags::new(false, Priority::Interactive, true),
2845            pending.module_channel,
2846            pending.module_epoch,
2847            701,
2848            b"terminal".to_vec(),
2849        )
2850        .unwrap();
2851
2852        router
2853            .route_for_connection(&module_ctx, terminal)
2854            .await
2855            .unwrap();
2856        let reason = tokio::time::timeout(Duration::from_secs(1), &mut close_receiver)
2857            .await
2858            .expect("close request should be sent for the full client sink")
2859            .expect("close sender should include a reason");
2860        assert!(
2861            reason
2862                .to_string()
2863                .contains("module_to_client_delivery_failed"),
2864            "unexpected close reason: {reason}"
2865        );
2866        assert_eq!(client_rx.try_recv().unwrap().header.corr, 700);
2867        assert!(client_rx.try_recv().is_err());
2868        assert_eq!(
2869            router.counters.snapshot()["client_egress_close_delivery_failed"],
2870            1
2871        );
2872    }
2873
2874    /// A terminal frame ends the request at the module even when the client
2875    /// cannot take it, so the drain must stop counting it at once rather than
2876    /// when the client connection's cleanup later removes the route.
2877    #[tokio::test]
2878    async fn terminal_frame_releases_its_credit_even_when_client_delivery_fails() {
2879        let forwarding = Arc::new(ForwardingTable::default());
2880        let control = Arc::new(ControlHandler::with_forwarding(
2881            Arc::new(crate::Registry::default()),
2882            Arc::clone(&forwarding),
2883        ));
2884        let router = Router::with_control_handler(control);
2885        let module_connection = ConnectionId::new(11);
2886        let client_connection = ConnectionId::new(21);
2887        let _close_receiver = forwarding.register_connection_close(client_connection);
2888        let (module_tx, _module_rx) = mpsc::channel(1);
2889        forwarding
2890            .register_module_connection(
2891                module_connection,
2892                "credit-provider".to_string(),
2893                1,
2894                Concurrency::ModuleManaged,
2895                FrameSink::new(module_tx),
2896            )
2897            .unwrap();
2898        // Capacity one, filled by the route.open response, so the terminal
2899        // frame below cannot be enqueued for the client.
2900        let (client_tx, _client_rx) = mpsc::channel(1);
2901        let pending = forwarding
2902            .begin_route_bind_relay_for_test(
2903                client_connection,
2904                FrameSink::new(client_tx),
2905                800,
2906                "credit-provider",
2907            )
2908            .unwrap();
2909        forwarding
2910            .complete_pending_relay(
2911                module_connection,
2912                pending.corr,
2913                RouteBindRelayOutcome::Accepted,
2914            )
2915            .unwrap();
2916        let DataRoute::Client(DataRouteState::Bound(route)) = forwarding
2917            .lookup_data_route(
2918                client_connection,
2919                pending.client_channel,
2920                pending.client_epoch,
2921            )
2922            .unwrap()
2923        else {
2924            panic!("expected a bound client route");
2925        };
2926        route.flow.acquire_tagged(801, false).await.unwrap();
2927        assert_eq!(route.flow.drain_in_flight(), 1);
2928
2929        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2930        let module_ctx = RouteCtx {
2931            connection_id: module_connection,
2932            egress: FrameSink::new(module_egress_tx),
2933        };
2934        let terminal = Frame::build(
2935            FrameType::Response,
2936            Flags::new(false, Priority::Interactive, true),
2937            pending.module_channel,
2938            pending.module_epoch,
2939            801,
2940            b"terminal".to_vec(),
2941        )
2942        .unwrap();
2943        router
2944            .route_for_connection(&module_ctx, terminal)
2945            .await
2946            .unwrap();
2947
2948        assert_eq!(
2949            router.counters.snapshot()["client_egress_close_delivery_failed"],
2950            1,
2951            "the client delivery must have failed for this test to mean anything"
2952        );
2953        assert_eq!(
2954            route.flow.drain_in_flight(),
2955            0,
2956            "the module's terminal frame must release its credit even though the client could not take it"
2957        );
2958    }
2959
2960    #[tokio::test]
2961    async fn full_route_goodbye_sink_requests_target_close_without_erroring_module() {
2962        let forwarding = Arc::new(ForwardingTable::default());
2963        let control = Arc::new(ControlHandler::with_forwarding(
2964            Arc::new(crate::Registry::default()),
2965            Arc::clone(&forwarding),
2966        ));
2967        let router = Router::with_control_handler(control);
2968        let module_connection = ConnectionId::new(30);
2969        let client_connection = ConnectionId::new(40);
2970        let mut close_receiver = forwarding.register_connection_close(client_connection);
2971        let (module_tx, _module_rx) = mpsc::channel(1);
2972        forwarding
2973            .register_module_connection(
2974                module_connection,
2975                "goodbye-full-provider".to_string(),
2976                1,
2977                Concurrency::ModuleManaged,
2978                FrameSink::new(module_tx),
2979            )
2980            .unwrap();
2981        let (client_tx, mut client_rx) = mpsc::channel(1);
2982        let pending = forwarding
2983            .begin_route_bind_relay_for_test(
2984                client_connection,
2985                FrameSink::new(client_tx),
2986                800,
2987                "goodbye-full-provider",
2988            )
2989            .unwrap();
2990        forwarding
2991            .complete_pending_relay(
2992                module_connection,
2993                pending.corr,
2994                RouteBindRelayOutcome::Accepted,
2995            )
2996            .unwrap();
2997
2998        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2999        let module_ctx = RouteCtx {
3000            connection_id: module_connection,
3001            egress: FrameSink::new(module_egress_tx),
3002        };
3003        let goodbye = Frame::build(
3004            FrameType::Goodbye,
3005            Flags::new(false, Priority::Passive, true),
3006            pending.module_channel,
3007            pending.module_epoch,
3008            801,
3009            Vec::new(),
3010        )
3011        .unwrap();
3012
3013        router
3014            .route_for_connection(&module_ctx, goodbye)
3015            .await
3016            .unwrap();
3017        let reason = tokio::time::timeout(Duration::from_secs(1), &mut close_receiver)
3018            .await
3019            .expect("close request should be sent for the full GOODBYE sink")
3020            .expect("close sender should include a reason");
3021        assert!(
3022            reason.to_string().contains("route_goodbye_delivery_failed"),
3023            "unexpected close reason: {reason}"
3024        );
3025        assert_eq!(client_rx.try_recv().unwrap().header.corr, 800);
3026        assert!(client_rx.try_recv().is_err());
3027        assert_eq!(router.counters.snapshot()["goodbye_relay_client_failed"], 1);
3028        assert_eq!(router.counters.snapshot()["route_released_epoch_fenced"], 1);
3029    }
3030
3031    /// One module and one client connection with `routes` routes bound between
3032    /// them. The client uses a real connection egress queue (the same byte
3033    /// budget and frame-count backstop as a live connection), and its route.open
3034    /// responses are drained so the queue starts empty.
3035    async fn multi_route_client(
3036        module_id: &str,
3037        module_connection: ConnectionId,
3038        client_connection: ConnectionId,
3039        routes: usize,
3040    ) -> (
3041        Router,
3042        FrameSink,
3043        mpsc::Receiver<OutboundFrame>,
3044        RouteCtx,
3045        Vec<crate::forwarding::PendingRouteBindRelay>,
3046        ConnectionCloseReceiver,
3047    ) {
3048        let forwarding = Arc::new(ForwardingTable::default());
3049        let control = Arc::new(ControlHandler::with_forwarding(
3050            Arc::new(crate::Registry::default()),
3051            Arc::clone(&forwarding),
3052        ));
3053        let router = Router::with_control_handler(control);
3054        let close_receiver = forwarding.register_connection_close(client_connection);
3055        let (module_tx, _module_rx) = mpsc::channel(8);
3056        forwarding
3057            .register_module_connection(
3058                module_connection,
3059                module_id.to_string(),
3060                1,
3061                Concurrency::ModuleManaged,
3062                FrameSink::new(module_tx),
3063            )
3064            .unwrap();
3065        let (client_sink, mut client_rx) = crate::server::connection_egress();
3066        let mut bound = Vec::with_capacity(routes);
3067        for index in 0..routes {
3068            let pending = forwarding
3069                .begin_route_bind_relay_for_test(
3070                    client_connection,
3071                    client_sink.clone(),
3072                    900 + index as u64,
3073                    module_id,
3074                )
3075                .unwrap();
3076            forwarding
3077                .complete_pending_relay(
3078                    module_connection,
3079                    pending.corr,
3080                    RouteBindRelayOutcome::Accepted,
3081                )
3082                .unwrap();
3083            assert_eq!(
3084                client_rx.recv().await.unwrap().header.corr,
3085                900 + index as u64
3086            );
3087            bound.push(pending);
3088        }
3089        let (module_egress_tx, _module_egress_rx) = mpsc::channel(8);
3090        let module_ctx = RouteCtx {
3091            connection_id: module_connection,
3092            egress: FrameSink::new(module_egress_tx),
3093        };
3094        (
3095            router,
3096            client_sink,
3097            client_rx,
3098            module_ctx,
3099            bound,
3100            close_receiver,
3101        )
3102    }
3103
3104    /// Per-frame cost of the egress sink's admission and release accounting:
3105    /// one million 200-byte frames enqueued with `try_send` and taken off the
3106    /// queue the way the connection writer does, in batches of 1,000 so the
3107    /// queue stays well inside its budget. Prints nanoseconds per frame; it is
3108    /// a measurement, not a gate. Run with
3109    /// `cargo test --release -p subc-daemon --lib egress_sink_per_frame_cost -- --ignored --nocapture`.
3110    #[test]
3111    #[ignore = "timing measurement, run on demand"]
3112    fn egress_sink_per_frame_cost() {
3113        const FRAMES: usize = 1_000_000;
3114        const BATCH: usize = 1_000;
3115        let (sink, mut rx) = crate::server::connection_egress();
3116        let template = stream_frame(9, 1, 0, vec![b't'; 200]);
3117        let started = Instant::now();
3118        for _ in 0..FRAMES / BATCH {
3119            for _ in 0..BATCH {
3120                sink.try_send(template.clone()).unwrap();
3121            }
3122            for _ in 0..BATCH {
3123                let outbound = rx.try_recv().unwrap();
3124                if let Some(charge) = &outbound.charge {
3125                    charge.taken_by_writer();
3126                }
3127                drop(std::hint::black_box(outbound));
3128            }
3129        }
3130        let elapsed = started.elapsed();
3131        assert_eq!(sink.backlog().queued_bytes, 0);
3132        println!(
3133            "egress sink: {FRAMES} frames in {elapsed:?}, {:.1} ns/frame",
3134            elapsed.as_nanos() as f64 / FRAMES as f64
3135        );
3136    }
3137
3138    fn stream_frame(channel: u16, epoch: u32, corr: u64, body: Vec<u8>) -> Frame {
3139        Frame::build(
3140            FrameType::StreamData,
3141            Flags::new(false, Priority::Interactive, false),
3142            channel,
3143            epoch,
3144            corr,
3145            body,
3146        )
3147        .unwrap()
3148    }
3149
3150    fn module_route_for_test(
3151        router: &Router,
3152        ctx: &RouteCtx,
3153        route: &crate::forwarding::PendingRouteBindRelay,
3154    ) -> Arc<RouteBinding> {
3155        match router
3156            .forwarding
3157            .lookup_data_route(ctx.connection_id, route.module_channel, route.module_epoch)
3158            .unwrap()
3159        {
3160            DataRoute::Module(DataRouteState::Bound(binding)) => binding,
3161            other => panic!("expected a bound module route, got {other:?}"),
3162        }
3163    }
3164
3165    fn assert_frame_size_error(frame: &Frame, channel: u16, epoch: u32, corr: u64, bytes: usize) {
3166        assert_eq!(frame.header.ty, FrameType::Error);
3167        assert_eq!(frame.header.channel, channel);
3168        assert_eq!(frame.header.epoch, epoch);
3169        assert_eq!(frame.header.corr, corr);
3170        assert!(frame.header.flags.is_daemon_origin());
3171        let body: ErrorBody = serde_json::from_slice(&frame.body).unwrap();
3172        assert_eq!(body.code, error_codes::FRAME_TOO_LARGE);
3173        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3174        assert!(body.message.contains(&bytes.to_string()));
3175        assert!(body.message.contains(&limit.to_string()));
3176        assert_eq!(
3177            body.detail,
3178            Some(serde_json::json!({ "frame_bytes": bytes, "byte_limit": limit }))
3179        );
3180    }
3181
3182    #[tokio::test]
3183    async fn module_egress_response_oversized_reply_keeps_connection_and_other_route() {
3184        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3185        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3186            "oversize-provider",
3187            ConnectionId::new(80),
3188            ConnectionId::new(81),
3189            2,
3190        )
3191        .await;
3192        let binding = module_route_for_test(&router, &ctx, &routes[0]);
3193        binding.flow.acquire_tagged(101, false).await.unwrap();
3194        module_route_for_test(&router, &ctx, &routes[1])
3195            .flow
3196            .acquire_tagged(102, false)
3197            .await
3198            .unwrap();
3199        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3200        let oversized = Frame::build(
3201            FrameType::Response,
3202            Flags::new(false, Priority::Interactive, true),
3203            routes[0].module_channel,
3204            routes[0].module_epoch,
3205            101,
3206            vec![b'x'; limit - subc_protocol::HEADER_LEN + 1],
3207        )
3208        .unwrap();
3209        assert_eq!(sink.backlog().queued_bytes, 0);
3210        router.route_for_connection(&ctx, oversized).await.unwrap();
3211
3212        // Reproduce a large reply followed by ordinary traffic on another route
3213        // before the client reads anything. The large reply must not monopolize
3214        // the queue and make that second delivery close the shared connection.
3215        router
3216            .route_for_connection(
3217                &ctx,
3218                route_frame(
3219                    FrameType::Response,
3220                    routes[1].module_channel,
3221                    routes[1].module_epoch,
3222                    102,
3223                ),
3224            )
3225            .await
3226            .unwrap();
3227        assert!(
3228            close.try_recv().is_err(),
3229            "an oversized reply must not close the multiplexed client"
3230        );
3231        let error = rx.try_recv().expect("the waiting client gets an ERROR");
3232        assert_frame_size_error(
3233            &error,
3234            routes[0].client_channel,
3235            routes[0].client_epoch,
3236            101,
3237            limit + 1,
3238        );
3239        let second = rx.try_recv().expect("the other route's reply arrives");
3240        assert_eq!(second.header.ty, FrameType::Response);
3241        assert_eq!(second.header.channel, routes[1].client_channel);
3242        assert_eq!(second.header.epoch, routes[1].client_epoch);
3243        assert_eq!(second.header.corr, 102);
3244        assert_eq!(second.body, b"route-body");
3245        assert_eq!(binding.flow.drain_in_flight(), 0);
3246        for route in &routes {
3247            module_route_for_test(&router, &ctx, route);
3248        }
3249        assert!(rx.try_recv().is_err());
3250        drop((error, second));
3251        assert_eq!(sink.backlog().queued_bytes, 0);
3252        assert_eq!(
3253            router.counters.snapshot()["client_egress_close_delivery_failed"],
3254            0
3255        );
3256
3257        let captured = test_log::captured_logs(&logs);
3258        let warnings: Vec<_> = captured
3259            .lines()
3260            .filter(|line| line.contains("WARN"))
3261            .collect();
3262        assert_eq!(warnings.len(), 1, "{captured}");
3263        let warning = warnings[0];
3264        for expected in [
3265            "module_id=oversize-provider".to_string(),
3266            "client_principal=direct".to_string(),
3267            format!("client_channel={}", routes[0].client_channel),
3268            format!("frame_bytes={}", limit + 1),
3269            format!("byte_limit={limit}"),
3270        ] {
3271            assert!(warning.contains(&expected), "missing {expected}: {warning}");
3272        }
3273    }
3274
3275    async fn poll_once<F: std::future::Future>(
3276        mut future: std::pin::Pin<&mut F>,
3277    ) -> std::task::Poll<F::Output> {
3278        std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))).await
3279    }
3280
3281    fn fill_client_budget(sink: &FrameSink, route: &crate::forwarding::PendingRouteBindRelay) {
3282        sink.try_send(
3283            Frame::build(
3284                FrameType::Response,
3285                Flags::new(false, Priority::Interactive, true),
3286                route.client_channel,
3287                route.client_epoch,
3288                100,
3289                vec![
3290                    b'x';
3291                    crate::server::CONNECTION_EGRESS_BYTE_BUDGET - subc_protocol::HEADER_LEN
3292                ],
3293            )
3294            .unwrap(),
3295        )
3296        .unwrap();
3297        assert_eq!(
3298            sink.backlog().queued_bytes,
3299            crate::server::CONNECTION_EGRESS_BYTE_BUDGET
3300        );
3301    }
3302
3303    async fn assert_full_client_burst_survives(ty: FrameType, oversized: bool) {
3304        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3305            "draining-burst",
3306            ConnectionId::new(92),
3307            ConnectionId::new(93),
3308            2,
3309        )
3310        .await;
3311        fill_client_budget(&sink, &routes[0]);
3312        let frame = if oversized {
3313            Frame::build(
3314                ty,
3315                Flags::new(false, Priority::Interactive, false),
3316                routes[1].module_channel,
3317                routes[1].module_epoch,
3318                101,
3319                vec![b's'; crate::server::CONNECTION_EGRESS_BYTE_BUDGET],
3320            )
3321            .unwrap()
3322        } else {
3323            route_frame(ty, routes[1].module_channel, routes[1].module_epoch, 101)
3324        };
3325        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3326        assert!(poll_once(delivery.as_mut()).await.is_pending());
3327        assert!(
3328            close.try_recv().is_err(),
3329            "fresh bursts must not close: {ty:?}"
3330        );
3331        tokio::time::advance(Duration::from_millis(50)).await;
3332        let queued = rx.try_recv().unwrap();
3333        queued.charge.as_ref().unwrap().taken_by_writer();
3334        drop(queued);
3335        assert!(matches!(
3336            poll_once(delivery.as_mut()).await,
3337            std::task::Poll::Ready(Ok(()))
3338        ));
3339        let delivered = rx
3340            .try_recv()
3341            .expect("the burst frame must be delivered after draining");
3342        assert_eq!(delivered.header.channel, routes[1].client_channel);
3343        assert_eq!(delivered.header.epoch, routes[1].client_epoch);
3344        assert_eq!(delivered.header.corr, 101);
3345        if oversized {
3346            assert_frame_size_error(
3347                &delivered,
3348                routes[1].client_channel,
3349                routes[1].client_epoch,
3350                101,
3351                crate::server::CONNECTION_EGRESS_BYTE_BUDGET + subc_protocol::HEADER_LEN,
3352            );
3353        } else {
3354            assert_eq!(delivered.header.ty, ty);
3355        }
3356        assert!(rx.try_recv().is_err());
3357        assert!(close.try_recv().is_err());
3358        assert_eq!(
3359            router.counters.snapshot()["client_egress_close_delivery_failed"],
3360            0
3361        );
3362        assert_eq!(router.counters.snapshot()["goodbye_relay_client_failed"], 0);
3363    }
3364
3365    #[tokio::test(start_paused = true)]
3366    async fn module_egress_fresh_full_queue_burst_survives() {
3367        for ty in [
3368            FrameType::Response,
3369            FrameType::StreamData,
3370            FrameType::Request,
3371            FrameType::Push,
3372        ] {
3373            assert_full_client_burst_survives(ty, false).await;
3374        }
3375    }
3376
3377    #[tokio::test(start_paused = true)]
3378    async fn module_goodbye_fresh_full_queue_burst_survives() {
3379        assert_full_client_burst_survives(FrameType::Goodbye, false).await;
3380    }
3381
3382    #[tokio::test(start_paused = true)]
3383    async fn frame_count_backstop_also_allows_a_draining_burst() {
3384        let (tx, mut rx) = mpsc::channel(1);
3385        let sink = FrameSink::with_byte_budget(tx, 2_000);
3386        sink.try_send(stream_frame(1, 1, 1, vec![b'x'; 100]))
3387            .unwrap();
3388        let mut delivery = Box::pin(sink.send_to_client(stream_frame(1, 1, 2, vec![b'y'; 100])));
3389        assert!(poll_once(delivery.as_mut()).await.is_pending());
3390        assert!(
3391            sink.backlog().queued_bytes < 2_000,
3392            "only frame capacity is exhausted"
3393        );
3394        tokio::time::advance(Duration::from_millis(50)).await;
3395        drop(rx.try_recv().unwrap());
3396        assert!(matches!(
3397            poll_once(delivery.as_mut()).await,
3398            std::task::Poll::Ready(Ok(()))
3399        ));
3400        assert_eq!(rx.try_recv().unwrap().header.corr, 2);
3401    }
3402
3403    #[tokio::test(start_paused = true)]
3404    async fn oversized_reply_replacement_fresh_full_queue_burst_survives() {
3405        for ty in [FrameType::Response, FrameType::StreamData] {
3406            assert_full_client_burst_survives(ty, true).await;
3407        }
3408    }
3409
3410    #[tokio::test(start_paused = true)]
3411    async fn module_egress_stopped_reader_closes_without_waiting() {
3412        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3413        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3414            "oldest-stopped-reader",
3415            ConnectionId::new(94),
3416            ConnectionId::new(95),
3417            2,
3418        )
3419        .await;
3420        fill_client_budget(&sink, &routes[0]);
3421        // The writer has taken the head but cannot finish writing it. Its
3422        // bytes stay charged, and the atomic age still diagnoses that stall.
3423        let writing = rx.try_recv().unwrap();
3424        writing.charge.as_ref().unwrap().taken_by_writer();
3425        tokio::time::advance(Duration::from_millis(251)).await;
3426        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(251)));
3427        assert_eq!(sink.backlog().queued_bytes, queued_frame_bytes(&writing));
3428        let started = tokio::time::Instant::now();
3429        let frame = stream_frame(
3430            routes[0].module_channel,
3431            routes[0].module_epoch,
3432            101,
3433            b"secret-body-never-log".to_vec(),
3434        );
3435        let flags = frame.header.flags.0;
3436        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3437        assert!(
3438            matches!(
3439                poll_once(delivery.as_mut()).await,
3440                std::task::Poll::Ready(Ok(()))
3441            ),
3442            "an oldest frame older than 250 ms must close immediately, without a new wait"
3443        );
3444        assert_eq!(started.elapsed(), Duration::ZERO);
3445        assert!(close
3446            .try_recv()
3447            .unwrap()
3448            .to_string()
3449            .contains("module_to_client_delivery_failed"));
3450        let captured = test_log::captured_logs(&logs);
3451        for expected in [
3452            "frame_type=Some(StreamData)".to_string(),
3453            format!("frame_flags=Some({flags})"),
3454            "oldest_queued_ms=251".to_string(),
3455            "close_cause=\"oldest_frame_older_than_250_ms\"".to_string(),
3456        ] {
3457            assert!(
3458                captured.contains(&expected),
3459                "missing {expected}: {captured}"
3460            );
3461        }
3462        assert!(!captured.contains("secret-body-never-log"));
3463    }
3464
3465    #[tokio::test(start_paused = true)]
3466    async fn client_gone_mid_wait_resumes_module_reader_immediately() {
3467        for writer_gone in [false, true] {
3468            let (router, sink, mut rx, ctx, routes, _close) = multi_route_client(
3469                "gone-during-burst",
3470                ConnectionId::new(96),
3471                ConnectionId::new(97),
3472                1,
3473            )
3474            .await;
3475            fill_client_budget(&sink, &routes[0]);
3476            let frame = route_frame(
3477                FrameType::Response,
3478                routes[0].module_channel,
3479                routes[0].module_epoch,
3480                101,
3481            );
3482            let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3483            assert!(poll_once(delivery.as_mut()).await.is_pending());
3484            tokio::time::advance(Duration::from_millis(50)).await;
3485            let started = tokio::time::Instant::now();
3486            if writer_gone {
3487                rx.close();
3488            } else {
3489                sink.close_client_delivery();
3490            }
3491            assert!(
3492                matches!(
3493                    poll_once(delivery.as_mut()).await,
3494                    std::task::Poll::Ready(Ok(()))
3495                ),
3496                "client teardown must wake the module reader before the writer drains"
3497            );
3498            assert_eq!(started.elapsed(), Duration::ZERO);
3499            assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 0);
3500            assert_eq!(rx.try_recv().unwrap().header.corr, 100);
3501            assert!(rx.try_recv().is_err());
3502        }
3503    }
3504
3505    #[tokio::test(start_paused = true)]
3506    async fn cancelled_module_delivery_releases_waiter_without_closing_client() {
3507        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3508            "cancelled-burst",
3509            ConnectionId::new(98),
3510            ConnectionId::new(99),
3511            1,
3512        )
3513        .await;
3514        fill_client_budget(&sink, &routes[0]);
3515        let frame = route_frame(
3516            FrameType::Response,
3517            routes[0].module_channel,
3518            routes[0].module_epoch,
3519            101,
3520        );
3521        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3522        assert!(poll_once(delivery.as_mut()).await.is_pending());
3523        assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 1);
3524        drop(delivery);
3525        assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 0);
3526        tokio::time::advance(Duration::from_secs(1)).await;
3527        assert!(close.try_recv().is_err());
3528        drop(rx.try_recv().unwrap());
3529        assert_eq!(sink.backlog().queued_bytes, 0);
3530        assert!(sink.backlog().oldest_age.is_none());
3531    }
3532
3533    #[tokio::test(start_paused = true)]
3534    async fn egress_atomic_age_follows_writer_and_clears_when_drained() {
3535        let (sink, mut rx) = crate::server::connection_egress();
3536        sink.try_send(stream_frame(1, 1, 1, vec![b'x'; 100]))
3537            .unwrap();
3538        tokio::time::advance(Duration::from_millis(200)).await;
3539        sink.try_send(stream_frame(2, 1, 2, vec![b'y'; 100]))
3540            .unwrap();
3541        let writing = rx.try_recv().unwrap();
3542        writing.charge.as_ref().unwrap().taken_by_writer();
3543        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(200)));
3544        drop(writing);
3545        // Between frames the lock-free marker can still name the previous
3546        // head. The next writer take advances it without scanning the queue.
3547        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(200)));
3548        tokio::time::advance(Duration::from_millis(50)).await;
3549        let next = rx.try_recv().unwrap();
3550        next.charge.as_ref().unwrap().taken_by_writer();
3551        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(50)));
3552        assert!(
3553            sink.backlog().queued_bytes > 0,
3554            "in-flight bytes remain charged until written"
3555        );
3556        drop(next);
3557        assert_eq!(sink.backlog().queued_bytes, 0);
3558        assert_eq!(sink.backlog().oldest_age, None);
3559    }
3560
3561    #[tokio::test(start_paused = true)]
3562    async fn module_egress_response_full_client_waits_only_remaining_grace() {
3563        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3564            "backpressure-provider",
3565            ConnectionId::new(82),
3566            ConnectionId::new(83),
3567            2,
3568        )
3569        .await;
3570        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3571        // Exactly the limit, including its header, must be admitted to an empty
3572        // queue. Leave it unread to deterministically exhaust only byte capacity.
3573        router
3574            .route_for_connection(
3575                &ctx,
3576                Frame::build(
3577                    FrameType::Response,
3578                    Flags::new(false, Priority::Interactive, true),
3579                    routes[0].module_channel,
3580                    routes[0].module_epoch,
3581                    201,
3582                    vec![b'x'; limit - subc_protocol::HEADER_LEN],
3583                )
3584                .unwrap(),
3585            )
3586            .await
3587            .unwrap();
3588        assert_eq!(sink.backlog().queued_bytes, limit);
3589        assert_eq!(sink.backlog().queued_frames, 1);
3590        let ordinary = route_frame(
3591            FrameType::Response,
3592            routes[1].module_channel,
3593            routes[1].module_epoch,
3594            202,
3595        );
3596        assert!(queued_frame_bytes(&ordinary) < limit);
3597        // A fitting reply gets only the unused portion of the oldest frame's
3598        // 250 ms grace, not an immediate close or a fresh 250 ms wait.
3599        tokio::time::advance(Duration::from_millis(100)).await;
3600        let mut delivery = Box::pin(router.route_for_connection(&ctx, ordinary));
3601        assert!(poll_once(delivery.as_mut()).await.is_pending());
3602        assert!(close.try_recv().is_err());
3603        tokio::time::advance(Duration::from_millis(149)).await;
3604        assert!(poll_once(delivery.as_mut()).await.is_pending());
3605        assert!(close.try_recv().is_err());
3606        tokio::time::advance(Duration::from_millis(1)).await;
3607        assert!(matches!(
3608            poll_once(delivery.as_mut()).await,
3609            std::task::Poll::Ready(Ok(()))
3610        ));
3611        drop(delivery);
3612        let reason = close.try_recv().expect("the full client must close");
3613        assert!(reason
3614            .to_string()
3615            .contains("module_to_client_delivery_failed"));
3616        assert!(!reason.to_string().contains("frame_too_large"));
3617        assert_eq!(
3618            router.counters.snapshot()["client_egress_close_delivery_failed"],
3619            1
3620        );
3621        let admitted = rx.try_recv().expect("the budget-sized frame was admitted");
3622        assert_eq!(admitted.header.ty, FrameType::Response);
3623        assert_eq!(admitted.header.corr, 201);
3624        assert!(
3625            rx.try_recv().is_err(),
3626            "no oversized-frame ERROR is substituted for backpressure"
3627        );
3628    }
3629
3630    #[tokio::test(start_paused = true)]
3631    async fn oversized_reply_to_a_full_client_waits_only_remaining_grace() {
3632        let (router, sink, _rx, ctx, routes, mut close) = multi_route_client(
3633            "full-oversize-provider",
3634            ConnectionId::new(90),
3635            ConnectionId::new(91),
3636            2,
3637        )
3638        .await;
3639        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3640        // Fill the client's queue to its budget and leave it unread.
3641        router
3642            .route_for_connection(
3643                &ctx,
3644                Frame::build(
3645                    FrameType::Response,
3646                    Flags::new(false, Priority::Interactive, true),
3647                    routes[0].module_channel,
3648                    routes[0].module_epoch,
3649                    501,
3650                    vec![b'x'; limit - subc_protocol::HEADER_LEN],
3651                )
3652                .unwrap(),
3653            )
3654            .await
3655            .unwrap();
3656        assert_eq!(sink.backlog().queued_bytes, limit);
3657        let oversized = Frame::build(
3658            FrameType::Response,
3659            Flags::new(false, Priority::Interactive, true),
3660            routes[1].module_channel,
3661            routes[1].module_epoch,
3662            502,
3663            vec![b'y'; limit - subc_protocol::HEADER_LEN + 1],
3664        )
3665        .unwrap();
3666        // The replacement ERROR gets the same bounded burst grace as the
3667        // ordinary reply; oversized payloads themselves are never queued.
3668        tokio::time::advance(Duration::from_millis(80)).await;
3669        let mut delivery = Box::pin(router.route_for_connection(&ctx, oversized));
3670        assert!(poll_once(delivery.as_mut()).await.is_pending());
3671        assert!(close.try_recv().is_err());
3672        tokio::time::advance(Duration::from_millis(169)).await;
3673        assert!(poll_once(delivery.as_mut()).await.is_pending());
3674        assert!(close.try_recv().is_err());
3675        tokio::time::advance(Duration::from_millis(1)).await;
3676        assert!(matches!(
3677            poll_once(delivery.as_mut()).await,
3678            std::task::Poll::Ready(Ok(()))
3679        ));
3680        drop(delivery);
3681        let reason = close.try_recv().expect("the full client must close");
3682        assert!(reason
3683            .to_string()
3684            .contains("module_to_client_delivery_failed"));
3685    }
3686
3687    #[tokio::test]
3688    async fn oversized_reverse_request_errors_module_without_reaching_client() {
3689        let (router, _sink, mut rx, mut ctx, routes, mut close) = multi_route_client(
3690            "reverse-oversize-provider",
3691            ConnectionId::new(84),
3692            ConnectionId::new(85),
3693            2,
3694        )
3695        .await;
3696        let (module_tx, mut module_rx) = mpsc::channel(8);
3697        ctx.egress = FrameSink::new(module_tx);
3698        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3699        router
3700            .route_for_connection(
3701                &ctx,
3702                Frame::build(
3703                    FrameType::Request,
3704                    Flags::new(false, Priority::Interactive, false),
3705                    routes[0].module_channel,
3706                    routes[0].module_epoch,
3707                    301,
3708                    vec![b'r'; limit - subc_protocol::HEADER_LEN + 1],
3709                )
3710                .unwrap(),
3711            )
3712            .await
3713            .unwrap();
3714        assert!(
3715            rx.try_recv().is_err(),
3716            "the reverse request never reaches the client"
3717        );
3718        let error = module_rx.try_recv().expect("the module gets the refusal");
3719        assert_frame_size_error(
3720            &error,
3721            routes[0].module_channel,
3722            routes[0].module_epoch,
3723            301,
3724            limit + 1,
3725        );
3726        assert!(module_rx.try_recv().is_err());
3727        for (index, route) in routes.iter().enumerate() {
3728            module_route_for_test(&router, &ctx, route);
3729            router
3730                .route_for_connection(
3731                    &ctx,
3732                    route_frame(
3733                        FrameType::Response,
3734                        route.module_channel,
3735                        route.module_epoch,
3736                        302 + index as u64,
3737                    ),
3738                )
3739                .await
3740                .unwrap();
3741            let reply = rx.try_recv().expect("both routes still deliver");
3742            assert_eq!(reply.header.ty, FrameType::Response);
3743            assert_eq!(reply.header.channel, route.client_channel);
3744        }
3745        assert!(close.try_recv().is_err());
3746        assert_eq!(
3747            router.counters.snapshot()["client_egress_close_delivery_failed"],
3748            0
3749        );
3750    }
3751
3752    #[tokio::test]
3753    async fn oversized_push_closes_client_with_precise_warn() {
3754        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3755        let (router, _sink, mut rx, ctx, routes, mut close) = multi_route_client(
3756            "push-oversize-provider",
3757            ConnectionId::new(86),
3758            ConnectionId::new(87),
3759            2,
3760        )
3761        .await;
3762        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3763        router
3764            .route_for_connection(
3765                &ctx,
3766                Frame::build(
3767                    FrameType::Push,
3768                    Flags::new(false, Priority::Interactive, false),
3769                    routes[0].module_channel,
3770                    routes[0].module_epoch,
3771                    0,
3772                    vec![b'p'; limit - subc_protocol::HEADER_LEN + 1],
3773                )
3774                .unwrap(),
3775            )
3776            .await
3777            .unwrap();
3778        let reason = close
3779            .try_recv()
3780            .expect("unsolicited oversize still closes the client");
3781        assert!(reason
3782            .to_string()
3783            .contains("frame_too_large: oversized push"));
3784        assert!(
3785            rx.try_recv().is_err(),
3786            "no part of the oversized push is forwarded"
3787        );
3788        let captured = test_log::captured_logs(&logs);
3789        let warnings: Vec<_> = captured
3790            .lines()
3791            .filter(|line| line.contains("WARN"))
3792            .collect();
3793        assert_eq!(warnings.len(), 1, "{captured}");
3794        let warning = warnings[0];
3795        for expected in [
3796            "oversized push".to_string(),
3797            "module_id=\"push-oversize-provider\"".to_string(),
3798            "principals=direct".to_string(),
3799            format!("client_channel={}", routes[0].client_channel),
3800            format!("size={}", limit + 1),
3801            format!("limit={limit}"),
3802        ] {
3803            assert!(warning.contains(&expected), "missing {expected}: {warning}");
3804        }
3805        assert_eq!(
3806            router.counters.snapshot()["client_egress_close_delivery_failed"],
3807            1
3808        );
3809    }
3810
3811    #[tokio::test]
3812    async fn oversized_stream_and_error_frames_end_request_even_with_queued_traffic() {
3813        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3814            "stream-oversize-provider",
3815            ConnectionId::new(88),
3816            ConnectionId::new(89),
3817            2,
3818        )
3819        .await;
3820        let binding = module_route_for_test(&router, &ctx, &routes[0]);
3821        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3822        for ty in [
3823            FrameType::StreamData,
3824            FrameType::StreamEnd,
3825            FrameType::Error,
3826        ] {
3827            binding.flow.acquire_tagged(401, false).await.unwrap();
3828            sink.try_send(route_frame(
3829                FrameType::Response,
3830                routes[1].client_channel,
3831                routes[1].client_epoch,
3832                402,
3833            ))
3834            .unwrap();
3835            router
3836                .route_for_connection(
3837                    &ctx,
3838                    Frame::build(
3839                        ty,
3840                        Flags::new(false, Priority::Interactive, false),
3841                        routes[0].module_channel,
3842                        routes[0].module_epoch,
3843                        401,
3844                        vec![b's'; limit - subc_protocol::HEADER_LEN + 1],
3845                    )
3846                    .unwrap(),
3847                )
3848                .await
3849                .unwrap();
3850            assert!(close.try_recv().is_err());
3851            assert_eq!(rx.try_recv().unwrap().header.corr, 402);
3852            let error = rx
3853                .try_recv()
3854                .expect("every correlated oversize frame becomes ERROR");
3855            assert_frame_size_error(
3856                &error,
3857                routes[0].client_channel,
3858                routes[0].client_epoch,
3859                401,
3860                limit + 1,
3861            );
3862            if ty == FrameType::StreamData {
3863                // The module is still running the request: it keeps its
3864                // credit until the module's own terminal, which the client,
3865                // already told frame_too_large, never sees.
3866                assert_eq!(binding.flow.drain_in_flight(), 1);
3867                router
3868                    .route_for_connection(
3869                        &ctx,
3870                        route_frame(
3871                            FrameType::StreamEnd,
3872                            routes[0].module_channel,
3873                            routes[0].module_epoch,
3874                            401,
3875                        ),
3876                    )
3877                    .await
3878                    .unwrap();
3879            }
3880            assert_eq!(binding.flow.drain_in_flight(), 0, "{ty:?} ends the request");
3881            assert!(rx.try_recv().is_err());
3882        }
3883    }
3884
3885    /// An awaited send (a control or error reply) is never refused by the byte
3886    /// budget: it parks until the writer frees bytes. If a release could miss a
3887    /// parked sender, that reply would hang for the connection's lifetime, so
3888    /// this pins the wakeup: the send stays parked while the queue is full and
3889    /// completes as soon as one frame leaves it.
3890    #[tokio::test]
3891    async fn awaited_send_parked_behind_a_full_byte_budget_wakes_when_bytes_free() {
3892        let (tx, mut rx) = mpsc::channel(1024);
3893        let sink = FrameSink::with_byte_budget(tx, 2_000);
3894        let mut queued = 0u64;
3895        while sink
3896            .try_send(stream_frame(7, 1, queued, vec![b'x'; 200]))
3897            .is_ok()
3898        {
3899            queued += 1;
3900        }
3901        assert!(queued > 0, "the budget admitted nothing");
3902
3903        let parked = tokio::spawn({
3904            let sink = sink.clone();
3905            async move { sink.send(stream_frame(0, 0, 999, vec![b'r'; 200])).await }
3906        });
3907        tokio::time::sleep(Duration::from_millis(100)).await;
3908        assert!(
3909            !parked.is_finished(),
3910            "the awaited send must wait while the byte budget is full"
3911        );
3912
3913        // The writer takes one frame and drops it, releasing its bytes.
3914        drop(rx.recv().await.expect("a queued frame"));
3915        tokio::time::timeout(Duration::from_secs(2), parked)
3916            .await
3917            .expect("the parked send was never woken after bytes were freed")
3918            .unwrap()
3919            .unwrap();
3920    }
3921
3922    /// A client multiplexing several token streams pauses its reader while the
3923    /// module keeps producing small frames. Far more frames than the old
3924    /// 64-frame queue allowed, but far fewer bytes than the budget, must all be
3925    /// held without closing the connection and delivered in order afterwards.
3926    #[tokio::test]
3927    async fn paused_client_reader_keeps_connection_through_small_frame_burst() {
3928        const ROUTES: usize = 4;
3929        const FRAMES_PER_ROUTE: usize = 250;
3930        let (router, client_sink, mut client_rx, module_ctx, routes, mut close_receiver) =
3931            multi_route_client(
3932                "burst-provider",
3933                ConnectionId::new(60),
3934                ConnectionId::new(61),
3935                ROUTES,
3936            )
3937            .await;
3938
3939        // The reader is paused: nothing is received until every frame is sent.
3940        for seq in 0..FRAMES_PER_ROUTE as u64 {
3941            for (index, route) in routes.iter().enumerate() {
3942                let body = format!("route-{index}-token-{seq:05}-{}", "t".repeat(170));
3943                router
3944                    .route_for_connection(
3945                        &module_ctx,
3946                        stream_frame(
3947                            route.module_channel,
3948                            route.module_epoch,
3949                            seq,
3950                            body.into_bytes(),
3951                        ),
3952                    )
3953                    .await
3954                    .unwrap();
3955            }
3956        }
3957
3958        let backlog = client_sink.backlog();
3959        assert_eq!(backlog.queued_frames, ROUTES * FRAMES_PER_ROUTE);
3960        assert!(backlog.queued_bytes < crate::server::CONNECTION_EGRESS_BYTE_BUDGET);
3961        assert!(
3962            close_receiver.try_recv().is_err(),
3963            "a paused reader under the byte budget must not be closed"
3964        );
3965        assert_eq!(
3966            router.counters.snapshot()["client_egress_close_delivery_failed"],
3967            0
3968        );
3969
3970        // The reader resumes: every frame arrives, in order within each route.
3971        let mut next_seq = vec![0u64; ROUTES];
3972        for _ in 0..ROUTES * FRAMES_PER_ROUTE {
3973            let frame = client_rx.try_recv().expect("every queued frame arrives");
3974            let index = routes
3975                .iter()
3976                .position(|route| route.client_channel == frame.header.channel)
3977                .expect("frame arrives on one of the bound client channels");
3978            assert_eq!(frame.header.corr, next_seq[index], "route {index} order");
3979            let expected_prefix = format!("route-{index}-token-{:05}-", next_seq[index]);
3980            assert!(frame.body.starts_with(expected_prefix.as_bytes()));
3981            next_seq[index] += 1;
3982        }
3983        assert!(client_rx.try_recv().is_err());
3984        assert_eq!(next_seq, vec![FRAMES_PER_ROUTE as u64; ROUTES]);
3985        assert_eq!(client_sink.backlog().queued_bytes, 0);
3986    }
3987
3988    /// A client that never reads exhausts its byte budget and the oldest
3989    /// frame's 250 ms grace, then closes with one header-only diagnosis.
3990    #[tokio::test(start_paused = true)]
3991    async fn never_reading_client_is_closed_at_byte_budget_with_warn_diagnosis() {
3992        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3993        const BODY: usize = 16 * 1024;
3994        let (router, client_sink, _client_rx, module_ctx, routes, mut close_receiver) =
3995            multi_route_client(
3996                "stuck-reader-provider",
3997                ConnectionId::new(70),
3998                ConnectionId::new(71),
3999                2,
4000            )
4001            .await;
4002
4003        let mut admitted = 0usize;
4004        let mut sent = 0u64;
4005        let started = tokio::time::Instant::now();
4006        while router.counters.snapshot()["client_egress_close_delivery_failed"] == 0 {
4007            assert!(sent < 1_000, "the byte budget never refused a frame");
4008            let route = &routes[(sent % 2) as usize];
4009            router
4010                .route_for_connection(
4011                    &module_ctx,
4012                    stream_frame(
4013                        route.module_channel,
4014                        route.module_epoch,
4015                        sent,
4016                        vec![b'z'; BODY],
4017                    ),
4018                )
4019                .await
4020                .unwrap();
4021            sent += 1;
4022            admitted = client_sink.backlog().queued_frames;
4023        }
4024        assert_eq!(
4025            started.elapsed(),
4026            crate::server::CONNECTION_EGRESS_STALL_GRACE
4027        );
4028        // The budget, not the frame-count backstop, did the refusing.
4029        let frame_bytes = subc_protocol::HEADER_LEN + BODY;
4030        assert_eq!(
4031            admitted,
4032            crate::server::CONNECTION_EGRESS_BYTE_BUDGET / frame_bytes
4033        );
4034        let reason = close_receiver
4035            .try_recv()
4036            .expect("the client connection must be asked to close");
4037        assert!(reason
4038            .to_string()
4039            .contains("module_to_client_delivery_failed"));
4040
4041        // A second refused frame for the same connection adds no second WARN.
4042        router
4043            .route_for_connection(
4044                &module_ctx,
4045                stream_frame(
4046                    routes[0].module_channel,
4047                    routes[0].module_epoch,
4048                    sent,
4049                    vec![b'z'; BODY],
4050                ),
4051            )
4052            .await
4053            .unwrap();
4054
4055        let captured = test_log::captured_logs(&logs);
4056        let warn_lines = captured
4057            .lines()
4058            .filter(|line| {
4059                line.contains("closing client connection: its egress queue could not take a frame")
4060            })
4061            .collect::<Vec<_>>();
4062        assert_eq!(warn_lines.len(), 1, "exactly one WARN, got: {captured}");
4063        let line = warn_lines[0];
4064        assert!(line.contains("WARN"), "{line}");
4065        assert!(line.contains("connection_id=71"), "{line}");
4066        assert!(
4067            line.contains("module_id=\"stuck-reader-provider\""),
4068            "{line}"
4069        );
4070        assert!(line.contains("client_channel="), "{line}");
4071        assert!(line.contains("principals=direct"), "{line}");
4072        let queued_bytes: usize = line
4073            .split("queued_bytes=")
4074            .nth(1)
4075            .and_then(|rest| rest.split_whitespace().next())
4076            .and_then(|value| value.parse().ok())
4077            .expect("queued_bytes is logged");
4078        assert_eq!(queued_bytes, admitted * frame_bytes);
4079        assert!(
4080            line.contains(&format!("queued_frames={admitted}")),
4081            "{line}"
4082        );
4083        assert!(line.contains("oldest_queued_ms="), "{line}");
4084        assert!(line.contains("oldest_queued_ms=250"), "{line}");
4085        assert!(line.contains("frame_type=Some(StreamData)"), "{line}");
4086        assert!(
4087            line.contains(&format!(
4088                "frame_flags=Some({})",
4089                Flags::new(false, Priority::Interactive, false).0
4090            )),
4091            "{line}"
4092        );
4093        assert!(
4094            line.contains("close_cause=\"waited_250_ms_without_room\""),
4095            "{line}"
4096        );
4097        assert!(
4098            !line.contains(&"z".repeat(20)),
4099            "body bytes must never be logged: {line}"
4100        );
4101    }
4102
4103    fn route_frame(ty: FrameType, channel: u16, epoch: u32, corr: u64) -> Frame {
4104        Frame::build(
4105            ty,
4106            Flags::new(false, Priority::Interactive, false),
4107            channel,
4108            epoch,
4109            corr,
4110            if ty == FrameType::Request || ty == FrameType::Response {
4111                b"route-body".to_vec()
4112            } else {
4113                Vec::new()
4114            },
4115        )
4116        .unwrap()
4117    }
4118
4119    type DynamicRouteFixture = (
4120        Router,
4121        Arc<ForwardingTable>,
4122        RouteCtx,
4123        mpsc::Receiver<crate::router::OutboundFrame>,
4124        RouteCtx,
4125        mpsc::Receiver<crate::router::OutboundFrame>,
4126        mpsc::Receiver<crate::router::OutboundFrame>,
4127        crate::forwarding::PendingRouteBindRelay,
4128    );
4129
4130    fn dynamic_route_fixture(commit: bool) -> DynamicRouteFixture {
4131        dynamic_route_fixture_with_busy(commit, false)
4132    }
4133
4134    fn dynamic_route_fixture_with_busy(commit: bool, busy_refusals: bool) -> DynamicRouteFixture {
4135        let forwarding = Arc::new(ForwardingTable::default());
4136        let control = Arc::new(crate::ControlHandler::with_forwarding(
4137            Arc::new(crate::Registry::default()),
4138            Arc::clone(&forwarding),
4139        ));
4140        let router = Router::with_control_handler(control);
4141        let module_connection = ConnectionId::new(500);
4142        let client_connection = ConnectionId::new(501);
4143        let (module_tx, module_rx) = mpsc::channel(if busy_refusals { 64 } else { 8 });
4144        forwarding
4145            .register_module_connection(
4146                module_connection,
4147                "epoch-router".into(),
4148                2,
4149                Concurrency::ModuleManaged,
4150                FrameSink::new(module_tx),
4151            )
4152            .unwrap();
4153        let (client_tx, client_rx) = mpsc::channel(if busy_refusals { 64 } else { 8 });
4154        let client_sink = FrameSink::new(client_tx);
4155        let pending = forwarding
4156            .begin_route_bind_relay_with_busy_for_test(
4157                client_connection,
4158                client_sink.clone(),
4159                700,
4160                "epoch-router",
4161                busy_refusals,
4162            )
4163            .unwrap();
4164        if commit {
4165            forwarding
4166                .complete_pending_relay(
4167                    module_connection,
4168                    pending.corr,
4169                    RouteBindRelayOutcome::Accepted,
4170                )
4171                .unwrap();
4172        }
4173        let (module_egress_tx, module_egress_rx) = mpsc::channel(8);
4174        (
4175            router,
4176            forwarding,
4177            RouteCtx {
4178                connection_id: client_connection,
4179                egress: client_sink,
4180            },
4181            client_rx,
4182            RouteCtx {
4183                connection_id: module_connection,
4184                egress: FrameSink::new(module_egress_tx),
4185            },
4186            module_egress_rx,
4187            module_rx,
4188            pending,
4189        )
4190    }
4191
4192    #[tokio::test]
4193    async fn route_epochs_validate_both_directions_and_rewrite_to_peer_handle() {
4194        let (
4195            router,
4196            _forwarding,
4197            client_ctx,
4198            mut client_rx,
4199            module_ctx,
4200            _module_egress_rx,
4201            mut module_rx,
4202            pending,
4203        ) = dynamic_route_fixture(true);
4204        let route_open = client_rx.recv().await.unwrap();
4205        assert_eq!(route_open.header.corr, 700);
4206
4207        router
4208            .route_for_connection(
4209                &client_ctx,
4210                route_frame(
4211                    FrameType::Request,
4212                    pending.client_channel,
4213                    pending.client_epoch,
4214                    701,
4215                ),
4216            )
4217            .await
4218            .unwrap();
4219        let forwarded = module_rx.recv().await.unwrap();
4220        assert_eq!(forwarded.header.channel, pending.module_channel);
4221        assert_eq!(forwarded.header.epoch, pending.module_epoch);
4222
4223        router
4224            .route_for_connection(
4225                &module_ctx,
4226                route_frame(
4227                    FrameType::Response,
4228                    pending.module_channel,
4229                    pending.module_epoch,
4230                    701,
4231                ),
4232            )
4233            .await
4234            .unwrap();
4235        let delivered = client_rx.recv().await.unwrap();
4236        assert_eq!(delivered.header.channel, pending.client_channel);
4237        assert_eq!(delivered.header.epoch, pending.client_epoch);
4238
4239        router
4240            .route_for_connection(
4241                &client_ctx,
4242                route_frame(
4243                    FrameType::Request,
4244                    pending.client_channel,
4245                    pending.client_epoch + 1,
4246                    702,
4247                ),
4248            )
4249            .await
4250            .unwrap();
4251        router
4252            .route_for_connection(
4253                &module_ctx,
4254                route_frame(
4255                    FrameType::Response,
4256                    pending.module_channel,
4257                    pending.module_epoch + 1,
4258                    703,
4259                ),
4260            )
4261            .await
4262            .unwrap();
4263        let stale_error = client_rx.recv().await.unwrap();
4264        assert_eq!(stale_error.header.ty, FrameType::Error);
4265        assert_eq!(stale_error.header.channel, pending.client_channel);
4266        assert_eq!(stale_error.header.epoch, pending.client_epoch + 1);
4267        assert_eq!(stale_error.header.corr, 702);
4268        let body: ErrorBody = serde_json::from_slice(&stale_error.body).unwrap();
4269        assert_eq!(body.code, "stale_route_epoch");
4270        assert!(module_rx.try_recv().is_err());
4271        assert!(client_rx.try_recv().is_err());
4272        let counters = router.counters.snapshot();
4273        assert_eq!(counters["client_frames_dropped_stale_route"], 1);
4274        assert_eq!(counters["module_frames_dropped_no_route"], 1);
4275    }
4276
4277    #[tokio::test]
4278    async fn accepted_route_publishes_route_open_before_immediate_reverse_request() {
4279        let (
4280            router,
4281            _,
4282            _client_ctx,
4283            mut client_rx,
4284            module_ctx,
4285            _module_egress_rx,
4286            _module_rx,
4287            pending,
4288        ) = dynamic_route_fixture(true);
4289        router
4290            .route_for_connection(
4291                &module_ctx,
4292                route_frame(
4293                    FrameType::Request,
4294                    pending.module_channel,
4295                    pending.module_epoch,
4296                    800,
4297                ),
4298            )
4299            .await
4300            .unwrap();
4301
4302        let first = client_rx.recv().await.unwrap();
4303        let second = client_rx.recv().await.unwrap();
4304        assert_eq!(first.header.channel, 0);
4305        assert_eq!(first.header.corr, 700);
4306        assert_eq!(second.header.channel, pending.client_channel);
4307        assert_eq!(second.header.epoch, pending.client_epoch);
4308        assert_eq!(second.header.corr, 800);
4309    }
4310
4311    #[tokio::test]
4312    async fn reserved_slot_ingress_errors_only_matching_client_requests() {
4313        let (
4314            router,
4315            _forwarding,
4316            client_ctx,
4317            mut client_rx,
4318            _module_ctx,
4319            _module_egress_rx,
4320            mut module_rx,
4321            pending,
4322        ) = dynamic_route_fixture(false);
4323        router
4324            .route_for_connection(
4325                &client_ctx,
4326                route_frame(
4327                    FrameType::Request,
4328                    pending.client_channel,
4329                    pending.client_epoch,
4330                    900,
4331                ),
4332            )
4333            .await
4334            .unwrap();
4335        let error = client_rx.recv().await.unwrap();
4336        assert_eq!(error.header.ty, FrameType::Error);
4337        assert_eq!(error.header.channel, pending.client_channel);
4338        assert_eq!(error.header.epoch, pending.client_epoch);
4339        assert_eq!(error.header.corr, 900);
4340
4341        router
4342            .route_for_connection(
4343                &client_ctx,
4344                route_frame(
4345                    FrameType::Response,
4346                    pending.client_channel,
4347                    pending.client_epoch,
4348                    901,
4349                ),
4350            )
4351            .await
4352            .unwrap();
4353        router
4354            .route_for_connection(
4355                &client_ctx,
4356                route_frame(
4357                    FrameType::Request,
4358                    pending.client_channel,
4359                    pending.client_epoch + 1,
4360                    902,
4361                ),
4362            )
4363            .await
4364            .unwrap();
4365        let stale_error = client_rx.recv().await.unwrap();
4366        assert_eq!(stale_error.header.ty, FrameType::Error);
4367        assert_eq!(stale_error.header.channel, pending.client_channel);
4368        assert_eq!(stale_error.header.epoch, pending.client_epoch + 1);
4369        assert_eq!(stale_error.header.corr, 902);
4370        let body: ErrorBody = serde_json::from_slice(&stale_error.body).unwrap();
4371        assert_eq!(body.code, "stale_route_epoch");
4372        assert!(module_rx.try_recv().is_err());
4373        let counters = router.counters.snapshot();
4374        assert_eq!(counters["client_frames_dropped_stale_route"], 1);
4375        assert_eq!(counters["module_frames_dropped_no_route"], 0);
4376    }
4377
4378    #[tokio::test]
4379    async fn dropped_module_route_goodbye_increments_counter() {
4380        let (
4381            router,
4382            _forwarding,
4383            client_ctx,
4384            mut client_rx,
4385            _module_ctx,
4386            _module_egress_rx,
4387            mut module_rx,
4388            pending,
4389        ) = dynamic_route_fixture(true);
4390        let _ = client_rx.recv().await;
4391        module_rx.close();
4392
4393        router
4394            .route_for_connection(
4395                &client_ctx,
4396                route_frame(
4397                    FrameType::Goodbye,
4398                    pending.client_channel,
4399                    pending.client_epoch,
4400                    999,
4401                ),
4402            )
4403            .await
4404            .unwrap();
4405
4406        let counters = router.counters.snapshot();
4407        assert_eq!(counters["goodbye_relay_module_dropped"], 1);
4408        assert_eq!(
4409            counters["goodbye_relay_module_dropped_by_module"],
4410            serde_json::json!({ "epoch-router": 1 })
4411        );
4412        assert_eq!(counters["route_released_epoch_fenced"], 1);
4413    }
4414
4415    #[tokio::test]
4416    async fn module_request_on_stale_epoch_receives_stale_route_epoch() {
4417        let (
4418            router,
4419            _forwarding,
4420            _client_ctx,
4421            _client_rx,
4422            module_ctx,
4423            mut module_egress_rx,
4424            mut module_rx,
4425            pending,
4426        ) = dynamic_route_fixture(true);
4427
4428        router
4429            .route_for_connection(
4430                &module_ctx,
4431                route_frame(
4432                    FrameType::Request,
4433                    pending.module_channel,
4434                    pending.module_epoch + 1,
4435                    1_000,
4436                ),
4437            )
4438            .await
4439            .unwrap();
4440
4441        let error = module_egress_rx.try_recv().unwrap();
4442        assert_eq!(error.header.ty, FrameType::Error);
4443        assert_eq!(error.header.channel, pending.module_channel);
4444        assert_eq!(error.header.epoch, pending.module_epoch + 1);
4445        assert_eq!(error.header.corr, 1_000);
4446        let body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
4447        assert_eq!(body.code, "stale_route_epoch");
4448        assert!(module_rx.try_recv().is_err());
4449        let counters = router.counters.snapshot();
4450        assert_eq!(counters["module_requests_dropped_stale_route"], 1);
4451        assert_eq!(counters["module_frames_dropped_no_route"], 0);
4452    }
4453
4454    #[tokio::test(start_paused = true)]
4455    async fn stale_epoch_drop_warns_once_per_minute_with_suppressed_count() {
4456        let (output, _guard) = test_log::log_capture(tracing::Level::WARN);
4457        let (
4458            router,
4459            _forwarding,
4460            client_ctx,
4461            mut client_rx,
4462            _module_ctx,
4463            _module_egress_rx,
4464            mut module_rx,
4465            pending,
4466        ) = dynamic_route_fixture(true);
4467        let _ = client_rx.recv().await;
4468        for corr in 1..=3 {
4469            router
4470                .route_for_connection(
4471                    &client_ctx,
4472                    route_frame(
4473                        FrameType::Request,
4474                        pending.client_channel,
4475                        pending.client_epoch + 1,
4476                        corr,
4477                    ),
4478                )
4479                .await
4480                .unwrap();
4481            assert_eq!(client_rx.recv().await.unwrap().header.ty, FrameType::Error);
4482        }
4483        assert!(module_rx.try_recv().is_err());
4484        let logs = test_log::captured_logs(&output);
4485        assert_eq!(
4486            logs.matches("dropping data-plane frame").count(),
4487            1,
4488            "{logs}"
4489        );
4490        assert!(logs.contains("WARN"), "{logs}");
4491        assert!(
4492            logs.contains(&format!("connection_id={}", client_ctx.connection_id.get())),
4493            "{logs}"
4494        );
4495        assert!(
4496            logs.contains(&format!("channel={}", pending.client_channel)),
4497            "{logs}"
4498        );
4499        assert!(
4500            logs.contains(&format!("epoch={}", pending.client_epoch + 1)),
4501            "{logs}"
4502        );
4503        assert!(
4504            logs.contains("client_to_module") && logs.contains("stale_epoch"),
4505            "{logs}"
4506        );
4507        assert!(logs.contains("suppressed=0"), "{logs}");
4508
4509        tokio::time::advance(Duration::from_secs(60)).await;
4510        router
4511            .route_for_connection(
4512                &client_ctx,
4513                route_frame(
4514                    FrameType::Request,
4515                    pending.client_channel,
4516                    pending.client_epoch + 2,
4517                    4,
4518                ),
4519            )
4520            .await
4521            .unwrap();
4522        let logs = test_log::captured_logs(&output);
4523        assert_eq!(
4524            logs.matches("dropping data-plane frame").count(),
4525            2,
4526            "{logs}"
4527        );
4528        assert!(logs.contains("suppressed=2"), "{logs}");
4529    }
4530
4531    #[tokio::test]
4532    async fn module_request_on_reserved_or_absent_route_receives_unknown_channel() {
4533        let (
4534            reserved_router,
4535            _forwarding,
4536            _client_ctx,
4537            _client_rx,
4538            reserved_module_ctx,
4539            mut reserved_module_egress_rx,
4540            _module_rx,
4541            reserved,
4542        ) = dynamic_route_fixture(false);
4543        reserved_router
4544            .route_for_connection(
4545                &reserved_module_ctx,
4546                route_frame(
4547                    FrameType::Request,
4548                    reserved.module_channel,
4549                    reserved.module_epoch,
4550                    1_001,
4551                ),
4552            )
4553            .await
4554            .unwrap();
4555        let reserved_error = reserved_module_egress_rx.try_recv().unwrap();
4556        let reserved_body: ErrorBody = serde_json::from_slice(&reserved_error.body).unwrap();
4557        assert_eq!(reserved_error.header.ty, FrameType::Error);
4558        assert_eq!(reserved_error.header.channel, reserved.module_channel);
4559        assert_eq!(reserved_error.header.epoch, reserved.module_epoch);
4560        assert_eq!(reserved_error.header.corr, 1_001);
4561        assert_eq!(reserved_body.code, "unknown_channel");
4562        assert_eq!(
4563            reserved_router.counters.snapshot()["module_requests_dropped_stale_route"],
4564            1
4565        );
4566
4567        let (
4568            absent_router,
4569            _forwarding,
4570            _client_ctx,
4571            _client_rx,
4572            absent_module_ctx,
4573            mut absent_module_egress_rx,
4574            _module_rx,
4575            absent,
4576        ) = dynamic_route_fixture(false);
4577        absent_router
4578            .route_for_connection(
4579                &absent_module_ctx,
4580                route_frame(
4581                    FrameType::Request,
4582                    absent.module_channel + 1,
4583                    absent.module_epoch,
4584                    1_002,
4585                ),
4586            )
4587            .await
4588            .unwrap();
4589        let absent_error = absent_module_egress_rx.try_recv().unwrap();
4590        let absent_body: ErrorBody = serde_json::from_slice(&absent_error.body).unwrap();
4591        assert_eq!(absent_error.header.ty, FrameType::Error);
4592        assert_eq!(absent_error.header.channel, absent.module_channel + 1);
4593        assert_eq!(absent_error.header.epoch, absent.module_epoch);
4594        assert_eq!(absent_error.header.corr, 1_002);
4595        assert_eq!(absent_body.code, "unknown_channel");
4596        assert_eq!(
4597            absent_router.counters.snapshot()["module_requests_dropped_stale_route"],
4598            1
4599        );
4600    }
4601
4602    #[tokio::test]
4603    async fn non_request_module_frame_on_dead_route_is_counted_without_error() {
4604        let (
4605            router,
4606            forwarding,
4607            client_ctx,
4608            mut client_rx,
4609            module_ctx,
4610            mut module_egress_rx,
4611            mut module_rx,
4612            pending,
4613        ) = dynamic_route_fixture(true);
4614        let (other_module_tx, _other_module_rx) = mpsc::channel(8);
4615        forwarding
4616            .register_module_connection(
4617                ConnectionId::new(502),
4618                "other-module".into(),
4619                2,
4620                Concurrency::ModuleManaged,
4621                FrameSink::new(other_module_tx),
4622            )
4623            .unwrap();
4624        let _ = client_rx.recv().await.unwrap();
4625
4626        router
4627            .route_for_connection(
4628                &client_ctx,
4629                route_frame(
4630                    FrameType::Goodbye,
4631                    pending.client_channel,
4632                    pending.client_epoch,
4633                    1_003,
4634                ),
4635            )
4636            .await
4637            .unwrap();
4638        let _ = module_rx.recv().await.unwrap();
4639
4640        router
4641            .route_for_connection(
4642                &module_ctx,
4643                route_frame(
4644                    FrameType::StreamData,
4645                    pending.module_channel,
4646                    pending.module_epoch,
4647                    1_004,
4648                ),
4649            )
4650            .await
4651            .unwrap();
4652
4653        // No ERROR goes back for a non-request frame. The one reply is the
4654        // route GOODBYE telling the module to let go of the released route.
4655        let reply = module_egress_rx.try_recv().unwrap();
4656        assert_eq!(reply.header.ty, FrameType::Goodbye);
4657        assert!(module_egress_rx.try_recv().is_err());
4658        let counters = router.counters.snapshot();
4659        assert_eq!(counters["module_frames_dropped_no_route"], 1);
4660        assert_eq!(
4661            counters["module_frames_dropped_no_route_by_module"],
4662            serde_json::json!({ "epoch-router": 1 })
4663        );
4664        assert_eq!(counters["module_requests_dropped_stale_route"], 0);
4665    }
4666
4667    /// Drain whatever the module connection's queue holds right now, the way a
4668    /// module's reader would before it stalls.
4669    fn drain_now(rx: &mut mpsc::Receiver<OutboundFrame>) {
4670        while rx.try_recv().is_ok() {}
4671    }
4672
4673    /// A module that stops reading for a moment when a client closes one of
4674    /// its routes still learns the route is gone: the GOODBYE its full egress
4675    /// queue refused is delivered as soon as it reads again, rather than
4676    /// dropped, which would leave the module holding the route for the rest of
4677    /// its connection.
4678    #[tokio::test]
4679    async fn route_goodbye_refused_by_stalled_module_is_delivered_when_it_resumes_reading() {
4680        const BUDGET: usize = 4_096;
4681        let forwarding = Arc::new(ForwardingTable::default());
4682        let control = Arc::new(ControlHandler::with_forwarding(
4683            Arc::new(Registry::default()),
4684            Arc::clone(&forwarding),
4685        ));
4686        let router = Router::with_control_handler(control);
4687        let module_connection = ConnectionId::new(80);
4688        let client_connection = ConnectionId::new(81);
4689        let (module_tx, mut module_rx) = mpsc::channel(64);
4690        let module_sink = FrameSink::with_byte_budget(module_tx, BUDGET);
4691        forwarding
4692            .register_module_connection(
4693                module_connection,
4694                "stalled-provider".into(),
4695                2,
4696                Concurrency::ModuleManaged,
4697                module_sink.clone(),
4698            )
4699            .unwrap();
4700        let (client_tx, mut client_rx) = mpsc::channel(8);
4701        let client_sink = FrameSink::new(client_tx);
4702        let pending = forwarding
4703            .begin_route_bind_relay_for_test(
4704                client_connection,
4705                client_sink.clone(),
4706                1_100,
4707                "stalled-provider",
4708            )
4709            .unwrap();
4710        forwarding
4711            .complete_pending_relay(
4712                module_connection,
4713                pending.corr,
4714                RouteBindRelayOutcome::Accepted,
4715            )
4716            .unwrap();
4717        let _ = client_rx.recv().await.unwrap();
4718        drain_now(&mut module_rx);
4719
4720        // The module stalls: its queue holds more than the byte budget, so the
4721        // queue refuses anything further.
4722        module_sink
4723            .try_send(stream_frame(9, 1, 0, vec![b'f'; BUDGET]))
4724            .unwrap();
4725        assert!(module_sink
4726            .try_send(stream_frame(9, 1, 1, Vec::new()))
4727            .is_err());
4728
4729        let client_ctx = RouteCtx {
4730            connection_id: client_connection,
4731            egress: client_sink,
4732        };
4733        router
4734            .route_for_connection(
4735                &client_ctx,
4736                route_frame(
4737                    FrameType::Goodbye,
4738                    pending.client_channel,
4739                    pending.client_epoch,
4740                    1_101,
4741                ),
4742            )
4743            .await
4744            .unwrap();
4745        tokio::task::yield_now().await;
4746        assert_eq!(
4747            router.counters.snapshot()["goodbye_relay_module_dropped"],
4748            0,
4749            "a GOODBYE refused by a momentarily full module queue must not be dropped"
4750        );
4751
4752        // The module reads again: the filler comes off, then the GOODBYE.
4753        let filler = module_rx.recv().await.unwrap();
4754        assert_eq!(filler.header.ty, FrameType::StreamData);
4755        drop(filler);
4756        let goodbye = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
4757            .await
4758            .expect("the refused GOODBYE must be delivered once the module frees room")
4759            .unwrap();
4760        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
4761        assert_eq!(goodbye.header.channel, pending.module_channel);
4762        assert_eq!(goodbye.header.epoch, pending.module_epoch);
4763        assert_eq!(
4764            router.counters.snapshot()["goodbye_relay_module_dropped"],
4765            0
4766        );
4767    }
4768
4769    /// A module still sending on a route the daemon released is told, with a
4770    /// route GOODBYE for exactly the (channel, epoch) it sent on. The same
4771    /// happens for a stale epoch on a channel whose route moved on and for a
4772    /// channel that never had a route; only the first is counted as traffic on
4773    /// a released route.
4774    #[tokio::test]
4775    async fn module_frame_on_route_the_daemon_does_not_hold_is_answered_with_goodbye() {
4776        let (
4777            router,
4778            _forwarding,
4779            client_ctx,
4780            mut client_rx,
4781            module_ctx,
4782            mut module_egress_rx,
4783            mut module_rx,
4784            pending,
4785        ) = dynamic_route_fixture(true);
4786        let _ = client_rx.recv().await.unwrap();
4787        router
4788            .route_for_connection(
4789                &client_ctx,
4790                route_frame(
4791                    FrameType::Goodbye,
4792                    pending.client_channel,
4793                    pending.client_epoch,
4794                    1_200,
4795                ),
4796            )
4797            .await
4798            .unwrap();
4799        drain_now(&mut module_rx);
4800
4801        let cases = [
4802            // Released route: the daemon allocated this (channel, epoch).
4803            (pending.module_channel, pending.module_epoch),
4804            // A channel the daemon never allocated on this connection.
4805            (pending.module_channel + 1, 1),
4806        ];
4807        for (channel, epoch) in cases {
4808            router
4809                .route_for_connection(
4810                    &module_ctx,
4811                    route_frame(FrameType::StreamData, channel, epoch, 1_201),
4812                )
4813                .await
4814                .unwrap();
4815            let reply = module_egress_rx
4816                .try_recv()
4817                .expect("a frame on a route the daemon does not hold is answered");
4818            assert_eq!(reply.header.ty, FrameType::Goodbye);
4819            assert_eq!(reply.header.channel, channel);
4820            assert_eq!(reply.header.epoch, epoch);
4821            assert_eq!(reply.header.corr, 0);
4822            assert!(module_egress_rx.try_recv().is_err());
4823        }
4824
4825        // A GOODBYE from the module for a route the daemon already released
4826        // is not answered: the module is letting go already.
4827        router
4828            .route_for_connection(
4829                &module_ctx,
4830                route_frame(FrameType::Goodbye, pending.module_channel + 2, 1, 0),
4831            )
4832            .await
4833            .unwrap();
4834        assert!(module_egress_rx.try_recv().is_err());
4835
4836        let counters = router.counters.snapshot();
4837        assert_eq!(counters["module_frames_dropped_no_route"], 3);
4838        assert_eq!(counters["module_frames_dropped_released_route"], 1);
4839        assert_eq!(
4840            counters["module_frames_dropped_released_route_by_module"],
4841            serde_json::json!({ "epoch-router": 1 })
4842        );
4843        assert_eq!(counters["module_orphan_route_goodbyes_sent"], 2);
4844    }
4845
4846    /// A chatty orphan (a streaming module still producing on a route it
4847    /// missed the GOODBYE for) is answered once per interval, not once per
4848    /// frame, and answered again once the interval has passed.
4849    #[tokio::test(start_paused = true)]
4850    async fn burst_of_orphan_module_frames_is_answered_once_per_interval() {
4851        let (
4852            router,
4853            _forwarding,
4854            client_ctx,
4855            mut client_rx,
4856            module_ctx,
4857            mut module_egress_rx,
4858            mut module_rx,
4859            pending,
4860        ) = dynamic_route_fixture(true);
4861        let _ = client_rx.recv().await.unwrap();
4862        router
4863            .route_for_connection(
4864                &client_ctx,
4865                route_frame(
4866                    FrameType::Goodbye,
4867                    pending.client_channel,
4868                    pending.client_epoch,
4869                    1_300,
4870                ),
4871            )
4872            .await
4873            .unwrap();
4874        drain_now(&mut module_rx);
4875
4876        let send_burst = |corr: u64| {
4877            route_frame(
4878                FrameType::StreamData,
4879                pending.module_channel,
4880                pending.module_epoch,
4881                corr,
4882            )
4883        };
4884        for corr in 0..20 {
4885            router
4886                .route_for_connection(&module_ctx, send_burst(corr))
4887                .await
4888                .unwrap();
4889        }
4890        let mut replies = 0;
4891        while let Ok(reply) = module_egress_rx.try_recv() {
4892            assert_eq!(reply.header.ty, FrameType::Goodbye);
4893            replies += 1;
4894        }
4895        assert_eq!(replies, 1, "a burst within the interval gets one GOODBYE");
4896
4897        tokio::time::advance(ORPHAN_ROUTE_GOODBYE_INTERVAL).await;
4898        router
4899            .route_for_connection(&module_ctx, send_burst(20))
4900            .await
4901            .unwrap();
4902        let retry = module_egress_rx
4903            .try_recv()
4904            .expect("the first orphan frame after the interval is answered again");
4905        assert_eq!(retry.header.channel, pending.module_channel);
4906        assert_eq!(retry.header.epoch, pending.module_epoch);
4907
4908        let counters = router.counters.snapshot();
4909        assert_eq!(counters["module_frames_dropped_no_route"], 21);
4910        assert_eq!(counters["module_orphan_route_goodbyes_sent"], 2);
4911    }
4912
4913    /// The rate-limit memory is per connection and goes away with it.
4914    #[test]
4915    fn orphan_goodbye_rate_limit_state_is_released_with_the_connection() {
4916        let router = Router::with_default_self_handler();
4917        let connection = router.begin_connection();
4918        let id = connection.id();
4919        assert!(router.orphan_goodbyes.claim(id, 7));
4920        assert!(!router.orphan_goodbyes.claim(id, 7));
4921        assert!(router.orphan_goodbyes.claim(id, 8));
4922        drop(connection);
4923        assert!(router
4924            .orphan_goodbyes
4925            .last_sent
4926            .lock()
4927            .unwrap()
4928            .get(&id)
4929            .is_none());
4930    }
4931
4932    #[test]
4933    fn channel_zero_cannot_be_registered_as_backend() {
4934        let mut router = Router::with_default_self_handler();
4935
4936        let err = router.register_backend(0, EchoBackend).unwrap_err();
4937
4938        assert_eq!(err, RouterError::ReservedChannelZero);
4939    }
4940
4941    mod audit_findings {
4942        use super::*;
4943        include!("router_audit_tests.rs");
4944    }
4945}