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