Skip to main content

subc_daemon/
forwarding.rs

1//! Forwarding snapshots and route publication. Spawn/claim publication takes
2//! the spawn transition, claim state/index, then forwarding, in that order.
3//! Bind commits read only the launch watch, never the spawn transition lock.
4//! No forwarding guard is held while awaiting a module.
5//! HELLO publication holds Registry before ForwardingTable::inner so an ACK
6//! cannot be observed before registry publication. Code holding inner must not
7//! take the registry lock, including through a callback.
8//!
9//! Spawn authority: an authority change takes the spawn's authority record
10//! state, then `inner` (see `crate::spawn_authority`). Code holding `inner`
11//! never takes a record's authority state; it reads only the record's
12//! immutable identity and the epochs and first-party marks published into
13//! `spawn_epochs` and `spawn_marks`.
14
15use std::{
16    collections::{BTreeMap, HashMap, HashSet},
17    error::Error,
18    fmt,
19    sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard},
20    time::Duration,
21};
22
23use subc_control::{
24    ClientControlResponse, RouteCloseReason, RouteOpenReplyExt, RouteOpenTarget,
25    RouteOpenTargetKind,
26};
27use subc_protocol::{
28    manifest::Concurrency,
29    session::{LiveRoot, ModuleControlResponse, ModuleControlResponseToModule},
30    ErrorBody, Flags, FrameType, Principal, Priority,
31};
32use tokio::sync::{oneshot, Semaphore};
33use tokio::time::Instant;
34use tracing::{debug, info, warn};
35
36use crate::spawn_authority::ApprovedDeclarations;
37use crate::{
38    control::{RouteBindBreakers, RouteBindConcurrency},
39    observability::DaemonCounters,
40    registry::ConnectionId,
41    router::FrameSink,
42    scopes::{BoundScope, ScopeDrain, ScopeTag, ScopeTagChange},
43    spawn_authority::{AuthorityPair, SpawnAuthorityRecord, SpawnKey},
44    Frame, ProjectRootId,
45};
46
47/// Default per-channel request-credit window for modules that schedule internally.
48const DEFAULT_MODULE_MANAGED_WINDOW: usize = 32;
49
50/// Watches leave eight request credits available for ordinary calls.
51const DEFAULT_MODULE_MANAGED_WATCH_WINDOW: usize = 24;
52
53/// High per-channel cap for stateless modules; this is an OOM guard, not scheduling policy.
54const STATELESS_PARALLEL_WINDOW: usize = 1024;
55
56/// A stopped probe cycle cannot retain its last unanswered correlation forever.
57/// Active endpoints replace the tombstone on their next serial health probe;
58/// this backstop covers endpoints that stop probing altogether.
59const HEALTH_PROBE_TOMBSTONE_TTL: Duration = Duration::from_secs(5 * 60);
60
61/// Module connection identity used in forwarding keys.
62///
63/// The generation is bumped every time a module connection is registered so a future restart cannot
64/// accidentally reuse a stale `(connection_id, route_channel)` binding.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct ModuleEndpointId {
67    pub connection_id: ConnectionId,
68    pub generation: u64,
69}
70
71/// Client-local route key. A route channel is unique only within one client connection.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub(crate) struct ClientRouteKey {
74    pub connection_id: ConnectionId,
75    pub channel: u16,
76}
77
78/// Module-local route key. A route channel is unique only within one live module endpoint.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80pub(crate) struct ModuleRouteKey {
81    pub endpoint: ModuleEndpointId,
82    pub channel: u16,
83}
84
85#[derive(Debug)]
86pub(crate) struct RouteBinding {
87    pub client_connection_id: ConnectionId,
88    pub client_sink: FrameSink,
89    pub client_negotiated_ver: u8,
90    pub client_channel: u16,
91    pub client_epoch: u32,
92    pub module_id: String,
93    pub module_endpoint: ModuleEndpointId,
94    pub module_sink: FrameSink,
95    pub module_negotiated_ver: u8,
96    pub module_channel: u16,
97    pub module_epoch: u32,
98    pub principal: Principal,
99    /// Opener attributes captured at admission for daemon-side prompt policy.
100    #[allow(dead_code)]
101    pub harness: String,
102    /// Only Callosum's exact production claim is retained; never relayed.
103    #[allow(dead_code)]
104    pub build_class: Option<String>,
105    /// Captured at connect, carried through admission; not standing authority.
106    #[allow(dead_code)]
107    pub operator_app: Option<crate::operator_apps::OperatorAppStamp>,
108    pub project_root: Option<ProjectRootId>,
109    pub bound_at: Instant,
110    pub flow: Arc<ChannelFlow>,
111    /// The scope the route was admitted under, with the tag its bind was
112    /// stamped at. A scope change finds the routes to close by it.
113    pub scope: Option<BoundScope>,
114    /// Close reasons this route's opener can decode, captured from route.open.
115    pub accepts_close_reasons: Option<Vec<String>>,
116    /// The opener's spawn and authority epoch when the open was attested;
117    /// `None` for an opener with no supervised spawn.
118    pub caller_authority: Option<AuthorityPair>,
119    /// The serving spawn and its authority epoch when the route was reserved;
120    /// `None` for a prefix or unsupervised target.
121    pub target_authority: Option<AuthorityPair>,
122}
123
124#[cfg(debug_assertions)]
125thread_local! {
126    /// Forwarding guards this thread holds, counted in debug builds.
127    static FORWARDING_GUARDS_HELD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
128}
129
130/// A guard on the forwarding table's state. Debug builds count the guards
131/// each thread holds, so code that must never wait while the forwarding lock
132/// is held can check it with [`assert_forwarding_unlocked`].
133struct InnerGuard<G>(G);
134
135impl<G> InnerGuard<G> {
136    fn new(guard: G) -> Self {
137        #[cfg(debug_assertions)]
138        FORWARDING_GUARDS_HELD.with(|held| held.set(held.get() + 1));
139        Self(guard)
140    }
141}
142
143impl<G> Drop for InnerGuard<G> {
144    fn drop(&mut self) {
145        #[cfg(debug_assertions)]
146        FORWARDING_GUARDS_HELD.with(|held| held.set(held.get().saturating_sub(1)));
147    }
148}
149
150impl<G: std::ops::Deref> std::ops::Deref for InnerGuard<G> {
151    type Target = G::Target;
152    fn deref(&self) -> &Self::Target {
153        &self.0
154    }
155}
156
157impl<G: std::ops::DerefMut> std::ops::DerefMut for InnerGuard<G> {
158    fn deref_mut(&mut self) -> &mut Self::Target {
159        &mut self.0
160    }
161}
162
163/// Panic in a debug build when this thread holds the forwarding lock. The
164/// configuration owner's state and a spawn authority record's state are taken
165/// before the forwarding lock, never under it; their lock functions call this
166/// so a path that inverts the order fails in tests instead of deadlocking.
167pub(crate) fn assert_forwarding_unlocked(what: &str) {
168    #[cfg(debug_assertions)]
169    FORWARDING_GUARDS_HELD.with(|held| {
170        assert_eq!(
171            held.get(),
172            0,
173            "{what} must not be taken while this thread holds the forwarding lock"
174        );
175    });
176    #[cfg(not(debug_assertions))]
177    let _ = what;
178}
179
180/// The spawn authority facts `route.open` hands to the relay reservation.
181#[derive(Debug, Clone, Default)]
182pub(crate) struct RouteAuthority {
183    /// The daemon incarnation reported in the reply's `target`.
184    pub(crate) incarnation: String,
185    /// The opener's spawn and epoch, captured once at admission.
186    pub(crate) caller: Option<AuthorityPair>,
187    /// The admitted capability deny check, for an attested opener.
188    pub(crate) capability_fence: Option<CapabilityFence>,
189}
190
191#[path = "forwarding_capability_fence.rs"]
192mod capability_fence;
193use capability_fence::refuse_acked_bind_locked;
194pub(crate) use capability_fence::CapabilityFence;
195
196/// What the reservation found serving the route.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub(crate) enum TargetAuthority {
199    /// A reserved-prefix child, which never reports its owner's mark.
200    Prefix,
201    /// A registration with no supervised spawn behind it.
202    Unsupervised,
203    /// A supervised spawn's own registration, at the epoch and with the mark
204    /// the forwarding table had published when the endpoint was reserved.
205    Spawn(
206        AuthorityPair,
207        crate::spawn_authority::ApprovedDeclarations,
208        bool,
209    ),
210}
211
212impl TargetAuthority {
213    fn pair(&self) -> Option<&AuthorityPair> {
214        match self {
215            Self::Spawn(pair, _, _) => Some(pair),
216            Self::Prefix | Self::Unsupervised => None,
217        }
218    }
219
220    /// The `target` key of the `route.open` reply. The approved set is the
221    /// serving spawn record's value; the mark is the one published for it.
222    fn reply_target(&self, incarnation: &str) -> Result<RouteOpenTarget, ForwardingError> {
223        let (kind, spawn, epoch, first_party, digest) = match self {
224            Self::Prefix => (RouteOpenTargetKind::Prefix, None, None, false, None),
225            Self::Unsupervised => (RouteOpenTargetKind::Unsupervised, None, None, false, None),
226            Self::Spawn(pair, approved, first_party) => (
227                RouteOpenTargetKind::Spawn,
228                Some(pair.key.spawn),
229                Some(pair.epoch),
230                *first_party,
231                Some(approved.digest.clone()),
232            ),
233        };
234        RouteOpenTarget::new(incarnation, kind, spawn, epoch, first_party, digest)
235            .map_err(|err| ForwardingError::RouteOpenBuild(err.to_string()))
236    }
237}
238
239/// Serialize a successful `route.open` reply with its `target` key.
240fn route_open_reply_body(
241    reply: &ClientControlResponse,
242    target: &TargetAuthority,
243    incarnation: &str,
244) -> Result<Vec<u8>, ForwardingError> {
245    let build = |err: serde_json::Error| ForwardingError::RouteOpenBuild(err.to_string());
246    let mut body = serde_json::to_value(reply).map_err(build)?;
247    RouteOpenReplyExt::new()
248        .with_target(Some(target.reply_target(incarnation)?))
249        .write_to(&mut body)
250        .map_err(build)?;
251    serde_json::to_vec(&body).map_err(build)
252}
253
254#[derive(Debug, Clone)]
255pub(crate) enum DataRoute {
256    Client(DataRouteState),
257    Module(DataRouteState),
258}
259
260#[derive(Debug, Clone)]
261pub(crate) enum DataRouteState {
262    Bound(Arc<RouteBinding>),
263    Reserved,
264    EpochMismatch,
265    Absent,
266}
267
268/// Which kind of peer a route GOODBYE is being delivered to. This decides what
269/// happens when the GOODBYE cannot be enqueued (egress full/closed):
270/// - `Client`: escalate to closing that client connection (a socket close is a
271///   stronger teardown signal, and a full client egress means it is the slow
272///   client we would drop anyway).
273/// - `Module`: never close; deliver late instead (see
274///   [`send_module_route_goodbye`]), and drop only if the module still has no
275///   room after [`LATE_MODULE_GOODBYE_DEADLINE`]. A client-disconnect notifies the
276///   SHARED module that one client's route is gone; closing the module on its
277///   egress backpressure would tear down every co-tenant client (the exact
278///   cross-tenant blast radius this never-close rule exists to prevent — observed when a
279///   flooding dead client filled BOTH its own and the module's egress, so its
280///   route-gone GOODBYE to the module failed and closed the shared connection).
281///   subc has already removed the route from its forwarding state and drops
282///   stale module frames for the released channel (see router.rs), so subc's
283///   own routing is correct. The residual: under SUSTAINED module-egress
284///   backpressure a module-targeted route-gone notification can be lost, which a
285///   module using it for client-refcounting (e.g. AFT's session accounting)
286///   would miss. This is INTENTIONALLY ACCEPTED, not a gap. A consuming module
287///   must bound stale bindings with its own idle-activity reaper (last-touched
288///   TTL) independent of route-gone signals — AFT does exactly this, so a lost
289///   GOODBYE degrades to "the
290///   binding stays warm until its idle TTL" (bounded wasted resources), never an
291///   unbounded leak; disk-durable replay is unaffected. A dedicated reliable
292///   module control lane was evaluated and deliberately NOT
293///   built: it would add starvation-avoidance machinery to the thin core for a
294///   bounded warm-resource window that is not a correctness issue. never-close
295///   is the invariant that matters here.
296#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297pub(crate) enum GoodbyeTargetKind {
298    Client,
299    Module,
300}
301
302#[derive(Debug, Clone)]
303pub(crate) struct GoodbyeTarget {
304    pub connection_id: ConnectionId,
305    pub sink: FrameSink,
306    pub negotiated_ver: u8,
307    pub channel: u16,
308    pub epoch: u32,
309    pub kind: GoodbyeTargetKind,
310    /// The module on the other end of the route: for a module-targeted relay
311    /// the receiving module (attributing a dropped relay), for a client target
312    /// the module whose route is going away (naming it when an undeliverable
313    /// relay closes the client).
314    pub module_id: Option<String>,
315}
316
317/// The frame a client connection's egress queue refused, for the diagnosis
318/// logged when that refusal closes the connection.
319#[derive(Debug, Clone, Copy)]
320pub(crate) struct UndeliveredFrame<'a> {
321    /// The module on the other end of the route the frame belonged to, when known.
322    pub module_id: Option<&'a str>,
323    /// The refusing connection's sink, read for what its queue held.
324    pub sink: &'a FrameSink,
325}
326
327/// How a route's principal appears in logs: `direct`, or `reserved:<module>`.
328pub(crate) fn principal_label(principal: &Principal) -> String {
329    match principal {
330        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
331        Principal::Direct => "direct".to_string(),
332        other => format!("{other:?}"),
333    }
334}
335
336/// The distinct principals of the routes bound on one client connection,
337/// sorted and comma-joined, or `none` when it has no bound route.
338fn connection_principals_locked(inner: &ForwardingInner, connection_id: ConnectionId) -> String {
339    let labels = inner
340        .client_to_module
341        .iter()
342        .filter(|(key, _)| key.connection_id == connection_id)
343        .map(|(_, route)| principal_label(&route.principal))
344        .collect::<std::collections::BTreeSet<_>>();
345    if labels.is_empty() {
346        "none".to_string()
347    } else {
348        labels.into_iter().collect::<Vec<_>>().join(",")
349    }
350}
351
352impl GoodbyeTarget {
353    /// True only when an undeliverable GOODBYE should escalate to closing the
354    /// target connection. Never escalate for module recipients.
355    pub(crate) fn close_on_delivery_failure(&self) -> bool {
356        matches!(self.kind, GoodbyeTargetKind::Client)
357    }
358}
359
360/// How long a route GOODBYE that a module's egress queue refused keeps waiting
361/// for room before it is given up and counted as dropped.
362///
363/// A module that stops reading for a moment (a GC pause, a long synchronous
364/// handler, a reconnect herd it is still working through) should still learn
365/// that the route is gone, because a module that never hears the GOODBYE keeps
366/// the route and keeps sending on it for as long as its connection lives. The
367/// value is the default module drain timeout: the daemon already treats that as
368/// the longest it is reasonable to wait on a module that is busy but alive, and
369/// a module that cannot free 21 bytes of egress in that time is wedged rather
370/// than slow. Resolving each module's own configured drain timeout here would
371/// need a registry lookup on a path that holds only the module's sink.
372pub(crate) const LATE_MODULE_GOODBYE_DEADLINE: Duration = crate::supervise::DEFAULT_DRAIN_TIMEOUT;
373
374/// Send a route GOODBYE to a module without ever closing the module's shared
375/// connection, which would sever every other route it serves.
376///
377/// The frame is enqueued at once when the module's egress queue has room. When
378/// it does not, a detached task waits for room (bounded by
379/// [`LATE_MODULE_GOODBYE_DEADLINE`]) and sends it then. Arriving late is safe:
380/// the daemon has already released the route, and module SDKs tear a route
381/// down only when both the channel AND the epoch match the route installed on
382/// that channel, so a late GOODBYE for a channel since reused at a newer epoch
383/// is ignored. The GOODBYE is counted in `goodbye_relay_module_dropped` only
384/// when the connection is closed or the deadline passes.
385pub(crate) fn send_module_route_goodbye(
386    counters: &DaemonCounters,
387    sink: &FrameSink,
388    frame: Frame,
389    module_id: Option<&str>,
390    context: &'static str,
391) {
392    let channel = frame.header.channel;
393    let epoch = frame.header.epoch;
394    let Err(err) = sink.try_send(frame.clone()) else {
395        return;
396    };
397    // Waiting is pointless once the module's writer is gone, and impossible
398    // outside a Tokio runtime (cleanup that runs from a destructor at shutdown).
399    let runtime = match tokio::runtime::Handle::try_current() {
400        Ok(runtime) if !sink.is_closed() => runtime,
401        _ => {
402            counters.increment_goodbye_relay_module_dropped(module_id);
403            warn!(
404            module_id = module_id.unwrap_or("unknown"),
405            route_channel = channel,
406            route_epoch = epoch,
407            error = %err,
408            context,
409            "route GOODBYE to module dropped: module connection is closed; not closing shared module connection"
410            );
411            return;
412        }
413    };
414    debug!(
415        module_id = module_id.unwrap_or("unknown"),
416        route_channel = channel,
417        route_epoch = epoch,
418        error = %err,
419        context,
420        "module egress queue refused route GOODBYE; delivering it once the module frees room"
421    );
422    let counters = counters.clone();
423    let sink = sink.clone();
424    let module_id = module_id.map(str::to_string);
425    runtime.spawn(async move {
426        let outcome = tokio::time::timeout(LATE_MODULE_GOODBYE_DEADLINE, sink.send(frame)).await;
427        let why = match outcome {
428            Ok(Ok(())) => {
429                debug!(
430                    module_id = module_id.as_deref().unwrap_or("unknown"),
431                    route_channel = channel,
432                    route_epoch = epoch,
433                    context,
434                    "late route GOODBYE delivered to module"
435                );
436                return;
437            }
438            Ok(Err(err)) => err.to_string(),
439            Err(_) => format!(
440                "module egress queue had no room within {LATE_MODULE_GOODBYE_DEADLINE:?}"
441            ),
442        };
443        counters.increment_goodbye_relay_module_dropped(module_id.as_deref());
444        warn!(
445            module_id = module_id.as_deref().unwrap_or("unknown"),
446            route_channel = channel,
447            route_epoch = epoch,
448            error = %why,
449            context,
450            "route GOODBYE to module dropped under backpressure; not closing shared module connection"
451        );
452    });
453}
454
455/// One route currently served by a module endpoint.
456///
457/// `goodbye_target` is deliberately retained alongside the census projection so
458/// a draining caller can address exactly the same route set that this read
459/// reports, without a second forwarding-table pass.
460#[derive(Debug, Clone)]
461pub(crate) struct EndpointRoute {
462    pub goodbye_target: GoodbyeTarget,
463    pub accepts_close_reasons: Option<Vec<String>>,
464    pub principal: Principal,
465    pub bound_at: Instant,
466    pub draining: bool,
467    /// WHY the endpoint is draining, when it is. Carried per-route so the
468    /// census can answer "closing because of what" without a second lookup;
469    /// `None` exactly when `draining` is false (one source: the drain map).
470    pub drain_reason: Option<RouteCloseReason>,
471}
472
473/// One live route a scope change closed: both ends to send GOODBYE to, and the
474/// reason for the client's `route.closed`.
475#[derive(Debug, Clone)]
476pub(crate) struct ScopeDrainedRoute {
477    pub reason: RouteCloseReason,
478    pub scope: BoundScope,
479    pub module_id: String,
480    pub client: GoodbyeTarget,
481    pub module: GoodbyeTarget,
482    pub accepts_close_reasons: Option<Vec<String>>,
483}
484
485/// One live route an authority change closed: both ends to send GOODBYE to,
486/// and the route as it was recorded, for the client's `route.closed`.
487#[derive(Debug, Clone)]
488pub(crate) struct AuthorityClosedRoute {
489    pub route: Arc<RouteBinding>,
490    pub client: GoodbyeTarget,
491    pub module: GoodbyeTarget,
492}
493
494#[derive(Debug)]
495pub(crate) struct PendingRouteBindRelay {
496    pub endpoint: ModuleEndpointId,
497    pub module_sink: FrameSink,
498    pub negotiated_ver: u8,
499    pub client_channel: u16,
500    pub client_epoch: u32,
501    pub module_channel: u16,
502    pub module_epoch: u32,
503    pub corr: u64,
504    pub receiver: oneshot::Receiver<RouteBindRelayOutcome>,
505}
506
507#[derive(Debug, Clone)]
508pub(crate) struct ModuleDrainTarget {
509    pub endpoint: ModuleEndpointId,
510    pub sink: FrameSink,
511    pub negotiated_ver: u8,
512    pub abandoned_bindings: Vec<GoodbyeTarget>,
513    pub excluded_subscriptions: u32,
514}
515
516/// One registered module connection, with its endpoint-bound output sink.
517#[cfg(unix)]
518#[derive(Debug, Clone)]
519pub(crate) struct ModuleConnectionTarget {
520    pub module_id: String,
521    pub endpoint: ModuleEndpointId,
522    pub sink: FrameSink,
523    pub negotiated_ver: u8,
524}
525
526#[derive(Debug, Clone)]
527pub(crate) enum RouteBindRelayOutcome {
528    Accepted,
529    /// The module refused the bind with its own body. Relayed to the client
530    /// without the daemon-origin bit: the code and message are module-chosen,
531    /// so the frame must not claim daemon authorship, even when the module
532    /// picks a daemon code like `module_reloading`.
533    Rejected(ErrorBody),
534    /// The daemon refused the bind itself — a drain or superseded endpoint
535    /// (`module_reloading`), a reply that arrived after the deadline
536    /// (`module_timeout`), or a scope that ended mid-bind. Carries the
537    /// daemon-origin bit because the daemon wrote it. The module may still
538    /// have received the bind (a late reply, or a drain that began after it
539    /// accepted); the daemon then ends that binding with a GOODBYE, so no
540    /// call runs on it.
541    DaemonRejected(ErrorBody),
542    ModuleGone(String),
543}
544
545/// What [`ForwardingTable::cutover_candidate`] did.
546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
547pub(crate) struct ForwardingCutover {
548    /// The endpoint now in the active slot (the former candidate).
549    pub promoted: ModuleEndpointId,
550    /// The endpoint demoted out of the active slot, to be drained by endpoint.
551    /// `None` when the incumbent's connection was already gone.
552    pub incumbent: Option<ModuleEndpointId>,
553}
554
555/// What tearing down one connection released.
556#[derive(Debug)]
557pub(crate) struct ConnectionCleanup {
558    /// Routes whose other end must be sent GOODBYE.
559    pub released: Vec<GoodbyeTarget>,
560    /// Pending route.bind relays to the closed module that were aborted: opens
561    /// that had not been bound yet. Zero when a client connection closed.
562    pub abandoned_relays: u32,
563}
564
565#[derive(Debug, Clone)]
566pub(crate) struct PendingRelayCompletion {
567    pub settled: bool,
568    pub abandoned: Option<GoodbyeTarget>,
569}
570
571#[derive(Debug)]
572pub(crate) struct PendingModuleControlRpc {
573    pub endpoint: ModuleEndpointId,
574    pub module_sink: FrameSink,
575    pub negotiated_ver: u8,
576    pub corr: u64,
577    pub receiver: oneshot::Receiver<ModuleControlRpcOutcome>,
578}
579
580#[derive(Debug, Clone)]
581pub(crate) enum ModuleControlRpcOutcome {
582    RawResponse(Vec<u8>),
583    Response(ModuleControlResponse),
584    Rejected(ErrorBody),
585    ModuleGone(String),
586    MalformedResponse(String),
587    UnexpectedOp { expected: String, actual: String },
588    DeadlineElapsed,
589}
590
591#[derive(Debug, Clone, PartialEq, Eq)]
592pub(crate) enum ModuleControlRpcCompletion {
593    Unknown,
594    Settled,
595    LateHealthAnswer {
596        module_id: String,
597        latency: Duration,
598    },
599}
600
601#[derive(Debug)]
602struct PendingModuleControlRpcEntry {
603    expected_op: String,
604    deadline: Instant,
605    health_probe_started_at: Option<Instant>,
606    sender: oneshot::Sender<ModuleControlRpcOutcome>,
607}
608
609#[derive(Debug)]
610struct HealthProbeTombstone {
611    expected_op: String,
612    module_id: String,
613    probe_started_at: Instant,
614    expires_at: Instant,
615}
616
617#[derive(Debug, Clone)]
618struct RouteReservation {
619    client_key: ClientRouteKey,
620    module_key: ModuleRouteKey,
621    client_epoch: u32,
622    module_epoch: u32,
623    project_root: Option<ProjectRootId>,
624}
625
626#[derive(Debug)]
627struct PendingRouteBindRelayEntry {
628    reservation: RouteReservation,
629    client_sink: FrameSink,
630    client_negotiated_ver: u8,
631    client_permit: crate::router::EgressPermit,
632    route_open_frame: Frame,
633    busy_refusals: bool,
634    accepts_close_reasons: Option<Vec<String>>,
635    request_window: usize,
636    watch_window: Option<usize>,
637    principal: Principal,
638    /// The scope admitted at `route.open`, with the tag captured then. Commit
639    /// compares it with the published tag.
640    scope: Option<BoundScope>,
641    harness: String,
642    build_class: Option<String>,
643    operator_app: Option<crate::operator_apps::OperatorAppStamp>,
644    /// The opener's spawn and epoch, captured once at `route.open` admission
645    /// and never re-read; commit compares it with `spawn_epochs`.
646    caller_authority: Option<AuthorityPair>,
647    /// What served the reserved endpoint, read under the write lock that
648    /// reserved it; commit compares a spawn's epoch with `spawn_epochs`.
649    target_authority: TargetAuthority,
650    /// Rechecked when the target acknowledges; see `capability_fence`.
651    capability_fence: Option<CapabilityFence>,
652    /// The daemon incarnation for the reply's `target` if commit rebuilds it.
653    incarnation: String,
654    deadline: Instant,
655    /// Set once `route.open` has finished putting the route.bind on the
656    /// module's egress queue. A path that drops this entry WITHOUT a module
657    /// reply (client teardown, module drain, the open's own abort) sends the
658    /// module a GOODBYE for the bind only when this is set, because only then
659    /// is the GOODBYE guaranteed to queue behind the bind. When it is not set,
660    /// the removal is recorded in `relays_released_before_enqueue` instead and
661    /// `route.open` sends that GOODBYE itself once its send has completed.
662    ///
663    /// A module reply does not consult it: an ack proves the module received
664    /// the bind, so the reply path decides about the GOODBYE on its own.
665    relay_enqueued: bool,
666    sender: oneshot::Sender<RouteBindRelayOutcome>,
667}
668
669/// What `mark_route_bind_relay_enqueued` found once `route.open` had put the
670/// route.bind on the module's queue.
671#[derive(Debug, Clone, Copy, PartialEq, Eq)]
672pub(crate) enum RouteBindRelayMark {
673    /// The relay is still pending; later removals handle their own GOODBYE.
674    Marked,
675    /// The module already answered and the reply path settled the relay:
676    /// it committed the route, or it refused it and sent any GOODBYE the
677    /// module needed. `route.open` must send nothing.
678    SettledByReply,
679    /// The relay was dropped without a module reply while the bind was still
680    /// being queued, so nothing has told the module to drop the binding it
681    /// is about to create. `route.open` must send that GOODBYE.
682    ReleasedWithoutReply,
683}
684
685#[derive(Debug, Clone)]
686pub(crate) enum RouteRelease {
687    Removed(GoodbyeTarget),
688    Stale,
689    Absent,
690}
691
692#[derive(Debug, Clone)]
693pub(crate) enum RoutePollSnapshot {
694    Bound {
695        module_id: String,
696        status: Option<String>,
697    },
698    Absent,
699}
700
701#[derive(Debug, Clone)]
702struct ModuleConnection {
703    endpoint: ModuleEndpointId,
704    sink: FrameSink,
705    negotiated_ver: u8,
706    concurrency: Concurrency,
707    // Captured at HELLO, not inferred from the id or a later prefix policy.
708    verified_prefix_owner: Option<String>,
709}
710
711pub(crate) struct ModuleHelloAck {
712    pub(crate) frame: Frame,
713    pub(crate) verified_prefix_owner: Option<String>,
714}
715
716#[derive(Debug, Default)]
717struct ForwardingInner {
718    operator_confirms: Arc<crate::operator_confirm::OperatorConfirms>,
719    daemon_draining: bool,
720    /// Whether forwarding reached quiescence during daemon shutdown, for each
721    /// active endpoint present when shutdown began. A pending wait is false
722    /// because it has not proved quiescence. Endpoint generations prevent a
723    /// result from describing a replacement connection with the same module id.
724    daemon_drain_results: HashMap<ModuleEndpointId, bool>,
725    /// The ACTIVE slot: the one endpoint per module id that routing resolves.
726    /// Every by-id lookup (relay reservation, drain-by-id, liveness, census,
727    /// live roots, module-control RPCs) reads this map and nothing else.
728    modules_by_id: HashMap<String, ModuleConnection>,
729    /// The CANDIDATE slot of a blue/green swap: a second process registered
730    /// under an id that already has an active endpoint. It has a full endpoint
731    /// identity (so its own connection can be looked up and torn down) but no
732    /// by-id lookup sees it, so nothing is routed to it until `cutover_candidate`
733    /// promotes it.
734    candidates_by_id: HashMap<String, ModuleConnection>,
735    /// Former active endpoints demoted by `cutover_candidate`, until their
736    /// connection is removed. Membership is what distinguishes an endpoint that
737    /// was SUPERSEDED by a promotion (still alive, still carrying bound routes,
738    /// about to be drained) from one that is merely STALE (replaced some other
739    /// way, which is treated as a fault on the acking connection).
740    superseded_endpoints: HashMap<ModuleEndpointId, ModuleConnection>,
741    endpoint_by_connection: HashMap<ConnectionId, ModuleEndpointId>,
742    module_id_by_endpoint: HashMap<ModuleEndpointId, String>,
743    /// Endpoints mid-drain, keyed to the reason the drain was begun with. The
744    /// value serves the census ("draining because restart"); membership alone
745    /// still answers every admission-gate check.
746    draining_endpoints: HashMap<ModuleEndpointId, RouteCloseReason>,
747    closing_connections: HashSet<ConnectionId>,
748    /// Pending binds check spawn liveness without keeping the spawn alive.
749    spawn_connections: HashMap<ConnectionId, std::sync::Weak<crate::supervise::RegistrationSpawn>>,
750    /// The spawn whose own registration each module connection is, for the
751    /// reply's `target`. A prefix child's connection never has an entry.
752    target_authority_by_connection: HashMap<ConnectionId, Arc<SpawnAuthorityRecord>>,
753    spawn_approved: HashMap<SpawnKey, ApprovedDeclarations>,
754    /// The authority epoch each spawn's last authority change published. A
755    /// spawn with no entry is at the initial epoch. A bind whose captured
756    /// caller or target epoch is older than this is refused at commit.
757    spawn_epochs: HashMap<SpawnKey, u64>,
758    /// The spawns whose first-party mark is raised, published by activation
759    /// and withdrawn by lowering or death, for the reply's `target`.
760    spawn_marks: HashSet<SpawnKey>,
761    /// Spawns published dead whose `spawn_epochs` entry is kept as a
762    /// tombstone. A module keeps the tombstone of its most recent death, plus
763    /// those a pending bind still names, so they cannot pile up.
764    dead_spawns: HashSet<SpawnKey>,
765    next_generation: u64,
766    reserved_client: HashMap<ClientRouteKey, ModuleRouteKey>,
767    reserved_module: HashMap<ModuleRouteKey, ClientRouteKey>,
768    next_client_channel: HashMap<ConnectionId, u16>,
769    next_module_channel: HashMap<ModuleEndpointId, u16>,
770    client_slot_epochs: HashMap<ClientRouteKey, u32>,
771    module_slot_epochs: HashMap<ModuleRouteKey, u32>,
772    last_published_epoch: HashMap<ClientRouteKey, u32>,
773    client_to_module: HashMap<ClientRouteKey, Arc<RouteBinding>>,
774    module_to_client: HashMap<ModuleRouteKey, Arc<RouteBinding>>,
775    status: HashMap<(ClientRouteKey, u32), String>,
776    pending_relays: HashMap<(ModuleEndpointId, u64), PendingRouteBindRelayEntry>,
777    /// Pending relays removed without a module reply before `route.open`
778    /// marked them enqueued. `route.open` consumes its key when it marks the
779    /// relay (and sends the GOODBYE the removal could not send safely) or when
780    /// it aborts, so an entry lives only while that open is mid-send.
781    relays_released_before_enqueue: HashSet<(ModuleEndpointId, u64)>,
782    /// Each scope's current `(scope_epoch, version)`, keyed `(owner, ref)`,
783    /// published by a scope sync in the same step that changes the record. A
784    /// bind commit reads it here so it never takes the scope table's lock
785    /// while holding this one. Absent means the scope is not live.
786    scope_tags: HashMap<(String, String), ScopeTag>,
787    next_control_corr: HashMap<ModuleEndpointId, u64>,
788    pending_control_rpcs: HashMap<(ModuleEndpointId, u64), PendingModuleControlRpcEntry>,
789    health_probe_tombstones: HashMap<(ModuleEndpointId, u64), HealthProbeTombstone>,
790}
791
792#[derive(Debug, Clone)]
793pub(crate) struct CloseReason {
794    code: &'static str,
795    message: String,
796}
797
798impl CloseReason {
799    pub(crate) fn new(code: &'static str, message: impl Into<String>) -> Self {
800        Self {
801            code,
802            message: message.into(),
803        }
804    }
805}
806
807impl fmt::Display for CloseReason {
808    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809        write!(f, "{}: {}", self.code, self.message)
810    }
811}
812
813pub(crate) type ConnectionCloseReceiver = oneshot::Receiver<CloseReason>;
814
815/// Dynamic forwarding state shared by the control plane and data-plane router.
816#[derive(Debug, Default)]
817pub struct ForwardingTable {
818    #[cfg(all(test, target_os = "linux"))]
819    route_commit_pause: Mutex<Option<RouteCommitPause>>,
820    #[cfg(all(test, target_os = "linux"))]
821    cleanup_tie_observer: Mutex<Option<oneshot::Sender<(bool, usize)>>>,
822    #[cfg(all(test, target_os = "linux"))]
823    cleanup_pause: Mutex<Option<RouteCommitPause>>,
824    #[cfg(test)]
825    policy_rebind_before_write: Mutex<Option<Arc<std::sync::Barrier>>>,
826    inner: Arc<RwLock<ForwardingInner>>,
827    frame_drop_warnings: Mutex<HashMap<ConnectionId, ChannelDropWarnings>>,
828    #[cfg(feature = "test-support")]
829    route_closing_hold: Mutex<Option<oneshot::Receiver<()>>>,
830    close_registry: Mutex<HashMap<ConnectionId, oneshot::Sender<CloseReason>>>,
831    counters: DaemonCounters,
832    /// Per-target-module bind-relay breaker state. It lives here, beside the
833    /// module connections it describes, because this is where a module
834    /// connection's identity is established and therefore where a stale
835    /// verdict has to be discarded.
836    route_bind_breakers: RouteBindBreakers,
837    /// Current route.bind relays keyed by target module. Admission is shared
838    /// across every client connection that points at the same endpoint.
839    route_bind_concurrency: RouteBindConcurrency,
840    /// Start and end of each module's `route.open` outage. Held here for the
841    /// same reason as the breakers: every handler built over this table must
842    /// see one outage per module, or each would log its own opening line.
843    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
844}
845
846#[cfg(all(test, target_os = "linux"))]
847#[derive(Debug)]
848struct RouteCommitPause {
849    reached: oneshot::Sender<()>,
850    release: std::sync::mpsc::Receiver<()>,
851}
852
853pub(crate) type PolicyRevocation = (Vec<EndpointRoute>, Vec<GoodbyeTarget>);
854
855#[derive(Debug)]
856struct FrameDropWarning {
857    last_warned: tokio::time::Instant,
858    suppressed: u64,
859}
860
861type ChannelDropWarnings = HashMap<(u16, &'static str), FrameDropWarning>;
862
863impl ForwardingTable {
864    #[cfg(all(test, target_os = "linux"))]
865    pub(crate) fn pause_cleanup_for_test(
866        &self,
867    ) -> (oneshot::Receiver<()>, std::sync::mpsc::Sender<()>) {
868        let (reached, observed) = oneshot::channel();
869        let (release, paused) = std::sync::mpsc::channel();
870        *self.cleanup_pause.lock().unwrap() = Some(RouteCommitPause {
871            reached,
872            release: paused,
873        });
874        (observed, release)
875    }
876    #[cfg(all(test, target_os = "linux"))]
877    pub(crate) fn observe_cleanup_tie_for_test(&self) -> oneshot::Receiver<(bool, usize)> {
878        let (send, receive) = oneshot::channel();
879        *self.cleanup_tie_observer.lock().unwrap() = Some(send);
880        receive
881    }
882    #[cfg(all(test, target_os = "linux"))]
883    pub(crate) fn spawn_connection_recorded_for_test(&self, connection: ConnectionId) -> bool {
884        self.read_inner()
885            .unwrap()
886            .spawn_connections
887            .contains_key(&connection)
888    }
889    #[cfg(all(test, target_os = "linux"))]
890    pub(crate) fn pause_route_commit_for_test(
891        &self,
892    ) -> (oneshot::Receiver<()>, std::sync::mpsc::Sender<()>) {
893        let (reached, observed) = oneshot::channel();
894        let (release, paused) = std::sync::mpsc::channel();
895        *self.route_commit_pause.lock().unwrap() = Some(RouteCommitPause {
896            reached,
897            release: paused,
898        });
899        (observed, release)
900    }
901    pub(crate) fn bind_spawn(
902        &self,
903        connection: ConnectionId,
904        spawn: &Arc<crate::supervise::RegistrationSpawn>,
905    ) -> Result<(), ForwardingError> {
906        self.write_inner()?
907            .spawn_connections
908            .insert(connection, Arc::downgrade(spawn));
909        Ok(())
910    }
911
912    /// Record that `connection` is `record`'s spawn's own module registration,
913    /// so a route reserved on it reports `target.kind: spawn`.
914    pub(crate) fn bind_target_authority(
915        &self,
916        connection: ConnectionId,
917        record: Arc<SpawnAuthorityRecord>,
918    ) -> Result<(), ForwardingError> {
919        let approved = record.approved();
920        let mut inner = self.write_inner()?;
921        inner.spawn_approved.insert(record.key(), approved);
922        inner
923            .target_authority_by_connection
924            .insert(connection, record);
925        Ok(())
926    }
927
928    /// Undo [`Self::bind_target_authority`] for a HELLO that was refused
929    /// after it: the connection is no registration of the spawn.
930    pub(crate) fn unbind_target_authority(
931        &self,
932        connection: ConnectionId,
933    ) -> Result<(), ForwardingError> {
934        self.write_inner()?
935            .target_authority_by_connection
936            .remove(&connection);
937        Ok(())
938    }
939    /// The spawn whose own module registration `connection` is, if any.
940    pub(crate) fn target_authority_for_connection(
941        &self,
942        connection: ConnectionId,
943    ) -> Result<Option<Arc<SpawnAuthorityRecord>>, ForwardingError> {
944        Ok(self
945            .read_inner()?
946            .target_authority_by_connection
947            .get(&connection)
948            .cloned())
949    }
950
951    /// The module connection that is `key`'s spawn's own registration.
952    pub(crate) fn connection_for_spawn(
953        &self,
954        key: &SpawnKey,
955    ) -> Result<Option<ConnectionId>, ForwardingError> {
956        Ok(self
957            .read_inner()?
958            .target_authority_by_connection
959            .iter()
960            .find(|(_, record)| record.key() == *key)
961            .map(|(connection, _)| *connection))
962    }
963
964    pub(crate) fn active_module_endpoint(
965        &self,
966        module_id: &str,
967    ) -> Result<Option<ModuleEndpointId>, ForwardingError> {
968        Ok(self
969            .read_inner()?
970            .modules_by_id
971            .get(module_id)
972            .map(|module| module.endpoint))
973    }
974
975    pub(crate) fn config_delivery_sink(
976        &self,
977        module: &str,
978        connection: ConnectionId,
979    ) -> Result<Option<FrameSink>, ForwardingError> {
980        let inner = self.read_inner()?;
981        Ok(inner
982            .modules_by_id
983            .get(module)
984            .filter(|target| {
985                target.endpoint.connection_id == connection
986                    && !inner.closing_connections.contains(&connection)
987            })
988            .map(|target| target.sink.clone()))
989    }
990
991    pub(crate) fn live_project_hint_target(
992        &self,
993        module: &str,
994        connection: ConnectionId,
995    ) -> Result<Option<(FrameSink, u8)>, ForwardingError> {
996        let inner = self.read_inner()?;
997        if inner.closing_connections.contains(&connection) {
998            return Ok(None);
999        }
1000        Ok(inner
1001            .modules_by_id
1002            .get(module)
1003            .into_iter()
1004            .chain(inner.candidates_by_id.get(module))
1005            .find(|target| target.endpoint.connection_id == connection)
1006            .map(|target| (target.sink.clone(), target.negotiated_ver)))
1007    }
1008    /// Keep a silent route diagnosable without letting a broken peer flood logs.
1009    /// Epoch and direction describe the dropped frame, but do not split its limit.
1010    pub(crate) fn warn_frame_drop(
1011        &self,
1012        connection_id: ConnectionId,
1013        channel: u16,
1014        epoch: u32,
1015        direction: &'static str,
1016        reason: &'static str,
1017    ) {
1018        let now = tokio::time::Instant::now();
1019        let mut warnings = self
1020            .frame_drop_warnings
1021            .lock()
1022            .unwrap_or_else(std::sync::PoisonError::into_inner);
1023        let entry = warnings
1024            .entry(connection_id)
1025            .or_default()
1026            .entry((channel, reason));
1027        let suppressed = match entry {
1028            std::collections::hash_map::Entry::Occupied(mut entry) => {
1029                let state = entry.get_mut();
1030                if now.saturating_duration_since(state.last_warned) < Duration::from_secs(60) {
1031                    state.suppressed = state.suppressed.saturating_add(1);
1032                    return;
1033                }
1034                state.last_warned = now;
1035                std::mem::take(&mut state.suppressed)
1036            }
1037            std::collections::hash_map::Entry::Vacant(entry) => {
1038                entry.insert(FrameDropWarning {
1039                    last_warned: now,
1040                    suppressed: 0,
1041                });
1042                0
1043            }
1044        };
1045        warn!(
1046            connection_id = connection_id.get(),
1047            channel, epoch, direction, reason, suppressed, "dropping data-plane frame"
1048        );
1049    }
1050
1051    /// Install scripted operator confirmation for an in-process integration harness,
1052    /// without bootstrapping a daemon process. Only available with `test-support`.
1053    ///
1054    /// The script has one response per line: `approve`, `decline`, `unavailable`,
1055    /// `hang` (until withdrawn), or `approve when <path>` (wait for the path to
1056    /// exist). Unreadable or exhausted scripts fail closed. If supplied, `events`
1057    /// receives the provider's JSON-lines event log. `limits: None` uses
1058    /// [`OperatorLimits::default`](crate::operator_confirm::OperatorLimits); use
1059    /// `Some(OperatorLimits { queue_wait, prompt_timeout, stuck_grace })` to
1060    /// override the queue wait, prompt timeout and stuck-provider grace periods.
1061    ///
1062    /// The current executable's file name **must start with `ckdev-`**. Otherwise
1063    /// this logs a warning and keeps the OS provider, just like bootstrap.
1064    /// `cortexkit-test-support`'s `ckdev_binary` copies a harness executable under
1065    /// a qualifying name; run that copy to enable scripted confirmation. See
1066    /// `crates/subc-client-rs/tests/real_daemon/operator_confirm.rs` for the
1067    /// reference end-to-end harness.
1068    ///
1069    /// Configure the table shared by the harness's `ControlHandler` and `Router`
1070    /// before serving any requests. This also configures privileged confirmations
1071    /// that use the same table.
1072    ///
1073    /// # Panics
1074    ///
1075    /// Panics if operator-confirm processing has already started.
1076    ///
1077    /// # Example
1078    ///
1079    /// ```no_run
1080    /// use std::{path::Path, sync::Arc};
1081    /// use subc_daemon::{ControlHandler, ForwardingTable, Registry};
1082    ///
1083    /// let registry = Arc::new(Registry::default());
1084    /// let forwarding = Arc::new(ForwardingTable::default());
1085    /// forwarding.configure_operator_script(
1086    ///     Path::new("operator.script"),
1087    ///     Some(Path::new("operator.events")),
1088    ///     None,
1089    /// );
1090    /// let handler = ControlHandler::with_forwarding(registry, forwarding);
1091    /// ```
1092    #[cfg(feature = "test-support")]
1093    pub fn configure_operator_script(
1094        &self,
1095        script: &std::path::Path,
1096        events: Option<&std::path::Path>,
1097        limits: Option<crate::operator_confirm::OperatorLimits>,
1098    ) {
1099        self.operator_confirms()
1100            .configure_script(script, events, limits);
1101    }
1102
1103    /// Hold the next supervisor drain between enqueueing `module.draining` and
1104    /// `route.closing`, so a test can forward a response in that window. Dropping
1105    /// the returned sender also releases the hold, including on a test panic.
1106    #[cfg(feature = "test-support")]
1107    pub fn hold_route_closing_for_test(&self) -> oneshot::Sender<()> {
1108        let (release, hold) = oneshot::channel();
1109        *self.route_closing_hold.lock().unwrap() = Some(hold);
1110        release
1111    }
1112
1113    #[cfg(feature = "test-support")]
1114    pub(crate) async fn wait_before_route_closing_for_test(&self) {
1115        let hold = self.route_closing_hold.lock().unwrap().take();
1116        if let Some(hold) = hold {
1117            let _ = hold.await;
1118        }
1119    }
1120
1121    pub(crate) fn operator_confirms(&self) -> Arc<crate::operator_confirm::OperatorConfirms> {
1122        Arc::clone(
1123            &self
1124                .inner
1125                .read()
1126                .unwrap_or_else(|p| p.into_inner())
1127                .operator_confirms,
1128        )
1129    }
1130
1131    #[cfg(test)]
1132    pub(crate) fn inject_operator_principal(&self, key: ModuleRouteKey, principal: Principal) {
1133        self.alter_operator_binding_for_test(key, |binding| binding.principal = principal);
1134    }
1135
1136    #[cfg(test)]
1137    pub(crate) fn alter_operator_binding_for_test(
1138        &self,
1139        key: ModuleRouteKey,
1140        alter: impl FnOnce(&mut RouteBinding),
1141    ) {
1142        let mut inner = self.write_inner().unwrap();
1143        let old = inner.module_to_client.remove(&key).unwrap();
1144        let client = ClientRouteKey {
1145            connection_id: old.client_connection_id,
1146            channel: old.client_channel,
1147        };
1148        inner.client_to_module.remove(&client);
1149        let mut binding = Arc::try_unwrap(old).expect("test binding has no outstanding readers");
1150        alter(&mut binding);
1151        let binding = Arc::new(binding);
1152        inner.client_to_module.insert(client, Arc::clone(&binding));
1153        inner.module_to_client.insert(key, binding);
1154    }
1155
1156    /// Mutate the route without delivering its withdrawal notice, so tests can
1157    /// exercise the commit-point route check rather than the withdrawal path.
1158    #[cfg(test)]
1159    pub(crate) fn invalidate_operator_route_for_test(&self, key: ModuleRouteKey, stale: bool) {
1160        let mut inner = self.write_inner().unwrap();
1161        let old = inner.module_to_client.remove(&key).unwrap();
1162        let client = ClientRouteKey {
1163            connection_id: old.client_connection_id,
1164            channel: old.client_channel,
1165        };
1166        inner.client_to_module.remove(&client);
1167        if stale {
1168            let mut binding = Arc::try_unwrap(old).expect("no binding readers at the test pause");
1169            binding.module_epoch += 1;
1170            let binding = Arc::new(binding);
1171            inner.client_to_module.insert(client, binding.clone());
1172            inner.module_to_client.insert(key, binding);
1173        }
1174    }
1175
1176    /// Keep the binding protected through confirmation admission. Route release
1177    /// takes the write lock and then the same confirm-state lock, so it cannot
1178    /// miss an admitted request or leave it waiting on a vanished route.
1179    pub(crate) fn with_operator_route<T>(
1180        &self,
1181        connection_id: ConnectionId,
1182        channel: u16,
1183        epoch: u32,
1184        admit: impl FnOnce(Option<&RouteBinding>) -> T,
1185    ) -> Result<T, ForwardingError> {
1186        self.with_operator_route_epoch(connection_id, channel, |binding| {
1187            admit(binding.filter(|binding| binding.module_epoch == epoch))
1188        })
1189    }
1190
1191    /// Like admission, but retains a mismatched epoch so a shortcut can audit
1192    /// a stale channel separately from a closed one, under the same read lock.
1193    pub(crate) fn with_operator_route_epoch<T>(
1194        &self,
1195        connection_id: ConnectionId,
1196        channel: u16,
1197        decide: impl FnOnce(Option<&RouteBinding>) -> T,
1198    ) -> Result<T, ForwardingError> {
1199        let inner = self.read_inner()?;
1200        let binding = inner
1201            .endpoint_by_connection
1202            .get(&connection_id)
1203            .and_then(|endpoint| {
1204                inner.module_to_client.get(&ModuleRouteKey {
1205                    endpoint: *endpoint,
1206                    channel,
1207                })
1208            });
1209        Ok(decide(binding.map(Arc::as_ref)))
1210    }
1211
1212    pub(crate) fn counters(&self) -> DaemonCounters {
1213        self.counters.clone()
1214    }
1215
1216    pub(crate) fn counters_ref(&self) -> &DaemonCounters {
1217        &self.counters
1218    }
1219
1220    pub(crate) fn route_bind_breakers(&self) -> RouteBindBreakers {
1221        self.route_bind_breakers.clone()
1222    }
1223
1224    pub(crate) fn route_bind_concurrency(&self) -> RouteBindConcurrency {
1225        self.route_bind_concurrency.clone()
1226    }
1227
1228    pub(crate) fn route_outages(&self) -> Arc<crate::route_outage::RouteOutageTracker> {
1229        Arc::clone(&self.route_outages)
1230    }
1231
1232    pub(crate) fn register_connection_close(
1233        &self,
1234        connection_id: ConnectionId,
1235    ) -> ConnectionCloseReceiver {
1236        let (sender, receiver) = oneshot::channel();
1237        let replaced = self
1238            .lock_close_registry()
1239            .insert(connection_id, sender)
1240            .is_some();
1241        if replaced {
1242            warn!(
1243                connection_id = connection_id.get(),
1244                "replaced existing connection close registration"
1245            );
1246        }
1247        receiver
1248    }
1249
1250    pub(crate) fn unregister_connection_close(&self, connection_id: ConnectionId) {
1251        self.lock_close_registry().remove(&connection_id);
1252        // The read loop and its tasks have ended and connection cleanup has
1253        // removed its routes and pending relays. The writer may still drain.
1254        // A channel-0 GOODBYE preserves the connection-to-launch association
1255        // until that cleanup.
1256        if let Ok(mut inner) = self.write_inner() {
1257            inner.spawn_connections.remove(&connection_id);
1258            inner.target_authority_by_connection.remove(&connection_id);
1259        }
1260    }
1261
1262    /// Close every established connection, modules and clients alike, as the
1263    /// last step of an announced daemon shutdown. By the time this runs each
1264    /// registered module has already been sent a module GOODBYE (see
1265    /// `Supervisor::end_children_for_daemon_shutdown`), so the EOF that follows
1266    /// is a planned stop; EOF with no GOODBYE before it stays reserved for a
1267    /// daemon that went away unannounced. Closing while the daemon is still
1268    /// alive lets it wait for the modules' own teardowns before it ends
1269    /// whatever is left.
1270    #[cfg(unix)]
1271    pub(crate) fn close_all_connections(&self, reason: &CloseReason) -> usize {
1272        let senders: Vec<_> = self.lock_close_registry().drain().collect();
1273        let count = senders.len();
1274        for (_, sender) in senders {
1275            let _ = sender.send(reason.clone());
1276        }
1277        count
1278    }
1279
1280    /// Every registered module connection, whichever slot it occupies (active,
1281    /// swap candidate, or superseded incumbent), once each. Daemon shutdown
1282    /// uses this to tell each of them it is a planned stop before closing it.
1283    #[cfg(unix)]
1284    pub(crate) fn module_connections(
1285        &self,
1286    ) -> Result<Vec<ModuleConnectionTarget>, ForwardingError> {
1287        let inner = self.read_inner()?;
1288        let mut seen = HashSet::new();
1289        Ok(inner
1290            .modules_by_id
1291            .values()
1292            .chain(inner.candidates_by_id.values())
1293            .chain(inner.superseded_endpoints.values())
1294            .filter(|module| seen.insert(module.endpoint))
1295            .map(|module| ModuleConnectionTarget {
1296                module_id: inner
1297                    .module_id_by_endpoint
1298                    .get(&module.endpoint)
1299                    .cloned()
1300                    .unwrap_or_default(),
1301                endpoint: module.endpoint,
1302                sink: module.sink.clone(),
1303                negotiated_ver: module.negotiated_ver,
1304            })
1305            .collect())
1306    }
1307
1308    /// Ask a registered connection to close. Returns true only for the request
1309    /// that actually reached it; later requests for the same connection, and
1310    /// requests for a connection that is not registered, return false.
1311    pub(crate) fn request_connection_close(
1312        &self,
1313        connection_id: ConnectionId,
1314        reason: CloseReason,
1315    ) -> bool {
1316        let sender = self.lock_close_registry().remove(&connection_id);
1317        if let Some(sender) = sender {
1318            debug!(
1319                connection_id = connection_id.get(),
1320                close_reason = %reason,
1321                "requesting connection close"
1322            );
1323            let _ = sender.send(reason);
1324            true
1325        } else {
1326            debug!(
1327                connection_id = connection_id.get(),
1328                close_reason = %reason,
1329                "connection close request ignored for inactive connection"
1330            );
1331            false
1332        }
1333    }
1334
1335    pub fn register_module_connection(
1336        &self,
1337        connection_id: ConnectionId,
1338        module_id: String,
1339        negotiated_ver: u8,
1340        concurrency: Concurrency,
1341        sink: FrameSink,
1342    ) -> Result<ModuleEndpointId, ForwardingError> {
1343        self.register_module_connection_inner(
1344            connection_id,
1345            module_id,
1346            negotiated_ver,
1347            concurrency,
1348            sink,
1349            None,
1350        )
1351    }
1352
1353    /// Register a module connection and queue its HELLO_ACK as the first frame
1354    /// on its sink, in the same write-lock critical section that makes the
1355    /// endpoint visible.
1356    ///
1357    /// A module reads HELLO_ACK as the first frame after its HELLO and exits on
1358    /// anything else. Once the endpoint is in `modules_by_id`, a `route.open`
1359    /// on any other connection can queue a `route.bind` request onto this sink,
1360    /// so the ack must already be queued by then. Every lookup that can queue a
1361    /// frame for the module takes this lock, so nothing can get in ahead of it.
1362    ///
1363    /// If the ack cannot be queued (the sink is closed or full), the
1364    /// registration fails with nothing inserted.
1365    pub(crate) fn register_module_connection_acked(
1366        &self,
1367        connection_id: ConnectionId,
1368        module_id: String,
1369        negotiated_ver: u8,
1370        concurrency: Concurrency,
1371        sink: FrameSink,
1372        hello_ack: ModuleHelloAck,
1373    ) -> Result<ModuleEndpointId, ForwardingError> {
1374        self.register_module_connection_inner(
1375            connection_id,
1376            module_id,
1377            negotiated_ver,
1378            concurrency,
1379            sink,
1380            Some(hello_ack),
1381        )
1382    }
1383
1384    fn register_module_connection_inner(
1385        &self,
1386        connection_id: ConnectionId,
1387        module_id: String,
1388        negotiated_ver: u8,
1389        concurrency: Concurrency,
1390        sink: FrameSink,
1391        hello_ack: Option<ModuleHelloAck>,
1392    ) -> Result<ModuleEndpointId, ForwardingError> {
1393        let mut inner = self.write_inner()?;
1394        if inner.daemon_draining || inner.closing_connections.contains(&connection_id) {
1395            return Err(ForwardingError::ConnectionClosing { connection_id });
1396        }
1397        check_module_connection_role_locked(&inner, connection_id)?;
1398        // Every refusal check has passed and nothing has been mutated yet, so
1399        // a failed enqueue leaves the table exactly as it was.
1400        let verified_prefix_owner = hello_ack
1401            .as_ref()
1402            .and_then(|hello| hello.verified_prefix_owner.clone());
1403        enqueue_hello_ack_locked(&sink, connection_id, hello_ack.map(|hello| hello.frame))?;
1404
1405        inner.next_generation = inner.next_generation.checked_add(1).unwrap_or(1);
1406        let endpoint = ModuleEndpointId {
1407            connection_id,
1408            generation: inner.next_generation,
1409        };
1410        inner.endpoint_by_connection.insert(connection_id, endpoint);
1411        inner
1412            .module_id_by_endpoint
1413            .insert(endpoint, module_id.clone());
1414        inner.next_module_channel.insert(endpoint, 1);
1415        inner.next_control_corr.insert(endpoint, 1);
1416        inner.modules_by_id.insert(
1417            module_id.clone(),
1418            ModuleConnection {
1419                endpoint,
1420                sink,
1421                negotiated_ver,
1422                concurrency,
1423                verified_prefix_owner,
1424            },
1425        );
1426        drop(inner);
1427
1428        // A new module connection has arrived under this id, so anything the
1429        // bind-relay breaker learned was learned about a process that is no
1430        // longer the one behind this name. See
1431        // `RouteBindBreakers::reset_for_new_module_connection`.
1432        //
1433        // Keyed on ARRIVAL rather than on teardown deliberately: a connection
1434        // going away is not evidence about anything, and a module whose
1435        // connection drops without coming back should keep its verdict until
1436        // something actually registers in its place. This also covers the
1437        // unclean replacements -- a module killed mid-bind, or one whose
1438        // connection was closing -- because registration is the single path by
1439        // which any module connection becomes usable.
1440        if let Some(discarded) = self
1441            .route_bind_breakers
1442            .reset_for_new_module_connection(&module_id)
1443        {
1444            info!(
1445                module_id = %module_id,
1446                discarded_consecutive_timeouts = discarded,
1447                "route.bind breaker state discarded: a new module connection replaced the process it described"
1448            );
1449        }
1450        Ok(endpoint)
1451    }
1452
1453    /// Register a blue/green swap candidate for `module_id` into the candidate
1454    /// slot, alongside whatever endpoint is active for the id.
1455    ///
1456    /// Unlike [`Self::register_module_connection`], this never touches the
1457    /// active slot and never resets the bind-relay breaker: the incumbent is
1458    /// still the process serving the id, so what the breaker learned about it
1459    /// is still true. The breaker is reset at cutover instead, when the process
1460    /// behind the name actually changes. A second candidate for the same id is
1461    /// refused.
1462    ///
1463    /// Production registers candidates through
1464    /// [`Self::register_candidate_module_connection_acked`]; this ack-less form
1465    /// is for tests that build forwarding state directly.
1466    #[cfg(test)]
1467    pub(crate) fn register_candidate_module_connection(
1468        &self,
1469        connection_id: ConnectionId,
1470        module_id: String,
1471        negotiated_ver: u8,
1472        concurrency: Concurrency,
1473        sink: FrameSink,
1474    ) -> Result<ModuleEndpointId, ForwardingError> {
1475        self.register_candidate_module_connection_inner(
1476            connection_id,
1477            module_id,
1478            negotiated_ver,
1479            concurrency,
1480            sink,
1481            None,
1482        )
1483    }
1484
1485    /// The swap-candidate counterpart of
1486    /// [`Self::register_module_connection_acked`]: the HELLO_ACK is queued on
1487    /// the candidate's sink before its endpoint is inserted. No by-id lookup
1488    /// sees a candidate, but its own connection's endpoint does become
1489    /// resolvable here, and at cutover it becomes routable; the ack has to be
1490    /// ahead of anything either can queue.
1491    pub(crate) fn register_candidate_module_connection_acked(
1492        &self,
1493        connection_id: ConnectionId,
1494        module_id: String,
1495        negotiated_ver: u8,
1496        concurrency: Concurrency,
1497        sink: FrameSink,
1498        hello_ack: Frame,
1499    ) -> Result<ModuleEndpointId, ForwardingError> {
1500        self.register_candidate_module_connection_inner(
1501            connection_id,
1502            module_id,
1503            negotiated_ver,
1504            concurrency,
1505            sink,
1506            Some(hello_ack),
1507        )
1508    }
1509
1510    fn register_candidate_module_connection_inner(
1511        &self,
1512        connection_id: ConnectionId,
1513        module_id: String,
1514        negotiated_ver: u8,
1515        concurrency: Concurrency,
1516        sink: FrameSink,
1517        hello_ack: Option<Frame>,
1518    ) -> Result<ModuleEndpointId, ForwardingError> {
1519        let mut inner = self.write_inner()?;
1520        if inner.daemon_draining || inner.closing_connections.contains(&connection_id) {
1521            return Err(ForwardingError::ConnectionClosing { connection_id });
1522        }
1523        check_module_connection_role_locked(&inner, connection_id)?;
1524        if inner.candidates_by_id.contains_key(&module_id) {
1525            return Err(ForwardingError::CandidateSlotOccupied { module_id });
1526        }
1527        // As in `register_module_connection_inner`: after every refusal check,
1528        // before any mutation.
1529        enqueue_hello_ack_locked(&sink, connection_id, hello_ack)?;
1530
1531        inner.next_generation = inner.next_generation.checked_add(1).unwrap_or(1);
1532        let endpoint = ModuleEndpointId {
1533            connection_id,
1534            generation: inner.next_generation,
1535        };
1536        inner.endpoint_by_connection.insert(connection_id, endpoint);
1537        inner
1538            .module_id_by_endpoint
1539            .insert(endpoint, module_id.clone());
1540        inner.next_module_channel.insert(endpoint, 1);
1541        inner.next_control_corr.insert(endpoint, 1);
1542        inner.candidates_by_id.insert(
1543            module_id,
1544            ModuleConnection {
1545                endpoint,
1546                sink,
1547                negotiated_ver,
1548                concurrency,
1549                verified_prefix_owner: None,
1550            },
1551        );
1552        Ok(endpoint)
1553    }
1554
1555    /// Promote `module_id`'s candidate to the active slot, in ONE forwarding
1556    /// write-lock critical section.
1557    ///
1558    /// That single section is the linearization point of a swap. Every relay
1559    /// reservation resolves the active slot under the same lock, so each one
1560    /// lands wholly before cutover (on the incumbent) or wholly after it (on the
1561    /// promoted candidate), never on a mix. A relay reserved on the incumbent
1562    /// before cutover can no longer commit: `commit_route_locked` requires the
1563    /// reservation's endpoint to be the active one, and an ack for it arriving
1564    /// later is answered by the superseded-endpoint arm of
1565    /// `complete_pending_relay` instead of ending the incumbent's connection.
1566    ///
1567    /// Both endpoints keep their identities: nothing is re-keyed, so the
1568    /// incumbent's bound routes and its pending correlation keys stay exactly
1569    /// where they are until it is drained with [`Self::begin_endpoint_drain`],
1570    /// using the incumbent endpoint this returns. Returns `Ok(None)` when there
1571    /// is no candidate for the id.
1572    pub(crate) fn cutover_candidate(
1573        &self,
1574        module_id: &str,
1575    ) -> Result<Option<ForwardingCutover>, ForwardingError> {
1576        let mut inner = self.write_inner()?;
1577        if inner.daemon_draining {
1578            return Err(ForwardingError::ModuleReloading {
1579                module_id: module_id.to_string(),
1580            });
1581        }
1582        let Some(candidate) = inner.candidates_by_id.remove(module_id) else {
1583            return Ok(None);
1584        };
1585        let promoted = candidate.endpoint;
1586        let incumbent = inner.modules_by_id.insert(module_id.to_string(), candidate);
1587        let incumbent = incumbent.map(|incumbent| {
1588            let endpoint = incumbent.endpoint;
1589            inner.superseded_endpoints.insert(endpoint, incumbent);
1590            endpoint
1591        });
1592        drop(inner);
1593
1594        // A different process now answers for this id; see the matching reset
1595        // in `register_module_connection` for why a verdict about the old one
1596        // must not carry over.
1597        if let Some(discarded) = self
1598            .route_bind_breakers
1599            .reset_for_new_module_connection(module_id)
1600        {
1601            info!(
1602                module_id = %module_id,
1603                discarded_consecutive_timeouts = discarded,
1604                "route.bind breaker state discarded: a swap candidate was promoted over the process it described"
1605            );
1606        }
1607        Ok(Some(ForwardingCutover {
1608            promoted,
1609            incumbent,
1610        }))
1611    }
1612
1613    #[allow(clippy::too_many_arguments)]
1614    pub(crate) async fn begin_route_bind_relay_for(
1615        &self,
1616        client_connection_id: ConnectionId,
1617        client_sink: FrameSink,
1618        client_negotiated_ver: u8,
1619        client_corr: u64,
1620        module_id: &str,
1621        principal: Principal,
1622        scope: Option<BoundScope>,
1623        project_root: Option<ProjectRootId>,
1624        harness: String,
1625        build_class: Option<String>,
1626        operator_app: Option<crate::operator_apps::OperatorAppStamp>,
1627        authority: RouteAuthority,
1628        deadline: Instant,
1629        busy_refusals: bool,
1630        accepts_close_reasons: Option<Vec<String>>,
1631    ) -> Result<PendingRouteBindRelay, ForwardingError> {
1632        // Reserve egress capacity before taking the forwarding lock. The permit is
1633        // held until the bind reaches one terminal state, so an accepted bind can
1634        // publish its table entry and RouteOpen response in one critical section.
1635        // The wait spends the open's relay deadline, like the bind's own send.
1636        let client_permit = tokio::time::timeout_at(deadline, client_sink.reserve_owned())
1637            .await
1638            .map_err(|_| ForwardingError::RelayDeadlineElapsed)?
1639            .map_err(|_| ForwardingError::ClientEgressClosed {
1640                connection_id: client_connection_id,
1641            })?;
1642        self.begin_route_bind_relay_inner(
1643            client_connection_id,
1644            client_sink,
1645            client_negotiated_ver,
1646            client_corr,
1647            module_id,
1648            principal,
1649            scope,
1650            project_root,
1651            harness,
1652            build_class,
1653            operator_app,
1654            authority,
1655            deadline,
1656            client_permit,
1657            busy_refusals,
1658            accepts_close_reasons,
1659        )
1660    }
1661
1662    #[cfg(test)]
1663    pub(crate) fn begin_route_bind_relay_for_test(
1664        &self,
1665        client_connection_id: ConnectionId,
1666        client_sink: FrameSink,
1667        client_corr: u64,
1668        module_id: &str,
1669    ) -> Result<PendingRouteBindRelay, ForwardingError> {
1670        self.begin_route_bind_relay_with_busy_for_test(
1671            client_connection_id,
1672            client_sink,
1673            client_corr,
1674            module_id,
1675            false,
1676        )
1677    }
1678
1679    #[cfg(test)]
1680    pub(crate) fn begin_route_bind_relay_with_busy_for_test(
1681        &self,
1682        client_connection_id: ConnectionId,
1683        client_sink: FrameSink,
1684        client_corr: u64,
1685        module_id: &str,
1686        busy_refusals: bool,
1687    ) -> Result<PendingRouteBindRelay, ForwardingError> {
1688        let permit =
1689            client_sink
1690                .try_reserve_owned()
1691                .map_err(|_| ForwardingError::ClientEgressClosed {
1692                    connection_id: client_connection_id,
1693                })?;
1694        self.begin_route_bind_relay_inner(
1695            client_connection_id,
1696            client_sink,
1697            subc_protocol::PROTOCOL_VERSION,
1698            client_corr,
1699            module_id,
1700            Principal::Direct,
1701            None,
1702            None,
1703            String::new(),
1704            None,
1705            None,
1706            RouteAuthority::default(),
1707            Instant::now() + std::time::Duration::from_secs(60),
1708            permit,
1709            busy_refusals,
1710            None,
1711        )
1712    }
1713
1714    pub(crate) fn begin_module_control_rpc_for(
1715        &self,
1716        module_id: &str,
1717        expected_op: &str,
1718        deadline: Instant,
1719    ) -> Result<PendingModuleControlRpc, ForwardingError> {
1720        self.begin_module_control_rpc_inner(module_id, expected_op, deadline, None, false)
1721    }
1722
1723    pub(crate) fn begin_health_probe_rpc_for(
1724        &self,
1725        module_id: &str,
1726        expected_op: &str,
1727        probe_started_at: Instant,
1728        deadline: Instant,
1729    ) -> Result<PendingModuleControlRpc, ForwardingError> {
1730        self.begin_module_control_rpc_inner(
1731            module_id,
1732            expected_op,
1733            deadline,
1734            Some(probe_started_at),
1735            false,
1736        )
1737    }
1738
1739    pub(crate) fn begin_drain_health_probe_rpc_for(
1740        &self,
1741        module_id: &str,
1742        expected_op: &str,
1743        probe_started_at: Instant,
1744        deadline: Instant,
1745    ) -> Result<PendingModuleControlRpc, ForwardingError> {
1746        self.begin_module_control_rpc_inner(
1747            module_id,
1748            expected_op,
1749            deadline,
1750            Some(probe_started_at),
1751            true,
1752        )
1753    }
1754
1755    /// A health probe addressed to one endpoint, in whichever slot it is.
1756    ///
1757    /// Every other control RPC resolves the id's ACTIVE endpoint, which is how
1758    /// a swap candidate (not active until cutover) and a superseded incumbent
1759    /// (not active after it) are unreachable by them. A swap needs to probe
1760    /// exactly those two: the candidate before promoting it, and the incumbent
1761    /// for its busy gauges while it drains.
1762    pub(crate) fn begin_endpoint_health_probe_rpc_for(
1763        &self,
1764        endpoint: ModuleEndpointId,
1765        expected_op: &str,
1766        probe_started_at: Instant,
1767        deadline: Instant,
1768    ) -> Result<PendingModuleControlRpc, ForwardingError> {
1769        let inner = self.write_inner()?;
1770        let module = module_connection_for_endpoint_locked(&inner, endpoint)
1771            .cloned()
1772            .ok_or(ForwardingError::NoModuleConnection)?;
1773        let module_id = inner
1774            .module_id_by_endpoint
1775            .get(&endpoint)
1776            .cloned()
1777            .unwrap_or_default();
1778        // A draining incumbent is exactly what this probes for busy gauges, so
1779        // draining is allowed, as it is for the by-id drain probe.
1780        self.begin_control_rpc_locked(
1781            inner,
1782            &module_id,
1783            module,
1784            expected_op,
1785            deadline,
1786            Some(probe_started_at),
1787            true,
1788        )
1789    }
1790
1791    fn begin_module_control_rpc_inner(
1792        &self,
1793        module_id: &str,
1794        expected_op: &str,
1795        deadline: Instant,
1796        health_probe_started_at: Option<Instant>,
1797        allow_draining: bool,
1798    ) -> Result<PendingModuleControlRpc, ForwardingError> {
1799        let inner = self.write_inner()?;
1800        let module = inner
1801            .modules_by_id
1802            .get(module_id)
1803            .cloned()
1804            .ok_or(ForwardingError::NoModuleConnection)?;
1805        self.begin_control_rpc_locked(
1806            inner,
1807            module_id,
1808            module,
1809            expected_op,
1810            deadline,
1811            health_probe_started_at,
1812            allow_draining,
1813        )
1814    }
1815
1816    #[allow(clippy::too_many_arguments)]
1817    fn begin_control_rpc_locked(
1818        &self,
1819        mut inner: InnerGuard<RwLockWriteGuard<'_, ForwardingInner>>,
1820        module_id: &str,
1821        module: ModuleConnection,
1822        expected_op: &str,
1823        deadline: Instant,
1824        health_probe_started_at: Option<Instant>,
1825        allow_draining: bool,
1826    ) -> Result<PendingModuleControlRpc, ForwardingError> {
1827        if !allow_draining && inner.draining_endpoints.contains_key(&module.endpoint) {
1828            return Err(ForwardingError::ModuleReloading {
1829                module_id: module_id.to_string(),
1830            });
1831        }
1832        if inner
1833            .closing_connections
1834            .contains(&module.endpoint.connection_id)
1835        {
1836            return Err(ForwardingError::ConnectionClosing {
1837                connection_id: module.endpoint.connection_id,
1838            });
1839        }
1840        if health_probe_started_at.is_some() {
1841            // Recurring health probes are serial per endpoint. Once the next one
1842            // starts, an older answer can no longer improve the current snapshot,
1843            // so retaining more than the newest unanswered probe has no value.
1844            inner
1845                .health_probe_tombstones
1846                .retain(|(endpoint, _), _| *endpoint != module.endpoint);
1847        }
1848        let corr = match inner.allocate_control_corr(module.endpoint) {
1849            Ok(corr) => corr,
1850            Err(err) => {
1851                drop(inner);
1852                self.request_connection_close(
1853                    module.endpoint.connection_id,
1854                    CloseReason::new(
1855                        "control_correlation_exhausted",
1856                        "daemon-originated channel-0 correlation space exhausted",
1857                    ),
1858                );
1859                return Err(err);
1860            }
1861        };
1862        let (sender, receiver) = oneshot::channel();
1863        inner.pending_control_rpcs.insert(
1864            (module.endpoint, corr),
1865            PendingModuleControlRpcEntry {
1866                expected_op: expected_op.to_string(),
1867                deadline,
1868                health_probe_started_at,
1869                sender,
1870            },
1871        );
1872
1873        Ok(PendingModuleControlRpc {
1874            endpoint: module.endpoint,
1875            module_sink: module.sink,
1876            negotiated_ver: module.negotiated_ver,
1877            corr,
1878            receiver,
1879        })
1880    }
1881
1882    #[allow(clippy::too_many_arguments)]
1883    fn begin_route_bind_relay_inner(
1884        &self,
1885        client_connection_id: ConnectionId,
1886        client_sink: FrameSink,
1887        client_negotiated_ver: u8,
1888        client_corr: u64,
1889        expected_module_id: &str,
1890        principal: Principal,
1891        scope: Option<BoundScope>,
1892        project_root: Option<ProjectRootId>,
1893        harness: String,
1894        build_class: Option<String>,
1895        operator_app: Option<crate::operator_apps::OperatorAppStamp>,
1896        authority: RouteAuthority,
1897        deadline: Instant,
1898        client_permit: crate::router::EgressPermit,
1899        busy_refusals: bool,
1900        accepts_close_reasons: Option<Vec<String>>,
1901    ) -> Result<PendingRouteBindRelay, ForwardingError> {
1902        let mut inner = self.write_inner()?;
1903        // HELLO and route.open can run on different tasks. Decide the role under
1904        // the same lock that installs endpoints and reserves client channels so
1905        // neither task can turn one connection into both kinds of owner.
1906        if inner
1907            .endpoint_by_connection
1908            .contains_key(&client_connection_id)
1909        {
1910            return Err(ForwardingError::ConnectionRoleConflict {
1911                connection_id: client_connection_id,
1912            });
1913        }
1914        if inner.closing_connections.contains(&client_connection_id) {
1915            return Err(ForwardingError::ConnectionClosing {
1916                connection_id: client_connection_id,
1917            });
1918        }
1919        let module = inner
1920            .modules_by_id
1921            .get(expected_module_id)
1922            .cloned()
1923            .ok_or(ForwardingError::NoModuleConnection)?;
1924        if inner.draining_endpoints.contains_key(&module.endpoint) {
1925            return Err(ForwardingError::ModuleReloading {
1926                module_id: expected_module_id.to_string(),
1927            });
1928        }
1929        if let Some(fence) = authority.capability_fence.as_ref() {
1930            if fence.target_connection != module.endpoint.connection_id {
1931                return Err(ForwardingError::TargetRegistrationChanged(
1932                    fence.registration_changed().message,
1933                ));
1934            }
1935        }
1936        if inner
1937            .closing_connections
1938            .contains(&module.endpoint.connection_id)
1939        {
1940            return Err(ForwardingError::ConnectionClosing {
1941                connection_id: module.endpoint.connection_id,
1942            });
1943        }
1944
1945        let corr = match inner.allocate_control_corr(module.endpoint) {
1946            Ok(corr) => corr,
1947            Err(err) => {
1948                drop(inner);
1949                self.request_connection_close(
1950                    module.endpoint.connection_id,
1951                    CloseReason::new(
1952                        "control_correlation_exhausted",
1953                        "daemon-originated channel-0 correlation space exhausted",
1954                    ),
1955                );
1956                return Err(err);
1957            }
1958        };
1959        let (client_channel, client_epoch, module_channel, module_epoch) =
1960            inner.allocate_route_slots(client_connection_id, module.endpoint)?;
1961        let client_key = ClientRouteKey {
1962            connection_id: client_connection_id,
1963            channel: client_channel,
1964        };
1965        let module_key = ModuleRouteKey {
1966            endpoint: module.endpoint,
1967            channel: module_channel,
1968        };
1969        let reservation = RouteReservation {
1970            client_key,
1971            module_key,
1972            client_epoch,
1973            module_epoch,
1974            project_root,
1975        };
1976        // The target is the endpoint reserved under this lock, never the
1977        // by-id registration route.open read before it waited for egress.
1978        let target_authority = target_authority_locked(&inner, &module);
1979        let response_body = route_open_reply_body(
1980            &ClientControlResponse::RouteOpen {
1981                request_window: None,
1982                watch_window: None,
1983                route_channel: client_channel,
1984                route_epoch: client_epoch,
1985            },
1986            &target_authority,
1987            &authority.incarnation,
1988        )?;
1989        let route_open_frame = Frame::build_with_version(
1990            client_negotiated_ver,
1991            FrameType::Response,
1992            Flags::new(false, Priority::Passive, false),
1993            0,
1994            0,
1995            client_corr,
1996            response_body,
1997        )
1998        .map_err(|err| ForwardingError::RouteOpenBuild(err.to_string()))?;
1999        let (sender, receiver) = oneshot::channel();
2000        inner.reserved_client.insert(client_key, module_key);
2001        inner.reserved_module.insert(module_key, client_key);
2002        inner.pending_relays.insert(
2003            (module.endpoint, corr),
2004            PendingRouteBindRelayEntry {
2005                reservation,
2006                client_sink,
2007                client_negotiated_ver,
2008                client_permit,
2009                route_open_frame,
2010                busy_refusals,
2011                accepts_close_reasons,
2012                request_window: window_for(&module.concurrency),
2013                watch_window: (busy_refusals && module.concurrency == Concurrency::ModuleManaged)
2014                    .then_some(DEFAULT_MODULE_MANAGED_WATCH_WINDOW),
2015                principal,
2016                scope,
2017                harness,
2018                build_class,
2019                operator_app,
2020                caller_authority: authority.caller,
2021                target_authority,
2022                capability_fence: authority.capability_fence,
2023                incarnation: authority.incarnation,
2024                deadline,
2025                relay_enqueued: false,
2026                sender,
2027            },
2028        );
2029
2030        Ok(PendingRouteBindRelay {
2031            endpoint: module.endpoint,
2032            module_sink: module.sink,
2033            negotiated_ver: module.negotiated_ver,
2034            client_channel,
2035            client_epoch,
2036            module_channel,
2037            module_epoch,
2038            corr,
2039            receiver,
2040        })
2041    }
2042
2043    /// Called by `route.open` right after the route.bind entered the module's
2044    /// egress queue.
2045    ///
2046    /// The module reader runs concurrently with `route.open`, so a fast module
2047    /// can receive the bind, ack it, and have the reader commit the route
2048    /// before this runs. A missing entry therefore does not mean the bind was
2049    /// abandoned: only a removal recorded in `relays_released_before_enqueue`
2050    /// does. Telling the two apart is what stops `route.open` from sending a
2051    /// GOODBYE for a route that was just committed.
2052    pub(crate) fn mark_route_bind_relay_enqueued(
2053        &self,
2054        endpoint: ModuleEndpointId,
2055        corr: u64,
2056    ) -> Result<RouteBindRelayMark, ForwardingError> {
2057        let mut inner = self.write_inner()?;
2058        if let Some(pending) = inner.pending_relays.get_mut(&(endpoint, corr)) {
2059            pending.relay_enqueued = true;
2060            return Ok(RouteBindRelayMark::Marked);
2061        }
2062        if inner
2063            .relays_released_before_enqueue
2064            .remove(&(endpoint, corr))
2065        {
2066            return Ok(RouteBindRelayMark::ReleasedWithoutReply);
2067        }
2068        Ok(RouteBindRelayMark::SettledByReply)
2069    }
2070
2071    pub(crate) fn release_client_route(
2072        &self,
2073        client_connection_id: ConnectionId,
2074        client_channel: u16,
2075        expected_epoch: u32,
2076    ) -> Result<RouteRelease, ForwardingError> {
2077        let mut inner = self.write_inner()?;
2078        let release = release_client_route_locked(
2079            &mut inner,
2080            ClientRouteKey {
2081                connection_id: client_connection_id,
2082                channel: client_channel,
2083            },
2084            expected_epoch,
2085        );
2086        self.record_route_release(&release);
2087        Ok(release)
2088    }
2089
2090    pub(crate) fn release_module_route(
2091        &self,
2092        module_connection_id: ConnectionId,
2093        module_channel: u16,
2094        expected_epoch: u32,
2095    ) -> Result<RouteRelease, ForwardingError> {
2096        let mut inner = self.write_inner()?;
2097        let Some(endpoint) = inner
2098            .endpoint_by_connection
2099            .get(&module_connection_id)
2100            .copied()
2101        else {
2102            return Ok(RouteRelease::Absent);
2103        };
2104        let release = release_module_route_locked(
2105            &mut inner,
2106            ModuleRouteKey {
2107                endpoint,
2108                channel: module_channel,
2109            },
2110            expected_epoch,
2111        );
2112        self.record_route_release(&release);
2113        Ok(release)
2114    }
2115
2116    pub(crate) fn abort_pending_relay(
2117        &self,
2118        endpoint: ModuleEndpointId,
2119        corr: u64,
2120        outcome: RouteBindRelayOutcome,
2121    ) -> Result<Option<GoodbyeTarget>, ForwardingError> {
2122        let mut inner = self.write_inner()?;
2123        let Some(pending) = inner.pending_relays.remove(&(endpoint, corr)) else {
2124            // If another path dropped the relay while `route.open` was still
2125            // sending the bind, and that open is now giving up without marking
2126            // it (its send failed or it was cancelled), forget the record so it
2127            // cannot outlive the open.
2128            inner
2129                .relays_released_before_enqueue
2130                .remove(&(endpoint, corr));
2131            return Ok(None);
2132        };
2133        release_reserved_route_locked(
2134            &mut inner,
2135            pending.reservation.client_key,
2136            pending.reservation.module_key,
2137        );
2138        let target = pending
2139            .relay_enqueued
2140            .then(|| abandoned_route_target(&inner, &pending.reservation));
2141        let _ = pending.sender.send(outcome);
2142        Ok(target.flatten())
2143    }
2144
2145    pub(crate) fn cancel_module_control_rpc(
2146        &self,
2147        endpoint: ModuleEndpointId,
2148        corr: u64,
2149    ) -> Result<(), ForwardingError> {
2150        self.write_inner()?
2151            .pending_control_rpcs
2152            .remove(&(endpoint, corr));
2153        Ok(())
2154    }
2155
2156    pub(crate) fn tombstone_health_probe_rpc(
2157        &self,
2158        endpoint: ModuleEndpointId,
2159        corr: u64,
2160    ) -> Result<bool, ForwardingError> {
2161        let key = (endpoint, corr);
2162        let expires_at = Instant::now() + HEALTH_PROBE_TOMBSTONE_TTL;
2163        {
2164            let mut inner = self.write_inner()?;
2165            let Some(pending) = inner.pending_control_rpcs.remove(&key) else {
2166                return Ok(false);
2167            };
2168            let Some(probe_started_at) = pending.health_probe_started_at else {
2169                inner.pending_control_rpcs.insert(key, pending);
2170                return Ok(false);
2171            };
2172            let module_id = inner
2173                .module_id_by_endpoint
2174                .get(&endpoint)
2175                .cloned()
2176                .unwrap_or_else(|| "unknown".to_string());
2177            inner.health_probe_tombstones.insert(
2178                key,
2179                HealthProbeTombstone {
2180                    expected_op: pending.expected_op,
2181                    module_id,
2182                    probe_started_at,
2183                    expires_at,
2184                },
2185            );
2186        }
2187        self.schedule_health_probe_tombstone_expiration(key, expires_at);
2188        Ok(true)
2189    }
2190
2191    fn schedule_health_probe_tombstone_expiration(
2192        &self,
2193        key: (ModuleEndpointId, u64),
2194        expires_at: Instant,
2195    ) {
2196        let inner = Arc::downgrade(&self.inner);
2197        tokio::spawn(async move {
2198            tokio::time::sleep_until(expires_at).await;
2199            let Some(inner) = inner.upgrade() else {
2200                return;
2201            };
2202            let Ok(mut inner) = inner.write() else {
2203                return;
2204            };
2205            let expired = inner
2206                .health_probe_tombstones
2207                .get(&key)
2208                .is_some_and(|tombstone| tombstone.expires_at <= Instant::now());
2209            if expired {
2210                inner.health_probe_tombstones.remove(&key);
2211            }
2212        });
2213    }
2214
2215    pub(crate) fn complete_pending_relay(
2216        &self,
2217        connection_id: ConnectionId,
2218        corr: u64,
2219        outcome: RouteBindRelayOutcome,
2220    ) -> Result<PendingRelayCompletion, ForwardingError> {
2221        self.complete_pending_relay_fenced(connection_id, corr, outcome, |_| None)
2222    }
2223
2224    /// Settle a route.bind reply. An accepted bind with a capability fence
2225    /// commits only if `fence_refusal` finds nothing wrong with it now.
2226    pub(crate) fn complete_pending_relay_fenced(
2227        &self,
2228        connection_id: ConnectionId,
2229        corr: u64,
2230        outcome: RouteBindRelayOutcome,
2231        fence_refusal: impl FnOnce(&CapabilityFence) -> Option<ErrorBody>,
2232    ) -> Result<PendingRelayCompletion, ForwardingError> {
2233        let mut inner = self.write_inner()?;
2234        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2235            return Ok(PendingRelayCompletion {
2236                settled: false,
2237                abandoned: None,
2238            });
2239        };
2240        let Some(pending) = inner.pending_relays.remove(&(endpoint, corr)) else {
2241            return Ok(PendingRelayCompletion {
2242                settled: false,
2243                abandoned: None,
2244            });
2245        };
2246
2247        if Instant::now() >= pending.deadline {
2248            release_reserved_route_locked(
2249                &mut inner,
2250                pending.reservation.client_key,
2251                pending.reservation.module_key,
2252            );
2253            let abandoned = matches!(outcome, RouteBindRelayOutcome::Accepted)
2254                .then(|| abandoned_route_target(&inner, &pending.reservation))
2255                .flatten();
2256            let _ = pending
2257                .sender
2258                .send(RouteBindRelayOutcome::DaemonRejected(ErrorBody {
2259                    code: "module_timeout".to_string(),
2260                    message: "route.bind response arrived after its daemon deadline".to_string(),
2261                    detail: None,
2262                }));
2263            return Ok(PendingRelayCompletion {
2264                settled: true,
2265                abandoned,
2266            });
2267        }
2268
2269        let fence_refusal = match (&outcome, &pending.capability_fence) {
2270            (RouteBindRelayOutcome::Accepted, Some(fence)) => fence_refusal(fence),
2271            _ => None,
2272        };
2273        // Read once: the scope check reads the wall clock, which can step
2274        // backwards, so a guard and a body that each read it could disagree.
2275        let scope_refusal = match (&outcome, &pending.scope) {
2276            (RouteBindRelayOutcome::Accepted, Some(scope)) => scope_refusal_locked(&inner, scope),
2277            _ => None,
2278        };
2279        // These readiness reads are not atomic with publication: a route may
2280        // commit after Dead. Taking a spawn transition lock here would invert
2281        // the publication lock order. Retirement, in one critical section,
2282        // stops every connection bound by the launch's claims and its own
2283        // registration channel from reading or sending frames, and shuts that
2284        // channel.
2285        // Once that step completes, no new request can cross the transient route
2286        // to or from the retired launch; connection teardown removes the route.
2287        match outcome {
2288            // Three shapes of "the client is not there to receive this route" that
2289            // must resolve identically: its egress is already closed, or it is
2290            // marked closing (its connection loop has been asked to end, but has
2291            // not drained yet, so the sink is still open), or its spawn is dead
2292            // before connection-close notifications have reached that loop.
2293            //
2294            // Only the first used to be caught here. The second fell through to
2295            // `commit_route_locked`, which refuses a closing client with
2296            // `ConnectionClosing` -- and this function is called from the MODULE
2297            // connection's frame handler, so that refusal ended the module's
2298            // connection instead of this one client's route. One dying client's
2299            // route.open then took down a connection carrying every other
2300            // client's routes to that module.
2301            //
2302            // The remedy for both is the same, which is why they share an arm:
2303            // give back the reserved handle pair, tell the waiting route.open the
2304            // route is gone, and report the module-side channel so the caller can
2305            // send a channel-scoped GOODBYE for the binding the module just
2306            // created. Nothing here touches the module connection.
2307            RouteBindRelayOutcome::Accepted
2308                if pending.client_sink.is_closed()
2309                    || spawn_connection_dead(
2310                        &inner,
2311                        pending.reservation.client_key.connection_id,
2312                    )
2313                    || inner
2314                        .closing_connections
2315                        .contains(&pending.reservation.client_key.connection_id) =>
2316            {
2317                let reason = if pending.client_sink.is_closed() {
2318                    "client egress closed before route publication"
2319                } else {
2320                    "client connection is closing before route publication"
2321                };
2322                release_reserved_route_locked(
2323                    &mut inner,
2324                    pending.reservation.client_key,
2325                    pending.reservation.module_key,
2326                );
2327                // Not gated on `relay_enqueued`: an ack proves the module
2328                // received the bind, and `route.open` sends nothing for a
2329                // relay a reply already settled, so this is the only GOODBYE.
2330                let abandoned = abandoned_route_target(&inner, &pending.reservation);
2331                let _ = pending
2332                    .sender
2333                    .send(RouteBindRelayOutcome::ModuleGone(reason.to_string()));
2334                return Ok(PendingRelayCompletion {
2335                    settled: true,
2336                    abandoned,
2337                });
2338            }
2339            // The endpoint that acked this bind is no longer accepting new
2340            // routes, for one of two reasons. Either it was the module's active
2341            // endpoint when this relay was reserved and a blue/green swap has
2342            // since promoted a candidate (the replacement process registered
2343            // beside it) into the active slot, superseding it; or a daemon
2344            // drain has gated it, and the ack arrived before the ordered module
2345            // drain settled pending relays. The module did nothing wrong: it
2346            // bound the route it was asked to bind, and the endpoint still
2347            // carries every other client's routes until it is drained. So the
2348            // ack is settled here, while the pending entry still holds the
2349            // client's sender and the reserved handle pair: release the pair,
2350            // refuse the waiting route.open with `module_reloading`, which
2351            // callers retry (after a swap the retry reserves on the promoted
2352            // endpoint), and hand back the module-side channel so the caller
2353            // sends one channel-scoped GOODBYE for the binding the module just
2354            // created. Returning an error instead would end the module
2355            // connection all those other routes share; nothing here touches it.
2356            //
2357            // An endpoint that stopped being active any other way is stale
2358            // (replaced, but not by a swap and not draining). It still falls
2359            // through to `commit_route_locked`, which refuses it with
2360            // `StaleModuleEndpoint` exactly as before swaps existed.
2361            RouteBindRelayOutcome::Accepted
2362                if inner.superseded_endpoints.contains_key(&endpoint)
2363                    || spawn_connection_dead(&inner, connection_id)
2364                    || inner.draining_endpoints.contains_key(&endpoint) =>
2365            {
2366                release_reserved_route_locked(
2367                    &mut inner,
2368                    pending.reservation.client_key,
2369                    pending.reservation.module_key,
2370                );
2371                // Not gated on `relay_enqueued`: an ack proves the module
2372                // received the bind, whether or not the enqueue mark was set.
2373                let abandoned = abandoned_route_target(&inner, &pending.reservation);
2374                let module_id = inner
2375                    .module_id_by_endpoint
2376                    .get(&endpoint)
2377                    .cloned()
2378                    .unwrap_or_else(|| "unknown".to_string());
2379                let _ = pending
2380                    .sender
2381                    .send(RouteBindRelayOutcome::DaemonRejected(ErrorBody::new(
2382                        "module_reloading",
2383                        format!("module_id '{module_id}' is reloading"),
2384                    )));
2385                return Ok(PendingRelayCompletion {
2386                    settled: true,
2387                    abandoned,
2388                });
2389            }
2390            // The scope the open was admitted under ended or changed after
2391            // admission. The module bound a route under a stamp that is no
2392            // longer true, so it must not become routable. Settled here like
2393            // the superseded arm above, never as an error from
2394            // `commit_route_locked`, which would close the module's whole
2395            // connection and every other client's routes to it: release the
2396            // pair, answer the waiting route.open by name, and hand back the
2397            // module-side channel for one channel-scoped GOODBYE.
2398            RouteBindRelayOutcome::Accepted if scope_refusal.is_some() => {
2399                let refusal = scope_refusal.expect("guard checked the refusal");
2400                let refused = RouteBindRelayOutcome::DaemonRejected(refusal);
2401                return Ok(refuse_acked_bind_locked(&mut inner, pending, refused));
2402            }
2403            // The caller's or the target's authority changed after the open
2404            // was attested, so the attestation the module bound on is no
2405            // longer true. Settled like the scope arm, never as an error from
2406            // `commit_route_locked`, which would close the module's shared
2407            // connection: release the pair, refuse the open by name, and hand
2408            // back the module-side channel for one channel-scoped GOODBYE.
2409            RouteBindRelayOutcome::Accepted
2410                if authority_stale_locked(&inner, pending.caller_authority.as_ref())
2411                    || authority_stale_locked(&inner, pending.target_authority.pair()) =>
2412            {
2413                let refused = RouteBindRelayOutcome::DaemonRejected(ErrorBody::new(
2414                    subc_protocol::error_codes::STALE_AUTHORITY_EPOCH,
2415                    "the caller's or target's authority changed while the route was binding",
2416                ));
2417                return Ok(refuse_acked_bind_locked(&mut inner, pending, refused));
2418            }
2419            // The opener's capability deny check no longer holds: the target
2420            // now provides a capability the opener must never reach, or the
2421            // admitted registration is gone. Settled like the arms above.
2422            RouteBindRelayOutcome::Accepted if fence_refusal.is_some() => {
2423                let refusal = fence_refusal.expect("guard checked the refusal");
2424                let refused = RouteBindRelayOutcome::DaemonRejected(refusal);
2425                return Ok(refuse_acked_bind_locked(&mut inner, pending, refused));
2426            }
2427            RouteBindRelayOutcome::Accepted => {
2428                #[cfg(all(test, target_os = "linux"))]
2429                if let Some(pause) = self.route_commit_pause.lock().unwrap().take() {
2430                    let _ = pause.reached.send(());
2431                    pause
2432                        .release
2433                        .recv_timeout(Duration::from_secs(5))
2434                        .expect("test must release bind publication");
2435                }
2436                let abandoned = commit_route_locked(&mut inner, pending)?;
2437                return Ok(PendingRelayCompletion {
2438                    settled: true,
2439                    abandoned,
2440                });
2441            }
2442            terminal => {
2443                release_reserved_route_locked(
2444                    &mut inner,
2445                    pending.reservation.client_key,
2446                    pending.reservation.module_key,
2447                );
2448                let _ = pending.sender.send(terminal);
2449            }
2450        }
2451        Ok(PendingRelayCompletion {
2452            settled: true,
2453            abandoned: None,
2454        })
2455    }
2456
2457    pub(crate) fn pending_module_control_op(
2458        &self,
2459        connection_id: ConnectionId,
2460        corr: u64,
2461    ) -> Result<Option<String>, ForwardingError> {
2462        let inner = self.read_inner()?;
2463        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2464            return Ok(None);
2465        };
2466        let key = (endpoint, corr);
2467        Ok(inner
2468            .pending_control_rpcs
2469            .get(&key)
2470            .map(|pending| pending.expected_op.clone())
2471            .or_else(|| {
2472                inner
2473                    .health_probe_tombstones
2474                    .get(&key)
2475                    .filter(|tombstone| tombstone.expires_at > Instant::now())
2476                    .map(|tombstone| tombstone.expected_op.clone())
2477            }))
2478    }
2479
2480    pub(crate) fn complete_module_control_rpc(
2481        &self,
2482        connection_id: ConnectionId,
2483        corr: u64,
2484        actual_op: Option<&str>,
2485        outcome: ModuleControlRpcOutcome,
2486    ) -> Result<ModuleControlRpcCompletion, ForwardingError> {
2487        let now = Instant::now();
2488        let mut inner = self.write_inner()?;
2489        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2490            return Ok(ModuleControlRpcCompletion::Unknown);
2491        };
2492        let key = (endpoint, corr);
2493        if let Some(pending) = inner.pending_control_rpcs.remove(&key) {
2494            if now >= pending.deadline {
2495                let late_health_answer = pending.health_probe_started_at.map(|probe_started_at| {
2496                    ModuleControlRpcCompletion::LateHealthAnswer {
2497                        module_id: inner
2498                            .module_id_by_endpoint
2499                            .get(&endpoint)
2500                            .cloned()
2501                            .unwrap_or_else(|| "unknown".to_string()),
2502                        latency: now.saturating_duration_since(probe_started_at),
2503                    }
2504                });
2505                let _ = pending
2506                    .sender
2507                    .send(ModuleControlRpcOutcome::DeadlineElapsed);
2508                return Ok(late_health_answer.unwrap_or(ModuleControlRpcCompletion::Settled));
2509            }
2510            let outcome = match actual_op {
2511                Some(actual) if actual != pending.expected_op => {
2512                    ModuleControlRpcOutcome::UnexpectedOp {
2513                        expected: pending.expected_op,
2514                        actual: actual.to_string(),
2515                    }
2516                }
2517                _ => outcome,
2518            };
2519            let _ = pending.sender.send(outcome);
2520            return Ok(ModuleControlRpcCompletion::Settled);
2521        }
2522
2523        let Some(tombstone) = inner.health_probe_tombstones.remove(&key) else {
2524            return Ok(ModuleControlRpcCompletion::Unknown);
2525        };
2526        if tombstone.expires_at <= now {
2527            return Ok(ModuleControlRpcCompletion::Unknown);
2528        }
2529        Ok(ModuleControlRpcCompletion::LateHealthAnswer {
2530            module_id: tombstone.module_id,
2531            latency: now.saturating_duration_since(tombstone.probe_started_at),
2532        })
2533    }
2534
2535    #[cfg(test)]
2536    pub(crate) fn health_probe_tombstone_count(&self) -> Result<usize, ForwardingError> {
2537        Ok(self.read_inner()?.health_probe_tombstones.len())
2538    }
2539
2540    #[cfg(test)]
2541    pub(crate) fn closing_connection_count(&self) -> Result<usize, ForwardingError> {
2542        Ok(self.read_inner()?.closing_connections.len())
2543    }
2544
2545    /// Reserved-but-uncommitted route handles, counted on both index sides, so
2546    /// a test can assert a reservation pair was actually given back.
2547    #[cfg(test)]
2548    pub(crate) fn reserved_route_count(&self) -> Result<(usize, usize), ForwardingError> {
2549        let inner = self.read_inner()?;
2550        Ok((inner.reserved_client.len(), inner.reserved_module.len()))
2551    }
2552
2553    pub(crate) fn module_endpoint_for_connection(
2554        &self,
2555        connection_id: ConnectionId,
2556    ) -> Result<Option<ModuleEndpointId>, ForwardingError> {
2557        Ok(self
2558            .read_inner()?
2559            .endpoint_by_connection
2560            .get(&connection_id)
2561            .copied())
2562    }
2563
2564    /// Looks up the module registered on a data-plane connection so route-drop
2565    /// diagnostics name the emitter instead of only reporting a daemon total.
2566    pub(crate) fn module_id_for_connection(
2567        &self,
2568        connection_id: ConnectionId,
2569    ) -> Result<Option<String>, ForwardingError> {
2570        let inner = self.read_inner()?;
2571        Ok(inner
2572            .endpoint_by_connection
2573            .get(&connection_id)
2574            .and_then(|endpoint| inner.module_id_by_endpoint.get(endpoint))
2575            .cloned())
2576    }
2577
2578    /// Whether the daemon ever allocated `(channel, epoch)` on this module
2579    /// connection. Epochs on a module channel are handed out as 1, 2, 3, ...
2580    /// and the last one handed out is remembered until the connection ends, so
2581    /// every epoch from 1 up to that one was a real route at some point. Used
2582    /// only on the drop path, to tell a module still sending on a route the
2583    /// daemon released from one sending on a route that never existed.
2584    pub(crate) fn module_route_epoch_was_allocated(
2585        &self,
2586        connection_id: ConnectionId,
2587        channel: u16,
2588        epoch: u32,
2589    ) -> Result<bool, ForwardingError> {
2590        let inner = self.read_inner()?;
2591        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2592            return Ok(false);
2593        };
2594        Ok(inner
2595            .module_slot_epochs
2596            .get(&ModuleRouteKey { endpoint, channel })
2597            .is_some_and(|last| epoch != 0 && epoch <= *last))
2598    }
2599
2600    pub(crate) fn has_live_module_connection(
2601        &self,
2602        module_id: &str,
2603    ) -> Result<bool, ForwardingError> {
2604        Ok(self.read_inner()?.modules_by_id.contains_key(module_id))
2605    }
2606
2607    /// Admission and route teardown share the forwarding-then-flow lock order.
2608    /// No asynchronous work may split validation from recording the credits.
2609    pub(crate) fn try_admit_request(
2610        &self,
2611        route: &Arc<RouteBinding>,
2612        epoch: u32,
2613        corr: u64,
2614        subscription: bool,
2615    ) -> Result<RequestAdmission, ForwardingError> {
2616        let inner = self.read_inner()?;
2617        let key = ClientRouteKey {
2618            connection_id: route.client_connection_id,
2619            channel: route.client_channel,
2620        };
2621        if epoch != route.client_epoch
2622            || !inner
2623                .client_to_module
2624                .get(&key)
2625                .is_some_and(|current| Arc::ptr_eq(current, route))
2626        {
2627            return Ok(RequestAdmission::Stale);
2628        }
2629        let admission = route.flow.try_acquire_tagged(corr, subscription);
2630        Ok(match admission {
2631            RequestAdmission::Stale
2632                if inner
2633                    .draining_endpoints
2634                    .contains_key(&route.module_endpoint) =>
2635            {
2636                RequestAdmission::ModuleReloading
2637            }
2638            admission => admission,
2639        })
2640    }
2641
2642    pub(crate) fn lookup_data_route(
2643        &self,
2644        connection_id: ConnectionId,
2645        channel: u16,
2646        epoch: u32,
2647    ) -> Result<DataRoute, ForwardingError> {
2648        let inner = self.read_inner()?;
2649        let state = if let Some(endpoint) =
2650            inner.endpoint_by_connection.get(&connection_id).copied()
2651        {
2652            let key = ModuleRouteKey { endpoint, channel };
2653            match inner.module_to_client.get(&key) {
2654                Some(route) if route.module_epoch == epoch => {
2655                    DataRouteState::Bound(Arc::clone(route))
2656                }
2657                Some(_) => DataRouteState::EpochMismatch,
2658                None if inner.reserved_module.contains_key(&key)
2659                    && inner.module_slot_epochs.get(&key).copied() == Some(epoch) =>
2660                {
2661                    DataRouteState::Reserved
2662                }
2663                None if inner.reserved_module.contains_key(&key) => DataRouteState::EpochMismatch,
2664                None => DataRouteState::Absent,
2665            }
2666        } else {
2667            let key = ClientRouteKey {
2668                connection_id,
2669                channel,
2670            };
2671            match inner.client_to_module.get(&key) {
2672                Some(route) if route.client_epoch == epoch => {
2673                    DataRouteState::Bound(Arc::clone(route))
2674                }
2675                Some(_) => DataRouteState::EpochMismatch,
2676                None if inner.reserved_client.contains_key(&key)
2677                    && inner.client_slot_epochs.get(&key).copied() == Some(epoch) =>
2678                {
2679                    DataRouteState::Reserved
2680                }
2681                None if inner.reserved_client.contains_key(&key) => DataRouteState::EpochMismatch,
2682                None => DataRouteState::Absent,
2683            }
2684        };
2685        Ok(
2686            if inner.endpoint_by_connection.contains_key(&connection_id) {
2687                DataRoute::Module(state)
2688            } else {
2689                DataRoute::Client(state)
2690            },
2691        )
2692    }
2693
2694    #[cfg(test)]
2695    pub(crate) fn inject_client_slot_epoch(
2696        &self,
2697        connection_id: ConnectionId,
2698        channel: u16,
2699        last_epoch: u32,
2700    ) {
2701        let mut inner = self.write_inner().expect("forwarding lock");
2702        inner.client_slot_epochs.insert(
2703            ClientRouteKey {
2704                connection_id,
2705                channel,
2706            },
2707            last_epoch,
2708        );
2709        inner.next_client_channel.insert(connection_id, channel);
2710    }
2711
2712    #[cfg(test)]
2713    pub(crate) fn inject_module_slot_epoch(
2714        &self,
2715        endpoint: ModuleEndpointId,
2716        channel: u16,
2717        last_epoch: u32,
2718    ) {
2719        let mut inner = self.write_inner().expect("forwarding lock");
2720        inner
2721            .module_slot_epochs
2722            .insert(ModuleRouteKey { endpoint, channel }, last_epoch);
2723        inner.next_module_channel.insert(endpoint, channel);
2724    }
2725
2726    #[cfg(test)]
2727    pub(crate) fn inject_control_corr(&self, endpoint: ModuleEndpointId, next_corr: u64) {
2728        self.write_inner()
2729            .expect("forwarding lock")
2730            .next_control_corr
2731            .insert(endpoint, next_corr);
2732    }
2733
2734    pub(crate) fn cache_status(
2735        &self,
2736        endpoint: ModuleEndpointId,
2737        module_channel: u16,
2738        module_epoch: u32,
2739        status: String,
2740    ) -> Result<bool, ForwardingError> {
2741        let mut inner = self.write_inner()?;
2742        if !inner.module_id_by_endpoint.contains_key(&endpoint) {
2743            return Err(ForwardingError::StaleModuleEndpoint);
2744        }
2745
2746        let module_key = ModuleRouteKey {
2747            endpoint,
2748            channel: module_channel,
2749        };
2750        let handle = if let Some(route) = inner.module_to_client.get(&module_key) {
2751            (route.module_epoch == module_epoch).then_some((
2752                ClientRouteKey {
2753                    connection_id: route.client_connection_id,
2754                    channel: route.client_channel,
2755                },
2756                route.client_epoch,
2757            ))
2758        } else if let Some(client_key) = inner.reserved_module.get(&module_key).copied() {
2759            (inner.module_slot_epochs.get(&module_key).copied() == Some(module_epoch)).then_some((
2760                client_key,
2761                inner
2762                    .client_slot_epochs
2763                    .get(&client_key)
2764                    .copied()
2765                    .unwrap_or(0),
2766            ))
2767        } else {
2768            None
2769        };
2770
2771        if let Some(handle) = handle {
2772            inner.status.insert(handle, status);
2773            Ok(true)
2774        } else {
2775            debug!(
2776                module_channel,
2777                module_epoch,
2778                generation = endpoint.generation,
2779                connection_id = endpoint.connection_id.get(),
2780                "dropping stale status update for module route handle"
2781            );
2782            Ok(false)
2783        }
2784    }
2785
2786    pub(crate) fn route_poll_snapshot(
2787        &self,
2788        client_connection_id: ConnectionId,
2789        client_channel: u16,
2790        client_epoch: u32,
2791    ) -> Result<RoutePollSnapshot, ForwardingError> {
2792        let inner = self.read_inner()?;
2793        let client_key = ClientRouteKey {
2794            connection_id: client_connection_id,
2795            channel: client_channel,
2796        };
2797        let Some(route) = inner.client_to_module.get(&client_key) else {
2798            return Ok(RoutePollSnapshot::Absent);
2799        };
2800        if route.client_epoch != client_epoch
2801            || !inner
2802                .module_id_by_endpoint
2803                .contains_key(&route.module_endpoint)
2804        {
2805            return Ok(RoutePollSnapshot::Absent);
2806        }
2807        Ok(RoutePollSnapshot::Bound {
2808            module_id: route.module_id.clone(),
2809            status: inner.status.get(&(client_key, client_epoch)).cloned(),
2810        })
2811    }
2812
2813    pub fn active_binding_count(&self) -> Result<usize, ForwardingError> {
2814        Ok(self.read_inner()?.client_to_module.len())
2815    }
2816
2817    /// How many distinct client connections hold at least one committed route,
2818    /// alongside the largest number of routes any single connection holds.
2819    ///
2820    /// `connected_clients` alone cannot distinguish many clients with a route
2821    /// each from one client accumulating hundreds, and those have opposite
2822    /// causes. Reading it required an out-of-band `lsof` during a live
2823    /// investigation, and the count of connections was mistaken for a count of
2824    /// client processes — which sent two of us after cleanup paths that were
2825    /// working correctly.
2826    pub fn client_route_concentration(&self) -> Result<(usize, usize), ForwardingError> {
2827        let inner = self.read_inner()?;
2828        let mut per_connection: HashMap<ConnectionId, usize> = HashMap::new();
2829        for key in inner.client_to_module.keys() {
2830            *per_connection.entry(key.connection_id).or_insert(0) += 1;
2831        }
2832        let max = per_connection.values().copied().max().unwrap_or(0);
2833        Ok((per_connection.len(), max))
2834    }
2835
2836    pub fn has_route_channel(&self, route_channel: u16) -> Result<bool, ForwardingError> {
2837        let inner = self.read_inner()?;
2838        Ok(inner
2839            .client_to_module
2840            .keys()
2841            .any(|key| key.channel == route_channel))
2842    }
2843
2844    /// Whether daemon-wide shutdown has begun draining all providers.
2845    /// `None` means normal operation; during daemon shutdown, return the
2846    /// endpoint's measured result, or false if no completed measurement exists.
2847    pub(crate) fn daemon_drain_result_for_connection(
2848        &self,
2849        connection_id: ConnectionId,
2850    ) -> Result<Option<bool>, ForwardingError> {
2851        let inner = self.read_inner()?;
2852        Ok(inner.daemon_draining.then(|| {
2853            inner
2854                .endpoint_by_connection
2855                .get(&connection_id)
2856                .and_then(|endpoint| inner.daemon_drain_results.get(endpoint))
2857                .copied()
2858                .unwrap_or(false)
2859        }))
2860    }
2861
2862    #[cfg(unix)]
2863    pub(crate) fn record_daemon_drain_result(
2864        &self,
2865        endpoint: ModuleEndpointId,
2866        drained: bool,
2867    ) -> Result<(), ForwardingError> {
2868        let mut inner = self.write_inner()?;
2869        // Only update an endpoint captured at the start of daemon shutdown.
2870        // Teardown removes its entry, so a late wait cannot recreate the result
2871        // or attribute it to a replacement connection.
2872        if let Some(result) = inner.daemon_drain_results.get_mut(&endpoint) {
2873            *result = drained;
2874        }
2875        Ok(())
2876    }
2877
2878    /// Gate every provider atomically, including registrations racing shutdown.
2879    /// No supervisor lock is held while taking the forwarding lock.
2880    #[cfg(unix)]
2881    pub(crate) fn begin_daemon_drain(
2882        &self,
2883    ) -> Result<Vec<(String, ModuleEndpointId)>, ForwardingError> {
2884        let mut inner = self.write_inner()?;
2885        if inner.daemon_draining {
2886            return Ok(Vec::new());
2887        }
2888        inner.daemon_draining = true;
2889        let modules = inner
2890            .modules_by_id
2891            .iter()
2892            .map(|(id, module)| (id.clone(), module.endpoint))
2893            .collect::<Vec<_>>();
2894        for (_, endpoint) in &modules {
2895            inner.daemon_drain_results.insert(*endpoint, false);
2896            inner
2897                .draining_endpoints
2898                .insert(*endpoint, RouteCloseReason::Restart);
2899        }
2900        // Swap candidates and superseded incumbents are not routable, but they
2901        // are live endpoints that could still be sent module-control work, so
2902        // the daemon-wide gate covers them too. Only the active endpoints are
2903        // returned to the supervisor for measurement, one per module id.
2904        let off_slot_endpoints = inner
2905            .candidates_by_id
2906            .values()
2907            .map(|module| module.endpoint)
2908            .chain(inner.superseded_endpoints.keys().copied())
2909            .collect::<Vec<_>>();
2910        for endpoint in off_slot_endpoints {
2911            inner
2912                .draining_endpoints
2913                .insert(endpoint, RouteCloseReason::Restart);
2914        }
2915        Ok(modules)
2916    }
2917
2918    /// Begin draining whatever endpoint is ACTIVE for `module_id`.
2919    ///
2920    /// After a swap's cutover the active endpoint is the promoted candidate, so
2921    /// this must not be used to drain the incumbent; use
2922    /// [`Self::begin_endpoint_drain`] with the endpoint `cutover_candidate`
2923    /// returned.
2924    pub(crate) fn begin_module_drain(
2925        &self,
2926        module_id: &str,
2927        reason: RouteCloseReason,
2928    ) -> Result<Option<ModuleDrainTarget>, ForwardingError> {
2929        let mut inner = self.write_inner()?;
2930        let Some(module) = inner.modules_by_id.get(module_id).cloned() else {
2931            return Ok(None);
2932        };
2933        Ok(Some(begin_drain_locked(
2934            &mut inner, module_id, module, reason,
2935        )))
2936    }
2937
2938    /// Begin draining one specific endpoint, whichever slot it is in.
2939    ///
2940    /// This is how a swap drains its incumbent after cutover: the incumbent's
2941    /// endpoint is captured by `cutover_candidate`, and resolving it by module id
2942    /// instead would find the promoted candidate and leave neither process
2943    /// routable. Returns `Ok(None)` when the endpoint is no longer registered.
2944    pub(crate) fn begin_endpoint_drain(
2945        &self,
2946        endpoint: ModuleEndpointId,
2947        reason: RouteCloseReason,
2948    ) -> Result<Option<ModuleDrainTarget>, ForwardingError> {
2949        let mut inner = self.write_inner()?;
2950        let Some(module) = module_connection_for_endpoint_locked(&inner, endpoint).cloned() else {
2951            return Ok(None);
2952        };
2953        let module_id = inner
2954            .module_id_by_endpoint
2955            .get(&endpoint)
2956            .cloned()
2957            .expect("an endpoint resolved to a module connection has a module id");
2958        Ok(Some(begin_drain_locked(
2959            &mut inner, &module_id, module, reason,
2960        )))
2961    }
2962}
2963
2964/// Mark `module`'s endpoint draining and settle everything still pending on it.
2965/// Shared by the by-id and by-endpoint drain entry points, which differ only in
2966/// how they find the endpoint.
2967fn begin_drain_locked(
2968    inner: &mut ForwardingInner,
2969    module_id: &str,
2970    module: ModuleConnection,
2971    reason: RouteCloseReason,
2972) -> ModuleDrainTarget {
2973    {
2974        let endpoint = module.endpoint;
2975        inner.draining_endpoints.insert(endpoint, reason);
2976
2977        let flows = inner
2978            .client_to_module
2979            .values()
2980            .filter(|route| route.module_endpoint == endpoint)
2981            .map(|route| Arc::clone(&route.flow))
2982            .collect::<Vec<_>>();
2983        let excluded_subscriptions = flows
2984            .into_iter()
2985            .map(|flow| flow.begin_drain())
2986            .fold(0u32, u32::saturating_add);
2987
2988        let pending_keys = inner
2989            .pending_relays
2990            .keys()
2991            .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
2992            .copied()
2993            .collect::<Vec<_>>();
2994        let mut abandoned_bindings = Vec::new();
2995        for key in pending_keys {
2996            let Some(pending) = inner.pending_relays.remove(&key) else {
2997                continue;
2998            };
2999            release_reserved_route_locked(
3000                inner,
3001                pending.reservation.client_key,
3002                pending.reservation.module_key,
3003            );
3004            if pending.relay_enqueued {
3005                if let Some(target) = abandoned_route_target(inner, &pending.reservation) {
3006                    abandoned_bindings.push(target);
3007                }
3008            } else {
3009                // The bind may still be on its way into the module's queue;
3010                // a GOODBYE sent now could overtake it. `route.open` sends
3011                // it once its send completes.
3012                inner.relays_released_before_enqueue.insert(key);
3013            }
3014            let _ = pending
3015                .sender
3016                .send(RouteBindRelayOutcome::DaemonRejected(ErrorBody::new(
3017                    "module_reloading",
3018                    format!("module_id '{module_id}' is reloading"),
3019                )));
3020        }
3021
3022        let pending_control_keys = inner
3023            .pending_control_rpcs
3024            .keys()
3025            .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
3026            .copied()
3027            .collect::<Vec<_>>();
3028        for key in pending_control_keys {
3029            if let Some(pending) = inner.pending_control_rpcs.remove(&key) {
3030                let _ = pending
3031                    .sender
3032                    .send(ModuleControlRpcOutcome::ModuleGone(format!(
3033                        "module '{module_id}' began draining during module-control RPC"
3034                    )));
3035            }
3036        }
3037
3038        ModuleDrainTarget {
3039            endpoint,
3040            sink: module.sink,
3041            negotiated_ver: module.negotiated_ver,
3042            abandoned_bindings,
3043            excluded_subscriptions,
3044        }
3045    }
3046}
3047
3048/// What a drain that timed out was still waiting on, for the log line that
3049/// reports the timeout. Per-request ages are not tracked.
3050#[derive(Debug, Default, PartialEq, Eq)]
3051pub(crate) struct DrainHoldouts {
3052    /// Requests still counted against the drain (subscriptions flagged as
3053    /// such are excluded from the drain and not counted here).
3054    pub(crate) requests: usize,
3055    /// Routes holding at least one of those requests.
3056    pub(crate) routes: usize,
3057    /// Every route on the endpoint, for scale.
3058    pub(crate) total_routes: usize,
3059    /// The client connections holding the most requests, largest first, at
3060    /// most three: enough to name the consumer without listing every route.
3061    pub(crate) top_connections: Vec<(u64, usize)>,
3062    /// The held requests themselves, as the module saw them, so its own log
3063    /// can say what each one was: `(module channel, corr)`, ordered by channel
3064    /// then corr, at most [`DRAIN_HELD_REQUESTS_LISTED`]. The daemon never reads
3065    /// request bodies, so it cannot name a request's method; the module can,
3066    /// from the channel and corr. A request is released only when the module
3067    /// sends a terminal frame (Response, Error or StreamEnd) with its corr on
3068    /// its route, so every pair listed here is one the module ended, if at all,
3069    /// without sending that frame.
3070    pub(crate) held: Vec<(u16, u64)>,
3071}
3072
3073/// How many held requests the drain-timeout line lists by channel and corr.
3074pub(crate) const DRAIN_HELD_REQUESTS_LISTED: usize = 32;
3075
3076impl ForwardingTable {
3077    /// Summarise the requests one endpoint's drain is still waiting on.
3078    pub(crate) fn endpoint_drain_holdouts(
3079        &self,
3080        endpoint: ModuleEndpointId,
3081    ) -> Result<DrainHoldouts, ForwardingError> {
3082        let inner = self.read_inner()?;
3083        let mut holdouts = DrainHoldouts::default();
3084        let mut by_connection: HashMap<u64, usize> = HashMap::new();
3085        for (key, route) in &inner.client_to_module {
3086            if route.module_endpoint != endpoint {
3087                continue;
3088            }
3089            holdouts.total_routes += 1;
3090            let held = route.flow.drain_in_flight();
3091            if held == 0 {
3092                continue;
3093            }
3094            holdouts.requests += held;
3095            holdouts.routes += 1;
3096            *by_connection.entry(key.connection_id.get()).or_default() += held;
3097            holdouts.held.extend(
3098                route
3099                    .flow
3100                    .drain_held_corrs()
3101                    .into_iter()
3102                    .map(|corr| (route.module_channel, corr)),
3103            );
3104        }
3105        holdouts.held.sort_unstable();
3106        holdouts.held.truncate(DRAIN_HELD_REQUESTS_LISTED);
3107        let mut connections = by_connection.into_iter().collect::<Vec<_>>();
3108        connections.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(&right.0)));
3109        connections.truncate(3);
3110        holdouts.top_connections = connections;
3111        Ok(holdouts)
3112    }
3113
3114    pub(crate) fn endpoint_in_flight_count(
3115        &self,
3116        endpoint: ModuleEndpointId,
3117    ) -> Result<usize, ForwardingError> {
3118        let inner = self.read_inner()?;
3119        Ok(inner
3120            .client_to_module
3121            .values()
3122            .filter(|route| route.module_endpoint == endpoint)
3123            .map(|route| route.flow.drain_in_flight())
3124            .sum())
3125    }
3126
3127    pub(crate) fn endpoint_is_draining(
3128        &self,
3129        endpoint: ModuleEndpointId,
3130    ) -> Result<bool, ForwardingError> {
3131        Ok(self
3132            .read_inner()?
3133            .draining_endpoints
3134            .contains_key(&endpoint))
3135    }
3136
3137    pub(crate) fn module_is_draining(&self, module_id: &str) -> Result<bool, ForwardingError> {
3138        let inner = self.read_inner()?;
3139        Ok(inner
3140            .modules_by_id
3141            .get(module_id)
3142            .is_some_and(|module| inner.draining_endpoints.contains_key(&module.endpoint)))
3143    }
3144
3145    pub(crate) fn release_module_endpoint_routes(
3146        &self,
3147        endpoint: ModuleEndpointId,
3148    ) -> Result<Vec<GoodbyeTarget>, ForwardingError> {
3149        let mut inner = self.write_inner()?;
3150        let routes = inner
3151            .module_to_client
3152            .iter()
3153            .filter(|(module_key, _)| module_key.endpoint == endpoint)
3154            .map(|(module_key, route)| (*module_key, route.module_epoch))
3155            .collect::<Vec<_>>();
3156        let mut released = Vec::with_capacity(routes.len());
3157        for (module_key, epoch) in routes {
3158            if let RouteRelease::Removed(target) =
3159                release_module_route_locked(&mut inner, module_key, epoch)
3160            {
3161                released.push(target);
3162            }
3163        }
3164        Ok(released)
3165    }
3166
3167    /// Revoke old bind decisions atomically, including binds still in flight.
3168    /// The provider stays available: its acknowledged config governs new binds.
3169    pub(crate) fn rebind_module_policy(
3170        &self,
3171        module_id: &str,
3172        expected_connection: Option<ConnectionId>,
3173        authorized: impl FnOnce() -> bool,
3174    ) -> Result<Option<PolicyRevocation>, ForwardingError> {
3175        #[cfg(test)]
3176        if let Some(hold) = self.policy_rebind_before_write.lock().unwrap().take() {
3177            hold.wait();
3178            hold.wait();
3179        }
3180        let mut inner = self.write_inner()?;
3181        let module = inner
3182            .modules_by_id
3183            .get(module_id)
3184            .cloned()
3185            .ok_or(ForwardingError::NoModuleConnection)?;
3186        if expected_connection.is_some_and(|connection| module.endpoint.connection_id != connection)
3187            || !authorized()
3188        {
3189            return Ok(None);
3190        }
3191        let endpoint = module.endpoint;
3192        if inner.draining_endpoints.contains_key(&endpoint) {
3193            return Err(ForwardingError::ModuleReloading {
3194                module_id: module_id.to_owned(),
3195            });
3196        }
3197        let target = begin_drain_locked(&mut inner, module_id, module, RouteCloseReason::Reload);
3198        let routes = endpoint_routes_locked(&inner, endpoint);
3199        let mut goodbyes = target.abandoned_bindings;
3200        for route in &routes {
3201            let target = &route.goodbye_target;
3202            if let RouteRelease::Removed(module) = release_client_route_locked(
3203                &mut inner,
3204                ClientRouteKey {
3205                    connection_id: target.connection_id,
3206                    channel: target.channel,
3207                },
3208                target.epoch,
3209            ) {
3210                goodbyes.push(module);
3211                goodbyes.push(target.clone());
3212            }
3213        }
3214        inner.draining_endpoints.remove(&endpoint);
3215        Ok(Some((routes, goodbyes)))
3216    }
3217
3218    #[cfg(test)]
3219    pub(crate) fn pause_policy_rebind_before_write(&self, hold: Arc<std::sync::Barrier>) {
3220        *self.policy_rebind_before_write.lock().unwrap() = Some(hold);
3221    }
3222
3223    #[cfg(test)]
3224    pub(crate) fn with_forwarding_write_lock_for_test(&self, work: impl FnOnce()) {
3225        let _guard = self.write_inner().unwrap();
3226        work();
3227    }
3228
3229    /// Enumerate one endpoint's current routes without contacting the module.
3230    ///
3231    /// The read lock makes this safe while the endpoint drains: the returned
3232    /// `draining` marker describes the same table state that owns the route,
3233    /// rather than inferring liveness from a module that may be stopping.
3234    pub(crate) fn endpoint_routes(
3235        &self,
3236        endpoint: ModuleEndpointId,
3237    ) -> Result<Vec<EndpointRoute>, ForwardingError> {
3238        let inner = self.read_inner()?;
3239        Ok(endpoint_routes_locked(&inner, endpoint))
3240    }
3241
3242    /// Snapshot all live endpoint route sets under one forwarding-table read lock.
3243    pub(crate) fn route_census(
3244        &self,
3245        module_id: Option<&str>,
3246    ) -> Result<Vec<(String, Vec<EndpointRoute>)>, ForwardingError> {
3247        let inner = self.read_inner()?;
3248        let mut endpoints = inner
3249            .modules_by_id
3250            .iter()
3251            .filter(|(id, _)| module_id.is_none_or(|requested| requested == id.as_str()))
3252            .map(|(id, module)| (id.clone(), module.endpoint))
3253            .collect::<Vec<_>>();
3254        endpoints.sort_by(|left, right| left.0.cmp(&right.0));
3255        Ok(endpoints
3256            .into_iter()
3257            .map(|(id, endpoint)| (id, endpoint_routes_locked(&inner, endpoint)))
3258            .collect())
3259    }
3260
3261    /// Snapshot only the endpoint currently routable under this module id.
3262    pub(crate) fn live_roots(
3263        &self,
3264        module_id: &str,
3265    ) -> Result<ModuleControlResponseToModule, ForwardingError> {
3266        let inner = self.read_inner()?;
3267        let endpoint = inner
3268            .modules_by_id
3269            .get(module_id)
3270            .map(|module| module.endpoint);
3271        let mut roots = BTreeMap::new();
3272        let mut unknown_root_bindings = 0;
3273        let mut total_bindings = 0;
3274        if let Some(endpoint) = endpoint {
3275            for binding in inner
3276                .module_to_client
3277                .values()
3278                .filter(|binding| binding.module_endpoint == endpoint)
3279            {
3280                total_bindings += 1;
3281                let workdir = binding
3282                    .scope
3283                    .as_ref()
3284                    .and_then(|scope| scope.workdir.as_deref())
3285                    .map(std::path::Path::new);
3286                if let Some(root) = &binding.project_root {
3287                    let entry = roots.entry(root.as_path().to_path_buf()).or_insert((0, 0));
3288                    entry.0 += 1;
3289                } else if workdir.is_none() {
3290                    unknown_root_bindings += 1;
3291                }
3292                if let Some(workdir) = workdir.filter(|workdir| {
3293                    binding.project_root.as_ref().map(ProjectRootId::as_path) != Some(*workdir)
3294                }) {
3295                    roots.entry(workdir.to_path_buf()).or_insert((0, 0)).0 += 1;
3296                }
3297            }
3298            for pending in inner
3299                .pending_relays
3300                .values()
3301                .filter(|pending| pending.reservation.module_key.endpoint == endpoint)
3302            {
3303                total_bindings += 1;
3304                if let Some(root) = &pending.reservation.project_root {
3305                    let entry = roots.entry(root.as_path().to_path_buf()).or_insert((0, 0));
3306                    entry.1 += 1;
3307                } else {
3308                    unknown_root_bindings += 1;
3309                }
3310            }
3311        }
3312        Ok(ModuleControlResponseToModule::LiveRoots {
3313            roots: roots
3314                .into_iter()
3315                .map(|(project_root, (bound, pending))| LiveRoot {
3316                    project_root,
3317                    bound,
3318                    pending,
3319                })
3320                .collect(),
3321            unknown_root_bindings,
3322            total_bindings,
3323        })
3324    }
3325
3326    /// True if this connection already owns committed or reserved CLIENT routes.
3327    /// A module registers (HELLO) before serving and never opens client routes, so
3328    /// a connection that has client routes must not also become a module endpoint
3329    /// — otherwise one connection holds both client and module state and cleanup
3330    /// only releases one side.
3331    pub(crate) fn connection_has_client_routes(
3332        &self,
3333        connection_id: ConnectionId,
3334    ) -> Result<bool, ForwardingError> {
3335        let inner = self.read_inner()?;
3336        Ok(connection_has_client_routes_locked(&inner, connection_id))
3337    }
3338
3339    pub(crate) fn cleanup_connection(
3340        &self,
3341        connection_id: ConnectionId,
3342    ) -> Result<Vec<GoodbyeTarget>, ForwardingError> {
3343        self.cleanup_connection_counted(connection_id)
3344            .map(|cleanup| cleanup.released)
3345    }
3346
3347    /// [`Self::cleanup_connection`], also reporting how many pending
3348    /// route.bind relays to the closed module were aborted. That count is the
3349    /// `abandoned` figure of the `route.closed` push sent for a lost module
3350    /// connection; it is always zero for a client connection.
3351    pub(crate) fn cleanup_connection_counted(
3352        &self,
3353        connection_id: ConnectionId,
3354    ) -> Result<ConnectionCleanup, ForwardingError> {
3355        self.frame_drop_warnings
3356            .lock()
3357            .unwrap_or_else(std::sync::PoisonError::into_inner)
3358            .remove(&connection_id);
3359        let mut inner = self.write_inner()?;
3360        inner.closing_connections.insert(connection_id);
3361        #[cfg(all(test, target_os = "linux"))]
3362        if let Some(pause) = self.cleanup_pause.lock().unwrap().take() {
3363            let _ = pause.reached.send(());
3364            pause
3365                .release
3366                .recv_timeout(Duration::from_secs(5))
3367                .expect("test must release connection cleanup");
3368        }
3369        #[cfg(all(test, target_os = "linux"))]
3370        if let Some(observe) = self.cleanup_tie_observer.lock().unwrap().take() {
3371            let pending = inner
3372                .pending_relays
3373                .values()
3374                .filter(|relay| relay.reservation.client_key.connection_id == connection_id)
3375                .count();
3376            let _ = observe.send((
3377                inner.spawn_connections.contains_key(&connection_id),
3378                pending,
3379            ));
3380        }
3381        let cleanup = if let Some(endpoint) = inner.endpoint_by_connection.remove(&connection_id) {
3382            remove_module_connection_locked(&mut inner, endpoint)
3383        } else {
3384            ConnectionCleanup {
3385                released: Self::cleanup_client_connection_locked(&mut inner, connection_id),
3386                abandoned_relays: 0,
3387            }
3388        };
3389        // The closing mark refuses new work for a connection whose teardown is
3390        // still pending. This is the latest point at which lifting it is safe:
3391        // teardown has just removed every per-connection entry above, under
3392        // this same write lock, so no lookup can still find live state for the
3393        // id; and ids come from a monotonic counter that never reissues one,
3394        // so the id can never name a future connection either. Keeping the
3395        // mark past this point only grew the set by one entry per connection
3396        // for the life of the daemon.
3397        inner.closing_connections.remove(&connection_id);
3398        Ok(cleanup)
3399    }
3400
3401    fn cleanup_client_connection_locked(
3402        inner: &mut ForwardingInner,
3403        connection_id: ConnectionId,
3404    ) -> Vec<GoodbyeTarget> {
3405        let routes = inner
3406            .client_to_module
3407            .iter()
3408            .filter(|(key, _)| key.connection_id == connection_id)
3409            .map(|(key, route)| (*key, route.client_epoch))
3410            .collect::<Vec<_>>();
3411        let mut released = Vec::with_capacity(routes.len());
3412        for (client_key, epoch) in routes {
3413            if let RouteRelease::Removed(target) =
3414                release_client_route_locked(inner, client_key, epoch)
3415            {
3416                released.push(target);
3417            }
3418        }
3419
3420        let pending_keys = inner
3421            .pending_relays
3422            .iter()
3423            .filter(|(_, pending)| pending.reservation.client_key.connection_id == connection_id)
3424            .map(|(key, _)| *key)
3425            .collect::<Vec<_>>();
3426        for key in pending_keys {
3427            let Some(pending) = inner.pending_relays.remove(&key) else {
3428                continue;
3429            };
3430            release_reserved_route_locked(
3431                inner,
3432                pending.reservation.client_key,
3433                pending.reservation.module_key,
3434            );
3435            if pending.relay_enqueued {
3436                if let Some(target) = abandoned_route_target(inner, &pending.reservation) {
3437                    released.push(target);
3438                }
3439            } else {
3440                // The bind may still be on its way into the module's queue;
3441                // a GOODBYE sent now could overtake it. `route.open` sends
3442                // it once its send completes.
3443                inner.relays_released_before_enqueue.insert(key);
3444            }
3445            let _ = pending.sender.send(RouteBindRelayOutcome::ModuleGone(
3446                "client connection closed during route.bind relay".to_string(),
3447            ));
3448        }
3449
3450        let orphaned = inner
3451            .reserved_client
3452            .iter()
3453            .filter(|(key, _)| key.connection_id == connection_id)
3454            .map(|(client, module)| (*client, *module))
3455            .collect::<Vec<_>>();
3456        for (client_key, module_key) in orphaned {
3457            release_reserved_route_locked(inner, client_key, module_key);
3458        }
3459        inner.next_client_channel.remove(&connection_id);
3460        inner
3461            .client_slot_epochs
3462            .retain(|key, _| key.connection_id != connection_id);
3463        inner
3464            .last_published_epoch
3465            .retain(|key, _| key.connection_id != connection_id);
3466        inner
3467            .status
3468            .retain(|(key, _), _| key.connection_id != connection_id);
3469
3470        released
3471    }
3472
3473    /// Close a client connection whose egress queue refused a frame for the
3474    /// route `(connection_id, channel)` at `expected_epoch`. The whole
3475    /// connection closes because its queue is shared by every route on it.
3476    ///
3477    /// The first request that actually closes the connection logs one WARN with
3478    /// the diagnosis: which principals the connection's routes belonged to,
3479    /// which module's frame did not fit and on which client channel, and what
3480    /// the queue held at that moment.
3481    pub(crate) fn escalate_client_delivery_failure(
3482        &self,
3483        connection_id: ConnectionId,
3484        channel: u16,
3485        expected_epoch: u32,
3486        reason: CloseReason,
3487        undelivered: UndeliveredFrame<'_>,
3488    ) -> Result<bool, ForwardingError> {
3489        self.escalate_client_delivery_failure_diagnosed(
3490            connection_id,
3491            channel,
3492            expected_epoch,
3493            reason,
3494            undelivered,
3495            None,
3496        )
3497    }
3498
3499    pub(crate) fn escalate_client_delivery_failure_diagnosed(
3500        &self,
3501        connection_id: ConnectionId,
3502        channel: u16,
3503        expected_epoch: u32,
3504        reason: CloseReason,
3505        undelivered: UndeliveredFrame<'_>,
3506        diagnosis: Option<&crate::router::ClientDeliveryDiagnosis>,
3507    ) -> Result<bool, ForwardingError> {
3508        let principals = {
3509            let mut inner = self.write_inner()?;
3510            let key = ClientRouteKey {
3511                connection_id,
3512                channel,
3513            };
3514            if inner.last_published_epoch.get(&key).copied() != Some(expected_epoch) {
3515                None
3516            } else {
3517                inner.closing_connections.insert(connection_id);
3518                Some(connection_principals_locked(&inner, connection_id))
3519            }
3520        };
3521        let Some(principals) = principals else {
3522            // A concurrent release can remove the epoch before escalation.
3523            // The frame was still lost, even though this route can no longer
3524            // authorize closing the shared client connection.
3525            self.warn_frame_drop(
3526                connection_id,
3527                channel,
3528                expected_epoch,
3529                "module_to_client",
3530                diagnosis
3531                    .map(|failure| failure.cause)
3532                    .unwrap_or("delivery_failed"),
3533            );
3534            return Ok(false);
3535        };
3536        let backlog = undelivered.sink.backlog();
3537        let close_reason = reason.to_string();
3538        if self.request_connection_close(connection_id, reason) {
3539            warn!(
3540                connection_id = connection_id.get(),
3541                principals = %principals,
3542                module_id = undelivered.module_id.unwrap_or("unknown"),
3543                client_channel = channel,
3544                queued_bytes = backlog.queued_bytes,
3545                queued_frames = backlog.queued_frames,
3546                frame_type = ?diagnosis.map(|failure| failure.frame_type),
3547                frame_flags = ?diagnosis.map(|failure| failure.flags.0),
3548                close_cause = diagnosis.map(|failure| failure.cause).unwrap_or("delivery_failed"),
3549                oldest_queued_ms = backlog
3550                    .oldest_age
3551                    .map(|age| age.as_millis() as u64)
3552                    .unwrap_or(0),
3553                close_reason = %close_reason,
3554                "closing client connection: its egress queue could not take a frame"
3555            );
3556        }
3557        Ok(true)
3558    }
3559
3560    /// Publish the tags a scope sync changed and close the live routes its
3561    /// drain table selects, in one critical section.
3562    ///
3563    /// The caller holds the scope table's write lock (scope table, then this
3564    /// table, always). Publishing and selecting under one lock is what closes
3565    /// the race with a bind commit: a commit before this sees the old tag and
3566    /// its route is selected here like any other; a commit after it sees the
3567    /// new tag and is refused.
3568    ///
3569    /// Every client route index entry is scanned, which includes routes on a
3570    /// swap's superseded endpoint (the old process of a module being replaced
3571    /// blue/green, which keeps its existing routes until they drain): those
3572    /// stay indexed until drained, so ending a scope reaches them too.
3573    pub(crate) fn publish_scope_changes(
3574        &self,
3575        changes: &[ScopeTagChange],
3576    ) -> Result<Vec<ScopeDrainedRoute>, ForwardingError> {
3577        let mut inner = self.write_inner()?;
3578        let mut by_scope: HashMap<(&str, &str), &ScopeTagChange> = HashMap::new();
3579        for change in changes {
3580            let key = (change.owner.clone(), change.scope_ref.clone());
3581            match change.after {
3582                Some(tag) => {
3583                    inner.scope_tags.insert(key, tag);
3584                }
3585                None => {
3586                    inner.scope_tags.remove(&key);
3587                }
3588            }
3589            by_scope.insert((change.owner.as_str(), change.scope_ref.as_str()), change);
3590        }
3591        let mut selected = Vec::new();
3592        for (client_key, route) in &inner.client_to_module {
3593            let Some(scope) = &route.scope else {
3594                continue;
3595            };
3596            let Some(change) = by_scope.get(&(scope.owner.as_str(), scope.scope_ref.as_str()))
3597            else {
3598                continue;
3599            };
3600            if change.before.map(|tag| tag.scope_epoch) != Some(scope.tag.scope_epoch) {
3601                continue;
3602            }
3603            let reason = match &change.drain {
3604                ScopeDrain::Nothing => continue,
3605                ScopeDrain::All(reason) => *reason,
3606                ScopeDrain::Carriers(narrowed) => {
3607                    let owner = Principal::Reserved {
3608                        module_id: scope.owner.clone(),
3609                    };
3610                    let hit = route.principal != owner
3611                        && narrowed.iter().any(|(principal, allowed)| {
3612                            *principal == route.principal
3613                                && allowed
3614                                    .as_ref()
3615                                    .is_none_or(|targets| !targets.contains(&route.module_id))
3616                        });
3617                    if !hit {
3618                        continue;
3619                    }
3620                    RouteCloseReason::ScopeCarrierRemoved
3621                }
3622            };
3623            selected.push((*client_key, route.client_epoch, reason));
3624        }
3625        let mut drained = Vec::new();
3626        for (client_key, client_epoch, reason) in selected {
3627            let Some(route) = inner.client_to_module.get(&client_key).cloned() else {
3628                continue;
3629            };
3630            let release = release_client_route_locked(&mut inner, client_key, client_epoch);
3631            self.record_route_release(&release);
3632            if let RouteRelease::Removed(module) = release {
3633                drained.push(ScopeDrainedRoute {
3634                    reason,
3635                    scope: route
3636                        .scope
3637                        .clone()
3638                        .expect("selected scope drain has a bound scope"),
3639                    module_id: route.module_id.clone(),
3640                    client: GoodbyeTarget {
3641                        connection_id: route.client_connection_id,
3642                        sink: route.client_sink.clone(),
3643                        negotiated_ver: route.client_negotiated_ver,
3644                        channel: route.client_channel,
3645                        epoch: route.client_epoch,
3646                        kind: GoodbyeTargetKind::Client,
3647                        module_id: Some(route.module_id.clone()),
3648                    },
3649                    module,
3650                    accepts_close_reasons: route.accepts_close_reasons.clone(),
3651                });
3652            }
3653        }
3654        Ok(drained)
3655    }
3656
3657    /// Publish a spawn's new authority epoch and release every live route
3658    /// whose recorded caller or target is that spawn at an older epoch, in one
3659    /// critical section.
3660    ///
3661    /// The caller holds the spawn's authority record state (record, then this
3662    /// table, always; see `SpawnAuthorityRecord::change_authority`). A bind
3663    /// that commits before this is selected here like any other route; one
3664    /// that commits after it sees the new epoch and is refused as stale.
3665    ///
3666    /// Unlike [`Self::publish_scope_changes`], every client route is scanned,
3667    /// scoped or not. Once a spawn is dead (`alive` false), its own mark and
3668    /// approved set are dropped and its epoch stays as a tombstone, so a bind
3669    /// still naming it is refused as stale. Another spawn of the same module
3670    /// is never touched: a blue/green swap candidate takes a higher spawn
3671    /// number than the incumbent that keeps serving beside it, so spawn order
3672    /// says nothing about which of them is still alive. `first_party` is the
3673    /// spawn's mark after the change; a lowering withdraws it here, in the
3674    /// same critical section as the epoch.
3675    pub(crate) fn publish_authority_change(
3676        &self,
3677        key: &SpawnKey,
3678        epoch: u64,
3679        alive: bool,
3680        first_party: bool,
3681    ) -> Result<Vec<AuthorityClosedRoute>, ForwardingError> {
3682        self.publish_approved_authority_change(key, epoch, alive, Some(first_party), None)
3683    }
3684
3685    /// Publish changed mark or approval facts with the new epoch. `None`
3686    /// leaves that fact unchanged; a dead spawn always loses its mark.
3687    pub(crate) fn publish_approved_authority_change(
3688        &self,
3689        key: &SpawnKey,
3690        epoch: u64,
3691        alive: bool,
3692        first_party: Option<bool>,
3693        approved: Option<&ApprovedDeclarations>,
3694    ) -> Result<Vec<AuthorityClosedRoute>, ForwardingError> {
3695        let mut inner = self.write_inner()?;
3696        if !alive {
3697            inner.spawn_approved.remove(key);
3698            inner.dead_spawns.insert(key.clone());
3699            prune_dead_spawn_tombstones_locked(&mut inner, key);
3700        } else if let Some(approved) = approved {
3701            inner.spawn_approved.insert(key.clone(), approved.clone());
3702        }
3703        // A record's epoch only rises; taking the larger keeps a published
3704        // epoch from ever moving backwards, whatever order publications land.
3705        let published = inner.spawn_epochs.entry(key.clone()).or_insert(epoch);
3706        *published = (*published).max(epoch);
3707        if !alive || first_party == Some(false) {
3708            inner.spawn_marks.remove(key);
3709        } else if first_party == Some(true) {
3710            inner.spawn_marks.insert(key.clone());
3711        }
3712        let older = |pair: &Option<AuthorityPair>| {
3713            pair.as_ref()
3714                .is_some_and(|pair| pair.key == *key && pair.epoch < epoch)
3715        };
3716        let selected = inner
3717            .client_to_module
3718            .iter()
3719            .filter(|(_, route)| older(&route.caller_authority) || older(&route.target_authority))
3720            .map(|(client_key, route)| (*client_key, route.client_epoch))
3721            .collect::<Vec<_>>();
3722        let mut closed = Vec::new();
3723        for (client_key, client_epoch) in selected {
3724            let Some(route) = inner.client_to_module.get(&client_key).cloned() else {
3725                continue;
3726            };
3727            let release = release_client_route_locked(&mut inner, client_key, client_epoch);
3728            self.record_route_release(&release);
3729            if let RouteRelease::Removed(module) = release {
3730                closed.push(AuthorityClosedRoute {
3731                    client: GoodbyeTarget {
3732                        connection_id: route.client_connection_id,
3733                        sink: route.client_sink.clone(),
3734                        negotiated_ver: route.client_negotiated_ver,
3735                        channel: route.client_channel,
3736                        epoch: route.client_epoch,
3737                        kind: GoodbyeTargetKind::Client,
3738                        module_id: Some(route.module_id.clone()),
3739                    },
3740                    module,
3741                    route,
3742                });
3743            }
3744        }
3745        Ok(closed)
3746    }
3747
3748    /// Publish a spawn's activated first-party mark, so `route.open` replies
3749    /// reserved from now on report it. The caller holds the spawn's authority
3750    /// record state. The epoch is unchanged and no route is closed: routes
3751    /// bound before activation keep the `first_party: false` they were
3752    /// attested with.
3753    pub(crate) fn publish_spawn_mark(&self, key: &SpawnKey) -> Result<(), ForwardingError> {
3754        self.write_inner()?.spawn_marks.insert(key.clone());
3755        Ok(())
3756    }
3757
3758    /// The epoch published for a spawn, for tests of the commit re-check.
3759    #[cfg(all(test, unix, feature = "test-support"))]
3760    pub(crate) fn published_spawn_epoch(&self, key: &SpawnKey) -> u64 {
3761        published_epoch_locked(&self.read_inner().unwrap(), key)
3762    }
3763
3764    /// The caller and target authority each live route opened by `client`
3765    /// recorded at commit.
3766    #[cfg(all(test, unix, feature = "test-support"))]
3767    pub(crate) fn route_authority_for_test(
3768        &self,
3769        client: ConnectionId,
3770    ) -> Vec<(Option<AuthorityPair>, Option<AuthorityPair>)> {
3771        self.read_inner()
3772            .unwrap()
3773            .client_to_module
3774            .iter()
3775            .filter(|(key, _)| key.connection_id == client)
3776            .map(|(_, route)| {
3777                (
3778                    route.caller_authority.clone(),
3779                    route.target_authority.clone(),
3780                )
3781            })
3782            .collect()
3783    }
3784
3785    /// The published tag of one scope, for tests of the commit re-check.
3786    #[cfg(test)]
3787    pub(crate) fn published_scope_tag(&self, owner: &str, scope_ref: &str) -> Option<ScopeTag> {
3788        self.read_inner()
3789            .ok()?
3790            .scope_tags
3791            .get(&(owner.to_string(), scope_ref.to_string()))
3792            .copied()
3793    }
3794
3795    fn record_route_release(&self, release: &RouteRelease) {
3796        match release {
3797            RouteRelease::Removed(_) => self.counters.increment_route_released_epoch_fenced(),
3798            RouteRelease::Stale => self.counters.increment_route_release_stale_skipped(),
3799            RouteRelease::Absent => {}
3800        }
3801    }
3802
3803    fn read_inner(
3804        &self,
3805    ) -> Result<InnerGuard<RwLockReadGuard<'_, ForwardingInner>>, ForwardingError> {
3806        self.inner
3807            .read()
3808            .map(InnerGuard::new)
3809            .map_err(|_| ForwardingError::Poisoned)
3810    }
3811
3812    fn write_inner(
3813        &self,
3814    ) -> Result<InnerGuard<RwLockWriteGuard<'_, ForwardingInner>>, ForwardingError> {
3815        self.inner
3816            .write()
3817            .map(InnerGuard::new)
3818            .map_err(|_| ForwardingError::Poisoned)
3819    }
3820
3821    fn lock_close_registry(
3822        &self,
3823    ) -> MutexGuard<'_, HashMap<ConnectionId, oneshot::Sender<CloseReason>>> {
3824        self.close_registry
3825            .lock()
3826            .unwrap_or_else(|poisoned| poisoned.into_inner())
3827    }
3828}
3829
3830impl ForwardingInner {
3831    fn allocate_route_slots(
3832        &mut self,
3833        connection_id: ConnectionId,
3834        endpoint: ModuleEndpointId,
3835    ) -> Result<(u16, u32, u16, u32), ForwardingError> {
3836        let client_start = *self.next_client_channel.entry(connection_id).or_insert(1);
3837        let mut client_channel = client_start;
3838        let client_channel = loop {
3839            let key = ClientRouteKey {
3840                connection_id,
3841                channel: client_channel,
3842            };
3843            let eligible = !self.client_to_module.contains_key(&key)
3844                && !self.reserved_client.contains_key(&key)
3845                && self.client_slot_epochs.get(&key).copied().unwrap_or(0) < u32::MAX;
3846            if eligible {
3847                break client_channel;
3848            }
3849            client_channel = next_channel(client_channel);
3850            if client_channel == client_start {
3851                return Err(ForwardingError::ClientRouteChannelExhausted { connection_id });
3852            }
3853        };
3854
3855        let module_start = *self.next_module_channel.entry(endpoint).or_insert(1);
3856        let mut module_channel = module_start;
3857        let module_channel = loop {
3858            let key = ModuleRouteKey {
3859                endpoint,
3860                channel: module_channel,
3861            };
3862            let eligible = !self.module_to_client.contains_key(&key)
3863                && !self.reserved_module.contains_key(&key)
3864                && self.module_slot_epochs.get(&key).copied().unwrap_or(0) < u32::MAX;
3865            if eligible {
3866                break module_channel;
3867            }
3868            module_channel = next_channel(module_channel);
3869            if module_channel == module_start {
3870                return Err(ForwardingError::ModuleRouteChannelExhausted { endpoint });
3871            }
3872        };
3873
3874        let client_key = ClientRouteKey {
3875            connection_id,
3876            channel: client_channel,
3877        };
3878        let module_key = ModuleRouteKey {
3879            endpoint,
3880            channel: module_channel,
3881        };
3882        let client_epoch = self
3883            .client_slot_epochs
3884            .get(&client_key)
3885            .copied()
3886            .unwrap_or(0)
3887            + 1;
3888        let module_epoch = self
3889            .module_slot_epochs
3890            .get(&module_key)
3891            .copied()
3892            .unwrap_or(0)
3893            + 1;
3894        self.client_slot_epochs.insert(client_key, client_epoch);
3895        self.module_slot_epochs.insert(module_key, module_epoch);
3896        self.next_client_channel
3897            .insert(connection_id, next_channel(client_channel));
3898        self.next_module_channel
3899            .insert(endpoint, next_channel(module_channel));
3900        Ok((client_channel, client_epoch, module_channel, module_epoch))
3901    }
3902
3903    fn allocate_control_corr(
3904        &mut self,
3905        endpoint: ModuleEndpointId,
3906    ) -> Result<u64, ForwardingError> {
3907        let candidate = self.next_control_corr.get(&endpoint).copied().unwrap_or(1);
3908        if candidate == 0 {
3909            self.closing_connections.insert(endpoint.connection_id);
3910            return Err(ForwardingError::RelayCorrelationExhausted);
3911        }
3912        self.next_control_corr.insert(
3913            endpoint,
3914            if candidate == u64::MAX {
3915                0
3916            } else {
3917                candidate + 1
3918            },
3919        );
3920        Ok(candidate)
3921    }
3922}
3923
3924fn connection_has_client_routes_locked(
3925    inner: &ForwardingInner,
3926    connection_id: ConnectionId,
3927) -> bool {
3928    inner
3929        .client_to_module
3930        .keys()
3931        .any(|key| key.connection_id == connection_id)
3932        || inner
3933            .reserved_client
3934            .keys()
3935            .any(|key| key.connection_id == connection_id)
3936}
3937
3938fn check_module_connection_role_locked(
3939    inner: &ForwardingInner,
3940    connection_id: ConnectionId,
3941) -> Result<(), ForwardingError> {
3942    if inner.endpoint_by_connection.contains_key(&connection_id)
3943        || connection_has_client_routes_locked(inner, connection_id)
3944    {
3945        return Err(ForwardingError::ConnectionRoleConflict { connection_id });
3946    }
3947    Ok(())
3948}
3949
3950fn next_channel(channel: u16) -> u16 {
3951    let next = channel.wrapping_add(1);
3952    if next == 0 {
3953        1
3954    } else {
3955        next
3956    }
3957}
3958
3959fn endpoint_routes_locked(
3960    inner: &ForwardingInner,
3961    endpoint: ModuleEndpointId,
3962) -> Vec<EndpointRoute> {
3963    let drain_reason = inner.draining_endpoints.get(&endpoint).copied();
3964    let draining = drain_reason.is_some();
3965    let mut routes = inner
3966        .module_to_client
3967        .iter()
3968        .filter(|(module_key, _)| module_key.endpoint == endpoint)
3969        .map(|(_, route)| EndpointRoute {
3970            goodbye_target: GoodbyeTarget {
3971                connection_id: route.client_connection_id,
3972                sink: route.client_sink.clone(),
3973                negotiated_ver: route.client_negotiated_ver,
3974                channel: route.client_channel,
3975                epoch: route.client_epoch,
3976                kind: GoodbyeTargetKind::Client,
3977                module_id: Some(route.module_id.clone()),
3978            },
3979            principal: route.principal.clone(),
3980            accepts_close_reasons: route.accepts_close_reasons.clone(),
3981            bound_at: route.bound_at,
3982            draining,
3983            drain_reason,
3984        })
3985        .collect::<Vec<_>>();
3986    routes.sort_by_key(|route| {
3987        (
3988            route.goodbye_target.connection_id.get(),
3989            route.goodbye_target.channel,
3990            route.goodbye_target.epoch,
3991        )
3992    });
3993    routes
3994}
3995
3996/// Why a bind admitted under `scope` may no longer commit: its absolute
3997/// deadline has passed (whether or not a sweep has published that yet), or,
3998/// read from the published tags, `scope_ended` when the scope is gone or at
3999/// another epoch, `scope_changed` (retryable) when only its content moved.
4000fn scope_refusal_locked(inner: &ForwardingInner, scope: &BoundScope) -> Option<ErrorBody> {
4001    if let Some(expired) = scope.deadline_refusal() {
4002        return Some(expired);
4003    }
4004    let key = (scope.owner.clone(), scope.scope_ref.clone());
4005    match inner.scope_tags.get(&key) {
4006        Some(current) if *current == scope.tag => None,
4007        Some(current) if current.scope_epoch == scope.tag.scope_epoch => Some(ErrorBody::new(
4008            subc_protocol::error_codes::SCOPE_CHANGED,
4009            format!(
4010                "scope '{}' of {} changed while the route was being bound; re-open it",
4011                scope.scope_ref, scope.owner
4012            ),
4013        )),
4014        _ => Some(ErrorBody::new(
4015            subc_protocol::error_codes::SCOPE_ENDED,
4016            format!(
4017                "scope '{}' of {} at scope_epoch {} ended while the route was being bound",
4018                scope.scope_ref, scope.owner, scope.tag.scope_epoch
4019            ),
4020        )),
4021    }
4022}
4023
4024fn release_reserved_route_locked(
4025    inner: &mut ForwardingInner,
4026    client_key: ClientRouteKey,
4027    module_key: ModuleRouteKey,
4028) {
4029    if inner.reserved_client.get(&client_key).copied() == Some(module_key) {
4030        inner.reserved_client.remove(&client_key);
4031    }
4032    if inner.reserved_module.get(&module_key).copied() == Some(client_key) {
4033        inner.reserved_module.remove(&module_key);
4034    }
4035    inner.status.retain(|(key, _), _| *key != client_key);
4036}
4037
4038fn release_client_route_locked(
4039    inner: &mut ForwardingInner,
4040    client_key: ClientRouteKey,
4041    expected_epoch: u32,
4042) -> RouteRelease {
4043    let Some(route) = inner.client_to_module.get(&client_key) else {
4044        return RouteRelease::Absent;
4045    };
4046    if route.client_epoch != expected_epoch {
4047        return RouteRelease::Stale;
4048    }
4049    let route = inner
4050        .client_to_module
4051        .remove(&client_key)
4052        .expect("route checked under the same forwarding lock");
4053    route.flow.close();
4054    if let Some(scope) = &route.scope {
4055        scope.release_bind();
4056    }
4057    inner.module_to_client.remove(&ModuleRouteKey {
4058        endpoint: route.module_endpoint,
4059        channel: route.module_channel,
4060    });
4061    inner.operator_confirms.route_closed(ModuleRouteKey {
4062        endpoint: route.module_endpoint,
4063        channel: route.module_channel,
4064    });
4065    inner.status.remove(&(client_key, expected_epoch));
4066    RouteRelease::Removed(GoodbyeTarget {
4067        connection_id: route.module_endpoint.connection_id,
4068        sink: route.module_sink.clone(),
4069        negotiated_ver: route.module_negotiated_ver,
4070        channel: route.module_channel,
4071        epoch: route.module_epoch,
4072        kind: GoodbyeTargetKind::Module,
4073        module_id: Some(route.module_id.clone()),
4074    })
4075}
4076
4077fn release_module_route_locked(
4078    inner: &mut ForwardingInner,
4079    module_key: ModuleRouteKey,
4080    expected_epoch: u32,
4081) -> RouteRelease {
4082    let Some(route) = inner.module_to_client.get(&module_key) else {
4083        return RouteRelease::Absent;
4084    };
4085    if route.module_epoch != expected_epoch {
4086        return RouteRelease::Stale;
4087    }
4088    let route = inner
4089        .module_to_client
4090        .remove(&module_key)
4091        .expect("route checked under the same forwarding lock");
4092    inner.operator_confirms.route_closed(module_key);
4093    route.flow.close();
4094    if let Some(scope) = &route.scope {
4095        scope.release_bind();
4096    }
4097    let client_key = ClientRouteKey {
4098        connection_id: route.client_connection_id,
4099        channel: route.client_channel,
4100    };
4101    inner.client_to_module.remove(&client_key);
4102    inner.status.remove(&(client_key, route.client_epoch));
4103    RouteRelease::Removed(GoodbyeTarget {
4104        connection_id: route.client_connection_id,
4105        sink: route.client_sink.clone(),
4106        negotiated_ver: route.client_negotiated_ver,
4107        channel: route.client_channel,
4108        epoch: route.client_epoch,
4109        kind: GoodbyeTargetKind::Client,
4110        module_id: Some(route.module_id.clone()),
4111    })
4112}
4113
4114fn commit_route_locked(
4115    inner: &mut ForwardingInner,
4116    mut pending: PendingRouteBindRelayEntry,
4117) -> Result<Option<GoodbyeTarget>, ForwardingError> {
4118    let reservation = pending.reservation;
4119    if inner
4120        .closing_connections
4121        .contains(&reservation.client_key.connection_id)
4122    {
4123        return Err(ForwardingError::ConnectionClosing {
4124            connection_id: reservation.client_key.connection_id,
4125        });
4126    }
4127    let module_id = inner
4128        .module_id_by_endpoint
4129        .get(&reservation.module_key.endpoint)
4130        .cloned()
4131        .ok_or(ForwardingError::StaleModuleEndpoint)?;
4132    if inner
4133        .draining_endpoints
4134        .contains_key(&reservation.module_key.endpoint)
4135    {
4136        return Err(ForwardingError::ModuleReloading { module_id });
4137    }
4138    if pending.busy_refusals {
4139        let body = route_open_reply_body(
4140            &ClientControlResponse::RouteOpen {
4141                route_channel: reservation.client_key.channel,
4142                route_epoch: reservation.client_epoch,
4143                request_window: Some(pending.request_window),
4144                watch_window: pending.watch_window,
4145            },
4146            &pending.target_authority,
4147            &pending.incarnation,
4148        )?;
4149        pending.route_open_frame = Frame::build_with_version(
4150            pending.client_negotiated_ver,
4151            FrameType::Response,
4152            pending.route_open_frame.header.flags,
4153            0,
4154            0,
4155            pending.route_open_frame.header.corr,
4156            body,
4157        )
4158        .map_err(|err| ForwardingError::RouteOpenBuild(err.to_string()))?;
4159    }
4160    if inner.reserved_client.remove(&reservation.client_key) != Some(reservation.module_key)
4161        || inner.reserved_module.remove(&reservation.module_key) != Some(reservation.client_key)
4162    {
4163        return Err(ForwardingError::UnknownReservation {
4164            client_channel: reservation.client_key.channel,
4165            module_channel: reservation.module_key.channel,
4166        });
4167    }
4168    let module = inner
4169        .modules_by_id
4170        .get(&module_id)
4171        .filter(|module| module.endpoint == reservation.module_key.endpoint)
4172        .cloned()
4173        .ok_or(ForwardingError::StaleModuleEndpoint)?;
4174    let binding = Arc::new(RouteBinding {
4175        client_connection_id: reservation.client_key.connection_id,
4176        client_sink: pending.client_sink,
4177        client_negotiated_ver: pending.client_negotiated_ver,
4178        client_channel: reservation.client_key.channel,
4179        client_epoch: reservation.client_epoch,
4180        module_id,
4181        module_endpoint: reservation.module_key.endpoint,
4182        module_sink: module.sink,
4183        module_negotiated_ver: module.negotiated_ver,
4184        module_channel: reservation.module_key.channel,
4185        module_epoch: reservation.module_epoch,
4186        principal: pending.principal,
4187        harness: pending.harness,
4188        build_class: pending.build_class,
4189        operator_app: pending.operator_app,
4190        project_root: reservation.project_root.clone(),
4191        bound_at: Instant::now(),
4192        flow: Arc::new(if pending.busy_refusals {
4193            ChannelFlow::with_admission(pending.request_window, true, pending.watch_window)
4194        } else {
4195            ChannelFlow::new(pending.request_window)
4196        }),
4197        scope: pending.scope,
4198        caller_authority: pending.caller_authority,
4199        target_authority: pending.target_authority.pair().cloned(),
4200        accepts_close_reasons: pending.accepts_close_reasons,
4201    });
4202    inner
4203        .client_to_module
4204        .insert(reservation.client_key, Arc::clone(&binding));
4205    inner
4206        .module_to_client
4207        .insert(reservation.module_key, Arc::clone(&binding));
4208    let previous_published = inner
4209        .last_published_epoch
4210        .insert(reservation.client_key, reservation.client_epoch);
4211
4212    // This point is reachable only through an accepted route.bind acknowledgement.
4213    // Publish history before notifying the opener, so a subsequent
4214    // `scope.served_by` query sees the acknowledged bind.
4215    if let Some(scope) = &binding.scope {
4216        scope.record_served(&binding.module_id, module.verified_prefix_owner.as_deref());
4217    }
4218
4219    // Sending through the reserved slot cannot fail, but it reports a receiver
4220    // that closed after reservation and before this locked publication point.
4221    // The frame is stamped and charged to the queued-byte count here, when it
4222    // actually enters the queue, not when the slot was reserved.
4223    let client_writer_closed = pending.client_permit.send(pending.route_open_frame);
4224    if client_writer_closed {
4225        // Not gated on `relay_enqueued`: only a module ack reaches this
4226        // commit, which proves the module holds the binding, and `route.open`
4227        // sends nothing for a relay a reply already settled.
4228        let abandoned = abandoned_route_target(inner, &reservation);
4229        if let Some(route) = inner.client_to_module.remove(&reservation.client_key) {
4230            route.flow.close();
4231        }
4232        inner.module_to_client.remove(&reservation.module_key);
4233        inner
4234            .status
4235            .remove(&(reservation.client_key, reservation.client_epoch));
4236        match previous_published {
4237            Some(epoch) => {
4238                inner
4239                    .last_published_epoch
4240                    .insert(reservation.client_key, epoch);
4241            }
4242            None => {
4243                inner.last_published_epoch.remove(&reservation.client_key);
4244            }
4245        }
4246        let _ = pending.sender.send(RouteBindRelayOutcome::ModuleGone(
4247            "client egress closed during route publication".to_string(),
4248        ));
4249        return Ok(abandoned);
4250    }
4251
4252    if let Some(scope) = &binding.scope {
4253        scope.commit_presence();
4254    }
4255    let _ = pending.sender.send(RouteBindRelayOutcome::Accepted);
4256    Ok(None)
4257}
4258
4259/// What serves `module`'s endpoint: a prefix child, a supervised spawn's own
4260/// registration at its published epoch, or an unsupervised registration.
4261fn target_authority_locked(inner: &ForwardingInner, module: &ModuleConnection) -> TargetAuthority {
4262    if module.verified_prefix_owner.is_some() {
4263        return TargetAuthority::Prefix;
4264    }
4265    match inner
4266        .target_authority_by_connection
4267        .get(&module.endpoint.connection_id)
4268    {
4269        Some(record) => {
4270            let key = record.key();
4271            TargetAuthority::Spawn(
4272                AuthorityPair {
4273                    epoch: published_epoch_locked(inner, &key),
4274                    key: key.clone(),
4275                },
4276                inner
4277                    .spawn_approved
4278                    .get(&record.key())
4279                    .cloned()
4280                    .unwrap_or_else(ApprovedDeclarations::none_approved),
4281                inner.spawn_marks.contains(&key),
4282            )
4283        }
4284        None => TargetAuthority::Unsupervised,
4285    }
4286}
4287
4288fn published_epoch_locked(inner: &ForwardingInner, key: &SpawnKey) -> u64 {
4289    inner
4290        .spawn_epochs
4291        .get(key)
4292        .copied()
4293        .unwrap_or(crate::spawn_authority::INITIAL_AUTHORITY_EPOCH)
4294}
4295
4296/// Drop the epoch tombstones of `newest`'s module's earlier dead spawns that
4297/// no pending bind names any more. A tombstone a pending bind still names is
4298/// kept, so that bind is refused as stale at commit rather than compared with
4299/// the initial epoch an absent entry reads as. Live spawns are never in
4300/// `dead_spawns`, so their entries are never touched here.
4301fn prune_dead_spawn_tombstones_locked(inner: &mut ForwardingInner, newest: &SpawnKey) {
4302    let named = inner
4303        .pending_relays
4304        .values()
4305        .flat_map(|pending| {
4306            [
4307                pending.caller_authority.as_ref(),
4308                pending.target_authority.pair(),
4309            ]
4310        })
4311        .flatten()
4312        .map(|pair| pair.key.clone())
4313        .collect::<HashSet<_>>();
4314    let expired = inner
4315        .dead_spawns
4316        .iter()
4317        .filter(|dead| {
4318            dead.module_id == newest.module_id && *dead != newest && !named.contains(*dead)
4319        })
4320        .cloned()
4321        .collect::<Vec<_>>();
4322    for dead in expired {
4323        inner.dead_spawns.remove(&dead);
4324        inner.spawn_epochs.remove(&dead);
4325    }
4326}
4327
4328fn authority_stale_locked(inner: &ForwardingInner, pair: Option<&AuthorityPair>) -> bool {
4329    pair.is_some_and(|pair| published_epoch_locked(inner, &pair.key) > pair.epoch)
4330}
4331
4332fn spawn_connection_dead(inner: &ForwardingInner, connection: ConnectionId) -> bool {
4333    inner
4334        .spawn_connections
4335        .get(&connection)
4336        .is_some_and(|spawn| spawn.upgrade().is_none_or(|spawn| !spawn.launch_ready()))
4337}
4338
4339/// The live module connection registered under exactly `endpoint`, whichever
4340/// slot holds it: active, swap candidate, or superseded incumbent.
4341///
4342/// Resolving by endpoint rather than by module id is what keeps an incumbent
4343/// addressable after a swap promoted a candidate over its id. An endpoint that
4344/// is in none of the three (a stale one, replaced without a promotion) resolves
4345/// to nothing, as it always has.
4346fn module_connection_for_endpoint_locked(
4347    inner: &ForwardingInner,
4348    endpoint: ModuleEndpointId,
4349) -> Option<&ModuleConnection> {
4350    let module_id = inner.module_id_by_endpoint.get(&endpoint)?;
4351    inner
4352        .modules_by_id
4353        .get(module_id)
4354        .filter(|module| module.endpoint == endpoint)
4355        .or_else(|| {
4356            inner
4357                .candidates_by_id
4358                .get(module_id)
4359                .filter(|module| module.endpoint == endpoint)
4360        })
4361        .or_else(|| inner.superseded_endpoints.get(&endpoint))
4362}
4363
4364fn abandoned_route_target(
4365    inner: &ForwardingInner,
4366    reservation: &RouteReservation,
4367) -> Option<GoodbyeTarget> {
4368    let module_id = inner
4369        .module_id_by_endpoint
4370        .get(&reservation.module_key.endpoint)?;
4371    let module = module_connection_for_endpoint_locked(inner, reservation.module_key.endpoint)?;
4372    (module.endpoint == reservation.module_key.endpoint).then(|| GoodbyeTarget {
4373        connection_id: module.endpoint.connection_id,
4374        sink: module.sink.clone(),
4375        negotiated_ver: module.negotiated_ver,
4376        channel: reservation.module_key.channel,
4377        epoch: reservation.module_epoch,
4378        kind: GoodbyeTargetKind::Module,
4379        module_id: Some(module_id.clone()),
4380    })
4381}
4382
4383/// Queue a registering module's HELLO_ACK on its sink. Called with the
4384/// forwarding write lock held, before the endpoint is inserted, which is what
4385/// puts the ack ahead of any `route.bind` or control RPC routed to the module.
4386/// `try_send` never waits, so holding the lock across it is safe.
4387fn enqueue_hello_ack_locked(
4388    sink: &FrameSink,
4389    connection_id: ConnectionId,
4390    hello_ack: Option<Frame>,
4391) -> Result<(), ForwardingError> {
4392    let Some(hello_ack) = hello_ack else {
4393        return Ok(());
4394    };
4395    sink.try_send(hello_ack)
4396        .map_err(|_| ForwardingError::ModuleEgressUnavailable { connection_id })
4397}
4398
4399fn remove_module_connection_locked(
4400    inner: &mut ForwardingInner,
4401    endpoint: ModuleEndpointId,
4402) -> ConnectionCleanup {
4403    // Commit the disconnect before its routes are released, so their teardown
4404    // cannot replace module_closed with route_closed.
4405    inner.operator_confirms.module_closed(endpoint);
4406    inner.draining_endpoints.remove(&endpoint);
4407    inner.daemon_drain_results.remove(&endpoint);
4408    let module_id = inner.module_id_by_endpoint.remove(&endpoint);
4409    if let Some(module_id) = module_id.as_ref() {
4410        if inner
4411            .modules_by_id
4412            .get(module_id)
4413            .is_some_and(|module| module.endpoint == endpoint)
4414        {
4415            inner.modules_by_id.remove(module_id);
4416        }
4417        if inner
4418            .candidates_by_id
4419            .get(module_id)
4420            .is_some_and(|module| module.endpoint == endpoint)
4421        {
4422            inner.candidates_by_id.remove(module_id);
4423        }
4424    }
4425    inner.superseded_endpoints.remove(&endpoint);
4426    inner.endpoint_by_connection.remove(&endpoint.connection_id);
4427    inner.next_module_channel.remove(&endpoint);
4428    inner.next_control_corr.remove(&endpoint);
4429    inner
4430        .health_probe_tombstones
4431        .retain(|(pending_endpoint, _), _| *pending_endpoint != endpoint);
4432    inner
4433        .module_slot_epochs
4434        .retain(|key, _| key.endpoint != endpoint);
4435    let reserved_module_keys: Vec<ModuleRouteKey> = inner
4436        .reserved_module
4437        .keys()
4438        .filter(|module_key| module_key.endpoint == endpoint)
4439        .copied()
4440        .collect();
4441    for module_key in reserved_module_keys {
4442        if let Some(client_key) = inner.reserved_module.get(&module_key).copied() {
4443            release_reserved_route_locked(inner, client_key, module_key);
4444        }
4445    }
4446
4447    let pending_keys: Vec<_> = inner
4448        .pending_relays
4449        .keys()
4450        .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
4451        .copied()
4452        .collect();
4453    let pending: Vec<_> = pending_keys
4454        .into_iter()
4455        .filter_map(|key| {
4456            inner
4457                .pending_relays
4458                .remove(&key)
4459                .map(|pending| (key, pending))
4460        })
4461        .collect();
4462    let abandoned_relays = u32::try_from(pending.len()).unwrap_or(u32::MAX);
4463    for (key, pending) in pending {
4464        // Recorded like every other removal without a reply, so a `route.open`
4465        // still sending the bind learns the relay was released rather than
4466        // settled by the module.
4467        if !pending.relay_enqueued {
4468            inner.relays_released_before_enqueue.insert(key);
4469        }
4470        let module_label = module_id.as_deref().unwrap_or("unknown");
4471        let _ = pending
4472            .sender
4473            .send(RouteBindRelayOutcome::ModuleGone(format!(
4474                "module '{module_label}' connection closed during route.bind relay"
4475            )));
4476    }
4477
4478    let pending_control_keys: Vec<_> = inner
4479        .pending_control_rpcs
4480        .keys()
4481        .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
4482        .copied()
4483        .collect();
4484    let pending_control: Vec<_> = pending_control_keys
4485        .into_iter()
4486        .filter_map(|key| inner.pending_control_rpcs.remove(&key))
4487        .collect();
4488    for pending in pending_control {
4489        let module_label = module_id.as_deref().unwrap_or("unknown");
4490        let _ = pending
4491            .sender
4492            .send(ModuleControlRpcOutcome::ModuleGone(format!(
4493                "module '{module_label}' connection closed during module-control RPC"
4494            )));
4495    }
4496
4497    let module_routes = inner
4498        .module_to_client
4499        .iter()
4500        .filter(|(module_key, _)| module_key.endpoint == endpoint)
4501        .map(|(module_key, route)| (*module_key, route.module_epoch))
4502        .collect::<Vec<_>>();
4503    let mut released = Vec::with_capacity(module_routes.len());
4504    for (module_key, epoch) in module_routes {
4505        if let RouteRelease::Removed(target) = release_module_route_locked(inner, module_key, epoch)
4506        {
4507            released.push(target);
4508        }
4509    }
4510    ConnectionCleanup {
4511        released,
4512        abandoned_relays,
4513    }
4514}
4515
4516#[derive(Debug, Clone, Copy)]
4517struct RequestCredit {
4518    subscription: bool,
4519    watch_credit: bool,
4520    excluded_from_drain: bool,
4521}
4522
4523/// Held credits by correlation, with exact totals kept beside them so a busy
4524/// refusal can report the occupancy without walking every held credit.
4525#[derive(Debug, Default)]
4526struct CreditLedger {
4527    by_corr: HashMap<u64, Vec<RequestCredit>>,
4528    total: usize,
4529    subscriptions: usize,
4530}
4531
4532impl CreditLedger {
4533    fn acquire(&mut self, corr: u64, subscription: bool, watch_credit: bool) {
4534        self.total += 1;
4535        self.subscriptions += usize::from(subscription);
4536        self.by_corr.entry(corr).or_default().push(RequestCredit {
4537            subscription,
4538            watch_credit,
4539            excluded_from_drain: false,
4540        });
4541    }
4542
4543    fn release(&mut self, corr: u64) -> Option<RequestCredit> {
4544        let credits = self.by_corr.get_mut(&corr)?;
4545        let released = credits.pop();
4546        if credits.is_empty() {
4547            self.by_corr.remove(&corr);
4548        }
4549        if let Some(credit) = &released {
4550            self.total -= 1;
4551            self.subscriptions -= usize::from(credit.subscription);
4552        }
4553        released
4554    }
4555
4556    fn capture_subscription_exclusions(&mut self) -> u32 {
4557        let mut excluded = 0u32;
4558        for credit in self.by_corr.values_mut().flatten() {
4559            if credit.subscription && !credit.excluded_from_drain {
4560                credit.excluded_from_drain = true;
4561                excluded = excluded.saturating_add(1);
4562            }
4563        }
4564        excluded
4565    }
4566
4567    fn in_flight(&self) -> usize {
4568        self.total
4569    }
4570
4571    fn drain_in_flight(&self) -> usize {
4572        self.by_corr
4573            .values()
4574            .flatten()
4575            .filter(|credit| !credit.excluded_from_drain)
4576            .count()
4577    }
4578
4579    /// The correlation ids of the requests a drain still waits on, one entry
4580    /// per held credit, in ascending order.
4581    fn drain_held_corrs(&self) -> Vec<u64> {
4582        let mut corrs = self
4583            .by_corr
4584            .iter()
4585            .flat_map(|(corr, credits)| {
4586                credits
4587                    .iter()
4588                    .filter(|credit| !credit.excluded_from_drain)
4589                    .map(move |_| *corr)
4590            })
4591            .collect::<Vec<_>>();
4592        corrs.sort_unstable();
4593        corrs
4594    }
4595}
4596
4597#[derive(Debug, Default)]
4598struct ChannelFlowState {
4599    closed: bool,
4600    credits: CreditLedger,
4601    last_busy_warn: Option<tokio::time::Instant>,
4602    /// Requests whose client delivery ended with `frame_too_large` while the
4603    /// module may still be running them; see `refused_streams`.
4604    refused: std::collections::HashSet<u64>,
4605    /// Client frames waiting for this legacy route's credit.
4606    waiting: waiting_requests::WaitingRequests,
4607}
4608
4609#[path = "forwarding_refused_streams.rs"]
4610mod refused_streams;
4611#[path = "forwarding_waiting_requests.rs"]
4612mod waiting_requests;
4613pub(crate) use waiting_requests::LegacyArrival;
4614#[cfg(test)]
4615pub(crate) use waiting_requests::WAITING_REQUESTS_PER_ROUTE;
4616
4617/// Per-channel request-credit accounting shared by the client and module route halves.
4618#[derive(Debug)]
4619pub(crate) struct ChannelFlow {
4620    sem: Semaphore,
4621    window: usize,
4622    busy_refusals: bool,
4623    watch_sem: Option<Semaphore>,
4624    watch_window: Option<usize>,
4625    state: Mutex<ChannelFlowState>,
4626    /// How many entries `ChannelFlowState::refused` holds, read without the lock.
4627    refused_count: std::sync::atomic::AtomicUsize,
4628    /// How many frames wait in `ChannelFlowState::waiting`, and the wake-up
4629    /// for a reader waiting for room there.
4630    waiting_len: std::sync::atomic::AtomicUsize,
4631    waiting_room: tokio::sync::Notify,
4632}
4633
4634impl ChannelFlow {
4635    pub(crate) fn new(window: usize) -> Self {
4636        Self::with_admission(window, false, None)
4637    }
4638
4639    fn with_admission(window: usize, busy_refusals: bool, watch_window: Option<usize>) -> Self {
4640        debug_assert!(window > 0, "flow-control window must be non-zero");
4641        Self {
4642            sem: Semaphore::new(window),
4643            window,
4644            busy_refusals,
4645            watch_sem: watch_window.map(Semaphore::new),
4646            watch_window,
4647            state: Mutex::new(ChannelFlowState::default()),
4648            refused_count: std::sync::atomic::AtomicUsize::new(0),
4649            waiting_len: std::sync::atomic::AtomicUsize::new(0),
4650            waiting_room: tokio::sync::Notify::new(),
4651        }
4652    }
4653
4654    pub(crate) fn busy_refusals(&self) -> bool {
4655        self.busy_refusals
4656    }
4657
4658    fn try_acquire_tagged(&self, corr: u64, subscription: bool) -> RequestAdmission {
4659        let mut state = self
4660            .state
4661            .lock()
4662            .unwrap_or_else(|poisoned| poisoned.into_inner());
4663        if state.closed {
4664            return RequestAdmission::Stale;
4665        }
4666        let busy = |state: &ChannelFlowState| {
4667            RequestAdmission::Busy(subc_protocol::RouteBusyDetail {
4668                reason: "no_credit".into(),
4669                request_in_flight: state.credits.in_flight(),
4670                watch_in_flight: state.credits.subscriptions,
4671                request_window: self.window,
4672                watch_window: self.watch_window,
4673            })
4674        };
4675        let Ok(total) = self.sem.try_acquire() else {
4676            return busy(&state);
4677        };
4678        // A watch takes the total credit first. Dropping it on watch-lane
4679        // exhaustion rolls back before any ledger entry becomes visible.
4680        let watch = if subscription {
4681            if let Some(sem) = &self.watch_sem {
4682                match sem.try_acquire() {
4683                    Ok(permit) => Some(permit),
4684                    Err(_) => return busy(&state),
4685                }
4686            } else {
4687                None
4688            }
4689        } else {
4690            None
4691        };
4692        state.credits.acquire(corr, subscription, watch.is_some());
4693        total.forget();
4694        if let Some(watch) = watch {
4695            watch.forget();
4696        }
4697        RequestAdmission::Admitted
4698    }
4699
4700    pub(crate) fn should_warn_busy(&self) -> bool {
4701        let mut state = self
4702            .state
4703            .lock()
4704            .unwrap_or_else(|poisoned| poisoned.into_inner());
4705        let now = tokio::time::Instant::now();
4706        if state
4707            .last_busy_warn
4708            .is_some_and(|last| now.duration_since(last) < std::time::Duration::from_secs(60))
4709        {
4710            return false;
4711        }
4712        state.last_busy_warn = Some(now);
4713        true
4714    }
4715
4716    #[cfg(test)]
4717    pub(crate) async fn acquire(&self) -> Result<(), ChannelFlowClosed> {
4718        self.acquire_tagged(0, false).await
4719    }
4720
4721    pub(crate) async fn acquire_tagged(
4722        &self,
4723        corr: u64,
4724        subscription: bool,
4725    ) -> Result<(), ChannelFlowClosed> {
4726        let permit = self.sem.acquire().await.map_err(|_| ChannelFlowClosed)?;
4727        let mut state = self
4728            .state
4729            .lock()
4730            .unwrap_or_else(|poisoned| poisoned.into_inner());
4731        if state.closed {
4732            return Err(ChannelFlowClosed);
4733        }
4734        state.credits.acquire(corr, subscription, false);
4735        permit.forget();
4736        Ok(())
4737    }
4738
4739    #[cfg(test)]
4740    pub(crate) fn release(&self) {
4741        self.release_corr(0);
4742    }
4743
4744    pub(crate) fn release_corr(&self, corr: u64) {
4745        let mut state = self
4746            .state
4747            .lock()
4748            .unwrap_or_else(|poisoned| poisoned.into_inner());
4749        let Some(released) = state.credits.release(corr) else {
4750            // Protocol-conforming modules emit exactly one terminal per request.
4751            // This guard is a best-effort safety net against window growth, not a
4752            // security boundary against malicious peers.
4753            warn!(
4754                window = self.window,
4755                available = self.sem.available_permits(),
4756                "flow-control over-release ignored"
4757            );
4758            return;
4759        };
4760        if !self.sem.is_closed() {
4761            self.sem.add_permits(1);
4762        }
4763        if released.watch_credit {
4764            if let Some(watch_sem) = self.watch_sem.as_ref().filter(|sem| !sem.is_closed()) {
4765                watch_sem.add_permits(1);
4766            }
4767        }
4768    }
4769
4770    #[cfg(test)]
4771    pub(crate) fn in_flight(&self) -> usize {
4772        self.state
4773            .lock()
4774            .unwrap_or_else(|poisoned| poisoned.into_inner())
4775            .credits
4776            .in_flight()
4777    }
4778
4779    pub(crate) fn drain_in_flight(&self) -> usize {
4780        self.state
4781            .lock()
4782            .unwrap_or_else(|poisoned| poisoned.into_inner())
4783            .credits
4784            .drain_in_flight()
4785    }
4786
4787    pub(crate) fn drain_held_corrs(&self) -> Vec<u64> {
4788        self.state
4789            .lock()
4790            .unwrap_or_else(|poisoned| poisoned.into_inner())
4791            .credits
4792            .drain_held_corrs()
4793    }
4794
4795    #[cfg(test)]
4796    pub(crate) fn available_permits(&self) -> usize {
4797        self.sem.available_permits()
4798    }
4799
4800    pub(crate) fn begin_drain(&self) -> u32 {
4801        let mut state = self
4802            .state
4803            .lock()
4804            .unwrap_or_else(|poisoned| poisoned.into_inner());
4805        state.closed = true;
4806        self.sem.close();
4807        if let Some(sem) = &self.watch_sem {
4808            sem.close();
4809        }
4810        state.credits.capture_subscription_exclusions()
4811    }
4812
4813    pub(crate) fn close(&self) {
4814        let mut state = self
4815            .state
4816            .lock()
4817            .unwrap_or_else(|poisoned| poisoned.into_inner());
4818        state.closed = true;
4819        self.sem.close();
4820        if let Some(sem) = &self.watch_sem {
4821            sem.close();
4822        }
4823        // Ends the wait of a task forwarding this route's waiting requests.
4824        self.waiting_room.notify_waiters();
4825    }
4826}
4827
4828#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4829pub(crate) struct ChannelFlowClosed;
4830
4831#[derive(Debug, Clone, PartialEq, Eq)]
4832pub(crate) enum RequestAdmission {
4833    Admitted,
4834    Busy(subc_protocol::RouteBusyDetail),
4835    ModuleReloading,
4836    Stale,
4837}
4838
4839impl fmt::Display for ChannelFlowClosed {
4840    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4841        write!(f, "flow-control window closed")
4842    }
4843}
4844
4845impl Error for ChannelFlowClosed {}
4846
4847#[cfg(test)]
4848#[path = "route_busy_flow_tests.rs"]
4849mod route_busy_flow_tests;
4850
4851fn window_for(concurrency: &Concurrency) -> usize {
4852    match concurrency {
4853        Concurrency::Serial => 1,
4854        Concurrency::ModuleManaged => DEFAULT_MODULE_MANAGED_WINDOW,
4855        Concurrency::StatelessParallel => STATELESS_PARALLEL_WINDOW,
4856    }
4857}
4858
4859#[derive(Debug, Clone, PartialEq, Eq)]
4860pub enum ForwardingError {
4861    /// A connection cannot hold both client routes and a module endpoint, or
4862    /// replace a module identity while that endpoint is still registered.
4863    ConnectionRoleConflict {
4864        connection_id: ConnectionId,
4865    },
4866    NoModuleConnection,
4867    ModuleReloading {
4868        module_id: String,
4869    },
4870    StaleModuleEndpoint,
4871    UnknownReservation {
4872        client_channel: u16,
4873        module_channel: u16,
4874    },
4875    ClientRouteChannelExhausted {
4876        connection_id: ConnectionId,
4877    },
4878    ModuleRouteChannelExhausted {
4879        endpoint: ModuleEndpointId,
4880    },
4881    RelayCorrelationExhausted,
4882    ConnectionClosing {
4883        connection_id: ConnectionId,
4884    },
4885    ClientEgressClosed {
4886        connection_id: ConnectionId,
4887    },
4888    RouteOpenBuild(String),
4889    /// A swap candidate is already registered for this module id.
4890    CandidateSlotOccupied {
4891        module_id: String,
4892    },
4893    /// A registering module's HELLO_ACK could not be queued because its
4894    /// outbound queue is closed or full.
4895    ModuleEgressUnavailable {
4896        connection_id: ConnectionId,
4897    },
4898    /// A capability-fenced bind's admitted target registration was replaced
4899    /// before the bind was reserved.
4900    TargetRegistrationChanged(String),
4901    /// `route.open`'s relay deadline passed before the bind could be reserved.
4902    RelayDeadlineElapsed,
4903    Poisoned,
4904}
4905
4906impl fmt::Display for ForwardingError {
4907    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4908        match self {
4909            Self::ConnectionRoleConflict { connection_id } => write!(f, "connection {} already holds an incompatible role", connection_id.get()),
4910            Self::NoModuleConnection => write!(f, "no module connection is registered"),
4911            Self::ModuleReloading { module_id } => {
4912                write!(f, "module_id '{module_id}' is reloading")
4913            }
4914            Self::StaleModuleEndpoint => write!(f, "module connection generation is stale"),
4915            Self::UnknownReservation {
4916                client_channel,
4917                module_channel,
4918            } => write!(
4919                f,
4920                "route reservation client channel {client_channel} / module channel {module_channel} was not found"
4921            ),
4922            Self::ClientRouteChannelExhausted { connection_id } => write!(
4923                f,
4924                "no client route channels are available for connection {}",
4925                connection_id.get()
4926            ),
4927            Self::ModuleRouteChannelExhausted { endpoint } => write!(
4928                f,
4929                "no module route channels are available for endpoint generation {} on connection {}",
4930                endpoint.generation,
4931                endpoint.connection_id.get()
4932            ),
4933            Self::RelayCorrelationExhausted => {
4934                write!(f, "module control correlation ids are exhausted")
4935            }
4936            Self::ConnectionClosing { connection_id } => write!(
4937                f,
4938                "connection {} is closing and cannot accept route allocation",
4939                connection_id.get()
4940            ),
4941            Self::ClientEgressClosed { connection_id } => write!(
4942                f,
4943                "client connection {} egress is closed",
4944                connection_id.get()
4945            ),
4946            Self::RouteOpenBuild(message) => {
4947                write!(f, "failed to prebuild route.open response: {message}")
4948            }
4949            Self::CandidateSlotOccupied { module_id } => write!(
4950                f,
4951                "module_id '{module_id}' already has a swap candidate registered"
4952            ),
4953            Self::ModuleEgressUnavailable { connection_id } => write!(
4954                f,
4955                "module connection {} egress is unavailable; HELLO_ACK could not be queued",
4956                connection_id.get()
4957            ),
4958            Self::TargetRegistrationChanged(message) => write!(f, "{message}"),
4959            Self::RelayDeadlineElapsed => write!(
4960                f,
4961                "the route.bind relay deadline passed while waiting for client egress"
4962            ),
4963            Self::Poisoned => write!(f, "forwarding table lock was poisoned"),
4964        }
4965    }
4966}
4967
4968impl Error for ForwardingError {}
4969
4970#[cfg(test)]
4971mod tests {
4972    use std::time::Duration;
4973
4974    use super::*;
4975    use tokio::sync::mpsc;
4976
4977    #[test]
4978    fn ordinary_long_running_request_is_not_excluded_from_drain() {
4979        let mut ledger = CreditLedger::default();
4980        ledger.acquire(1, false, false);
4981
4982        assert_eq!(ledger.capture_subscription_exclusions(), 0);
4983        assert_eq!(ledger.drain_in_flight(), 1);
4984    }
4985
4986    #[test]
4987    fn bit_set_subscription_is_excluded_and_counted() {
4988        let mut ledger = CreditLedger::default();
4989        ledger.acquire(1, true, false);
4990
4991        assert_eq!(ledger.capture_subscription_exclusions(), 1);
4992        assert_eq!(ledger.drain_in_flight(), 0);
4993    }
4994
4995    #[test]
4996    fn subscription_opened_after_drain_snapshot_is_not_excluded() {
4997        let mut ledger = CreditLedger::default();
4998        ledger.acquire(1, true, false);
4999        assert_eq!(ledger.capture_subscription_exclusions(), 1);
5000
5001        ledger.acquire(2, true, false);
5002
5003        assert_eq!(ledger.drain_in_flight(), 1);
5004    }
5005
5006    #[test]
5007    fn drain_with_no_subscriptions_reports_zero_excluded() {
5008        let mut ledger = CreditLedger::default();
5009        assert_eq!(ledger.capture_subscription_exclusions(), 0);
5010    }
5011
5012    fn test_hello_ack(corr: u64) -> Frame {
5013        Frame::build(
5014            FrameType::HelloAck,
5015            Flags::new(false, Priority::Passive, false),
5016            0,
5017            0,
5018            corr,
5019            Vec::new(),
5020        )
5021        .unwrap()
5022    }
5023
5024    /// An acked registration whose HELLO_ACK cannot be queued must leave no
5025    /// endpoint behind: a routable module that never got its ack would read a
5026    /// route.bind first and exit. A closed queue and a full one both refuse.
5027    #[test]
5028    fn acked_registration_that_cannot_queue_its_hello_ack_inserts_nothing() {
5029        let forwarding = ForwardingTable::default();
5030
5031        let (closed_tx, closed_rx) = mpsc::channel(8);
5032        drop(closed_rx);
5033        let closed = ConnectionId::new(1);
5034        assert_eq!(
5035            forwarding.register_module_connection_acked(
5036                closed,
5037                "closed".to_string(),
5038                2,
5039                Concurrency::ModuleManaged,
5040                FrameSink::new(closed_tx),
5041                ModuleHelloAck {
5042                    frame: test_hello_ack(1),
5043                    verified_prefix_owner: None
5044                },
5045            ),
5046            Err(ForwardingError::ModuleEgressUnavailable {
5047                connection_id: closed
5048            })
5049        );
5050
5051        let (full_tx, _full_rx) = mpsc::channel(1);
5052        let full_sink = FrameSink::new(full_tx);
5053        full_sink.try_send(test_hello_ack(99)).unwrap();
5054        let full = ConnectionId::new(2);
5055        assert_eq!(
5056            forwarding.register_module_connection_acked(
5057                full,
5058                "full".to_string(),
5059                2,
5060                Concurrency::ModuleManaged,
5061                full_sink.clone(),
5062                ModuleHelloAck {
5063                    frame: test_hello_ack(2),
5064                    verified_prefix_owner: None
5065                },
5066            ),
5067            Err(ForwardingError::ModuleEgressUnavailable {
5068                connection_id: full
5069            })
5070        );
5071        assert_eq!(
5072            forwarding.register_candidate_module_connection_acked(
5073                full,
5074                "full".to_string(),
5075                2,
5076                Concurrency::ModuleManaged,
5077                full_sink,
5078                test_hello_ack(3),
5079            ),
5080            Err(ForwardingError::ModuleEgressUnavailable {
5081                connection_id: full
5082            })
5083        );
5084
5085        for (connection, module_id) in [(closed, "closed"), (full, "full")] {
5086            assert_eq!(
5087                forwarding
5088                    .module_endpoint_for_connection(connection)
5089                    .unwrap(),
5090                None
5091            );
5092            let (client_tx, _client_rx) = mpsc::channel(8);
5093            assert_eq!(
5094                forwarding
5095                    .begin_route_bind_relay_for_test(
5096                        ConnectionId::new(50),
5097                        FrameSink::new(client_tx),
5098                        1,
5099                        module_id,
5100                    )
5101                    .err(),
5102                Some(ForwardingError::NoModuleConnection)
5103            );
5104        }
5105        assert!(forwarding.read_inner().unwrap().candidates_by_id.is_empty());
5106    }
5107
5108    /// Both acked registration forms put the HELLO_ACK on the module's queue
5109    /// by the time the endpoint can be resolved.
5110    #[test]
5111    fn acked_registration_queues_the_hello_ack_first() {
5112        let forwarding = ForwardingTable::default();
5113        let (active_tx, mut active_rx) = mpsc::channel(8);
5114        forwarding
5115            .register_module_connection_acked(
5116                ConnectionId::new(1),
5117                "acked".to_string(),
5118                2,
5119                Concurrency::ModuleManaged,
5120                FrameSink::new(active_tx),
5121                ModuleHelloAck {
5122                    frame: test_hello_ack(11),
5123                    verified_prefix_owner: None,
5124                },
5125            )
5126            .unwrap();
5127        let (candidate_tx, mut candidate_rx) = mpsc::channel(8);
5128        forwarding
5129            .register_candidate_module_connection_acked(
5130                ConnectionId::new(2),
5131                "acked".to_string(),
5132                2,
5133                Concurrency::ModuleManaged,
5134                FrameSink::new(candidate_tx),
5135                test_hello_ack(12),
5136            )
5137            .unwrap();
5138
5139        let active_first = active_rx.try_recv().unwrap().frame;
5140        assert_eq!(active_first.header.ty, FrameType::HelloAck);
5141        assert_eq!(active_first.header.corr, 11);
5142        let candidate_first = candidate_rx.try_recv().unwrap().frame;
5143        assert_eq!(candidate_first.header.ty, FrameType::HelloAck);
5144        assert_eq!(candidate_first.header.corr, 12);
5145    }
5146
5147    #[test]
5148    fn multi_provider_route_limit_reports_per_client_exhaustion_without_affecting_second_client() {
5149        let forwarding = ForwardingTable::default();
5150        let module_connection = ConnectionId::new(10);
5151        let exhausted_client = ConnectionId::new(20);
5152        let second_client = ConnectionId::new(30);
5153        let (module_tx, _module_rx) = mpsc::channel(1);
5154        let endpoint = forwarding
5155            .register_module_connection(
5156                module_connection,
5157                "route-limit-provider".to_string(),
5158                1,
5159                Concurrency::ModuleManaged,
5160                FrameSink::new(module_tx),
5161            )
5162            .unwrap();
5163
5164        {
5165            let mut inner = forwarding.inner.write().unwrap();
5166            for channel in 1..=u16::MAX {
5167                inner.reserved_client.insert(
5168                    ClientRouteKey {
5169                        connection_id: exhausted_client,
5170                        channel,
5171                    },
5172                    ModuleRouteKey {
5173                        endpoint,
5174                        channel: 1,
5175                    },
5176                );
5177            }
5178        }
5179
5180        let (exhausted_tx, _exhausted_rx) = mpsc::channel(1);
5181        let err = forwarding
5182            .begin_route_bind_relay_for_test(
5183                exhausted_client,
5184                FrameSink::new(exhausted_tx),
5185                1,
5186                "route-limit-provider",
5187            )
5188            .unwrap_err();
5189        assert!(matches!(
5190            err,
5191            ForwardingError::ClientRouteChannelExhausted { connection_id }
5192                if connection_id == exhausted_client
5193        ));
5194
5195        let (second_tx, _second_rx) = mpsc::channel(1);
5196        let pending = forwarding
5197            .begin_route_bind_relay_for_test(
5198                second_client,
5199                FrameSink::new(second_tx),
5200                2,
5201                "route-limit-provider",
5202            )
5203            .unwrap();
5204        assert_eq!(pending.client_channel, 1);
5205    }
5206
5207    #[test]
5208    fn released_module_channels_are_reused_after_wrap_without_slot_leak() {
5209        let forwarding = ForwardingTable::default();
5210        let module_connection = ConnectionId::new(40);
5211        let client = ConnectionId::new(50);
5212        let (module_tx, _module_rx) = mpsc::channel(1);
5213        forwarding
5214            .register_module_connection(
5215                module_connection,
5216                "slot-reuse-provider".to_string(),
5217                1,
5218                Concurrency::ModuleManaged,
5219                FrameSink::new(module_tx),
5220            )
5221            .unwrap();
5222
5223        let (client_tx, _client_rx) = mpsc::channel(1);
5224        let client_sink = FrameSink::new(client_tx);
5225        let mut wrapped_channel = None;
5226        for index in 0..=usize::from(u16::MAX) {
5227            let pending = forwarding
5228                .begin_route_bind_relay_for_test(
5229                    client,
5230                    client_sink.clone(),
5231                    index as u64 + 1,
5232                    "slot-reuse-provider",
5233                )
5234                .unwrap();
5235            if index == usize::from(u16::MAX) {
5236                wrapped_channel = Some(pending.module_channel);
5237            }
5238            forwarding
5239                .abort_pending_relay(
5240                    pending.endpoint,
5241                    pending.corr,
5242                    RouteBindRelayOutcome::ModuleGone("test abort".to_string()),
5243                )
5244                .unwrap();
5245        }
5246
5247        assert_eq!(wrapped_channel, Some(1));
5248    }
5249
5250    #[test]
5251    fn cleanup_connection_prunes_stale_next_client_channel_cursor() {
5252        let forwarding = ForwardingTable::default();
5253        let client = ConnectionId::new(60);
5254        forwarding
5255            .inner
5256            .write()
5257            .unwrap()
5258            .next_client_channel
5259            .insert(client, 41);
5260
5261        let released = forwarding.cleanup_connection(client).unwrap();
5262
5263        assert!(released.is_empty());
5264        assert!(!forwarding
5265            .inner
5266            .read()
5267            .unwrap()
5268            .next_client_channel
5269            .contains_key(&client));
5270    }
5271
5272    #[test]
5273    fn stale_module_cleanup_preserves_fast_reconnect_successor() {
5274        let forwarding = ForwardingTable::default();
5275        let module_id = "fast-reconnect-provider";
5276        let first_connection = ConnectionId::new(70);
5277        let second_connection = ConnectionId::new(80);
5278        let (first_tx, _first_rx) = mpsc::channel(1);
5279        let first_endpoint = forwarding
5280            .register_module_connection(
5281                first_connection,
5282                module_id.to_string(),
5283                1,
5284                Concurrency::ModuleManaged,
5285                FrameSink::new(first_tx),
5286            )
5287            .unwrap();
5288        let (second_tx, _second_rx) = mpsc::channel(1);
5289        let second_endpoint = forwarding
5290            .register_module_connection(
5291                second_connection,
5292                module_id.to_string(),
5293                1,
5294                Concurrency::ModuleManaged,
5295                FrameSink::new(second_tx),
5296            )
5297            .unwrap();
5298        assert_ne!(first_endpoint, second_endpoint);
5299
5300        let released = forwarding.cleanup_connection(first_connection).unwrap();
5301
5302        assert!(released.is_empty());
5303        assert_eq!(
5304            forwarding
5305                .inner
5306                .read()
5307                .unwrap()
5308                .modules_by_id
5309                .get(module_id)
5310                .map(|module| module.endpoint),
5311            Some(second_endpoint)
5312        );
5313        assert!(forwarding.has_live_module_connection(module_id).unwrap());
5314        let control_rpc = forwarding
5315            .begin_module_control_rpc_for(
5316                module_id,
5317                "health.check",
5318                Instant::now() + Duration::from_secs(1),
5319            )
5320            .unwrap();
5321        assert_eq!(control_rpc.endpoint, second_endpoint);
5322    }
5323
5324    fn route_fixture(
5325        module_id: &str,
5326    ) -> (
5327        ForwardingTable,
5328        ConnectionId,
5329        ModuleEndpointId,
5330        ConnectionId,
5331        FrameSink,
5332        mpsc::Receiver<crate::router::OutboundFrame>,
5333    ) {
5334        let forwarding = ForwardingTable::default();
5335        let module_connection = ConnectionId::new(100);
5336        let client_connection = ConnectionId::new(200);
5337        let (module_tx, _module_rx) = mpsc::channel(8);
5338        let endpoint = forwarding
5339            .register_module_connection(
5340                module_connection,
5341                module_id.to_string(),
5342                2,
5343                Concurrency::ModuleManaged,
5344                FrameSink::new(module_tx),
5345            )
5346            .unwrap();
5347        let (client_tx, client_rx) = mpsc::channel(8);
5348        (
5349            forwarding,
5350            module_connection,
5351            endpoint,
5352            client_connection,
5353            FrameSink::new(client_tx),
5354            client_rx,
5355        )
5356    }
5357
5358    #[test]
5359    #[cfg(unix)]
5360    fn daemon_drain_gates_current_and_racing_provider_registrations() {
5361        let (forwarding, _, endpoint, _, sink, _) = route_fixture("provider");
5362        assert_eq!(
5363            forwarding.begin_daemon_drain().unwrap(),
5364            [("provider".to_string(), endpoint)]
5365        );
5366        assert!(forwarding.endpoint_is_draining(endpoint).unwrap());
5367        assert!(matches!(
5368            forwarding.register_module_connection(
5369                ConnectionId::new(300),
5370                "late-provider".into(),
5371                2,
5372                Concurrency::ModuleManaged,
5373                sink,
5374            ),
5375            Err(ForwardingError::ConnectionClosing { .. })
5376        ));
5377    }
5378
5379    #[test]
5380    #[cfg(unix)]
5381    fn daemon_drain_results_are_endpoint_fenced_and_removed_on_cleanup() {
5382        let (forwarding, connection, endpoint, _, _, _) = route_fixture("provider");
5383        assert_eq!(
5384            forwarding
5385                .daemon_drain_result_for_connection(connection)
5386                .unwrap(),
5387            None
5388        );
5389        forwarding
5390            .record_daemon_drain_result(endpoint, true)
5391            .unwrap();
5392        forwarding.begin_daemon_drain().unwrap();
5393        assert_eq!(
5394            forwarding
5395                .daemon_drain_result_for_connection(connection)
5396                .unwrap(),
5397            Some(false)
5398        );
5399        let replacement = ModuleEndpointId {
5400            generation: endpoint.generation + 1,
5401            ..endpoint
5402        };
5403        forwarding
5404            .record_daemon_drain_result(replacement, true)
5405            .unwrap();
5406        assert_eq!(
5407            forwarding
5408                .daemon_drain_result_for_connection(connection)
5409                .unwrap(),
5410            Some(false)
5411        );
5412        forwarding
5413            .record_daemon_drain_result(endpoint, true)
5414            .unwrap();
5415        assert_eq!(
5416            forwarding
5417                .daemon_drain_result_for_connection(connection)
5418                .unwrap(),
5419            Some(true)
5420        );
5421        assert_eq!(
5422            forwarding
5423                .daemon_drain_result_for_connection(ConnectionId::new(300))
5424                .unwrap(),
5425            Some(false)
5426        );
5427        forwarding.cleanup_connection(connection).unwrap();
5428        forwarding
5429            .record_daemon_drain_result(endpoint, true)
5430            .unwrap();
5431        assert_eq!(
5432            forwarding
5433                .daemon_drain_result_for_connection(connection)
5434                .unwrap(),
5435            Some(false)
5436        );
5437        assert!(forwarding
5438            .read_inner()
5439            .unwrap()
5440            .daemon_drain_results
5441            .is_empty());
5442    }
5443
5444    #[test]
5445    #[cfg(unix)]
5446    fn late_bind_ack_during_daemon_drain_settles_without_leaking_or_closing_module() {
5447        let (forwarding, module_connection, endpoint, client_connection, sink, mut rx) =
5448            route_fixture("provider");
5449        let mut pending =
5450            begin_test_route(&forwarding, client_connection, sink.clone(), 1, "provider");
5451        assert_eq!(forwarding.reserved_route_count().unwrap(), (1, 1));
5452        forwarding.begin_daemon_drain().unwrap();
5453        let completion = forwarding
5454            .complete_pending_relay(
5455                module_connection,
5456                pending.corr,
5457                RouteBindRelayOutcome::Accepted,
5458            )
5459            .expect("draining admission is not a fatal module error");
5460        assert!(completion.settled);
5461        let abandoned = completion
5462            .abandoned
5463            .expect("late accepted bind needs a route GOODBYE");
5464        assert_eq!(abandoned.channel, pending.module_channel);
5465        assert!(matches!(pending.receiver.try_recv().unwrap(),
5466            RouteBindRelayOutcome::DaemonRejected(error) if error.code == "module_reloading"));
5467        assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
5468        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
5469        assert!(
5470            rx.try_recv().is_err(),
5471            "no route.open may be published during drain"
5472        );
5473        assert_eq!(
5474            forwarding
5475                .module_endpoint_for_connection(module_connection)
5476                .unwrap(),
5477            Some(endpoint)
5478        );
5479        assert!(
5480            !forwarding
5481                .complete_pending_relay(
5482                    module_connection,
5483                    pending.corr,
5484                    RouteBindRelayOutcome::Accepted,
5485                )
5486                .unwrap()
5487                .settled
5488        );
5489    }
5490
5491    fn test_ping(corr: u64) -> Frame {
5492        Frame::build(
5493            FrameType::Ping,
5494            Flags::new(false, Priority::Passive, false),
5495            0,
5496            0,
5497            corr,
5498            Vec::new(),
5499        )
5500        .unwrap()
5501    }
5502
5503    fn begin_test_route(
5504        forwarding: &ForwardingTable,
5505        client_connection: ConnectionId,
5506        client_sink: FrameSink,
5507        corr: u64,
5508        module_id: &str,
5509    ) -> PendingRouteBindRelay {
5510        forwarding
5511            .begin_route_bind_relay_for_test(client_connection, client_sink, corr, module_id)
5512            .unwrap()
5513    }
5514
5515    #[test]
5516    fn module_registration_and_client_reservation_are_mutually_exclusive_in_both_orders() {
5517        for candidate in [false, true] {
5518            for register_first in [false, true] {
5519                let (forwarding, module_connection, _, client_connection, sink, _rx) =
5520                    route_fixture("target");
5521                let register = || {
5522                    if candidate {
5523                        forwarding.register_candidate_module_connection(
5524                            client_connection,
5525                            "source".into(),
5526                            2,
5527                            Concurrency::ModuleManaged,
5528                            sink.clone(),
5529                        )
5530                    } else {
5531                        forwarding.register_module_connection(
5532                            client_connection,
5533                            "source".into(),
5534                            2,
5535                            Concurrency::ModuleManaged,
5536                            sink.clone(),
5537                        )
5538                    }
5539                };
5540                if register_first {
5541                    register().unwrap();
5542                    assert!(
5543                        forwarding
5544                            .begin_route_bind_relay_for_test(
5545                                client_connection,
5546                                sink.clone(),
5547                                1,
5548                                "target",
5549                            )
5550                            .is_err(),
5551                        "a deferred route.open cannot reserve after HELLO"
5552                    );
5553                    assert!(forwarding
5554                        .cleanup_connection(client_connection)
5555                        .unwrap()
5556                        .is_empty());
5557                } else {
5558                    let pending =
5559                        begin_test_route(&forwarding, client_connection, sink.clone(), 1, "target");
5560                    assert!(
5561                        register().is_err(),
5562                        "HELLO cannot register after a route reservation"
5563                    );
5564                    forwarding
5565                        .complete_pending_relay(
5566                            module_connection,
5567                            pending.corr,
5568                            RouteBindRelayOutcome::Accepted,
5569                        )
5570                        .unwrap();
5571                    assert_eq!(
5572                        forwarding
5573                            .cleanup_connection(client_connection)
5574                            .unwrap()
5575                            .len(),
5576                        1
5577                    );
5578                }
5579                assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
5580                assert_eq!(forwarding.active_binding_count().unwrap(), 0);
5581            }
5582        }
5583    }
5584
5585    /// A pending route.open reserves its queue slot with `reserve_owned` and
5586    /// sends its prebuilt response through that slot when the module accepts.
5587    /// A queue already holding many data frames (far more than the old 64-frame
5588    /// queue) must not stop the open from reserving or completing, and the
5589    /// response must be charged to the queue's byte count when it is sent.
5590    #[tokio::test]
5591    async fn pending_route_open_completes_behind_queued_data_frames() {
5592        assert_eq!(
5593            crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION,
5594            8,
5595            "the per-connection pending route.open limit is its own constant"
5596        );
5597        let (forwarding, module_connection, _endpoint, client, _unused_sink, _unused_rx) =
5598            route_fixture("open-behind-data");
5599        let (sink, mut client_rx) = crate::server::connection_egress();
5600        const DATA_FRAMES: usize = 1_000;
5601        let data = |corr: u64| {
5602            Frame::build(
5603                FrameType::StreamData,
5604                Flags::new(false, Priority::Interactive, false),
5605                9,
5606                1,
5607                corr,
5608                vec![b'x'; 200],
5609            )
5610            .unwrap()
5611        };
5612        for corr in 0..DATA_FRAMES as u64 {
5613            sink.try_send(data(corr)).unwrap();
5614        }
5615        let data_bytes = DATA_FRAMES * (subc_protocol::HEADER_LEN + 200);
5616        assert_eq!(sink.backlog().queued_bytes, data_bytes);
5617
5618        let pending = tokio::time::timeout(
5619            Duration::from_secs(5),
5620            forwarding.begin_route_bind_relay_for(
5621                client,
5622                sink.clone(),
5623                subc_protocol::PROTOCOL_VERSION,
5624                4_242,
5625                "open-behind-data",
5626                Principal::Direct,
5627                None,
5628                None,
5629                "fixture".into(),
5630                None,
5631                None,
5632                RouteAuthority::default(),
5633                Instant::now() + Duration::from_secs(60),
5634                false,
5635                None,
5636            ),
5637        )
5638        .await
5639        .expect("reserving the route.open slot must not wait behind data frames")
5640        .unwrap();
5641        forwarding
5642            .complete_pending_relay(
5643                module_connection,
5644                pending.corr,
5645                RouteBindRelayOutcome::Accepted,
5646            )
5647            .unwrap();
5648
5649        let backlog = sink.backlog();
5650        assert_eq!(backlog.queued_frames, DATA_FRAMES + 1);
5651        assert!(
5652            backlog.queued_bytes > data_bytes,
5653            "the route.open response must be counted in queued bytes: {backlog:?}"
5654        );
5655        for corr in 0..DATA_FRAMES as u64 {
5656            assert_eq!(client_rx.recv().await.unwrap().header.corr, corr);
5657        }
5658        let open = client_rx.recv().await.unwrap();
5659        assert_eq!(open.header.corr, 4_242);
5660        assert_eq!(open.header.ty, FrameType::Response);
5661        drop(open);
5662        assert_eq!(sink.backlog().queued_bytes, 0);
5663        assert_eq!(sink.backlog().queued_frames, 0);
5664    }
5665
5666    /// The drain-timeout line reports these numbers, so they must count the
5667    /// requests the drain is waiting on and no others: a route with nothing in
5668    /// flight is not a holdout, and a flagged subscription is excluded from the
5669    /// drain and so from the count.
5670    #[tokio::test]
5671    async fn drain_holdouts_count_held_requests_and_name_the_connection() {
5672        let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
5673            route_fixture("holdouts");
5674        let mut bound = |corr| {
5675            let route = begin_test_route(&forwarding, client, sink.clone(), corr, "holdouts");
5676            forwarding
5677                .complete_pending_relay(
5678                    module_connection,
5679                    route.corr,
5680                    RouteBindRelayOutcome::Accepted,
5681                )
5682                .unwrap();
5683            client_rx.try_recv().unwrap();
5684            match forwarding
5685                .lookup_data_route(client, route.client_channel, route.client_epoch)
5686                .unwrap()
5687            {
5688                DataRoute::Client(DataRouteState::Bound(binding)) => binding,
5689                other => panic!("expected live route, got {other:?}"),
5690            }
5691        };
5692        let holding = bound(61);
5693        let _idle = bound(62);
5694        holding.flow.acquire_tagged(7, false).await.unwrap();
5695        holding.flow.acquire_tagged(2, false).await.unwrap();
5696        holding.flow.acquire_tagged(3, true).await.unwrap();
5697        forwarding
5698            .begin_module_drain("holdouts", RouteCloseReason::Restart)
5699            .unwrap();
5700
5701        let holdouts = forwarding.endpoint_drain_holdouts(endpoint).unwrap();
5702        assert_eq!(
5703            holdouts,
5704            DrainHoldouts {
5705                requests: 2,
5706                routes: 1,
5707                total_routes: 2,
5708                top_connections: vec![(client.get(), 2)],
5709                // The held requests by the module's channel and corr, ascending,
5710                // without the excluded subscription (corr 3).
5711                held: vec![(holding.module_channel, 2), (holding.module_channel, 7)],
5712            }
5713        );
5714    }
5715
5716    #[test]
5717    fn endpoint_routes_keep_goodbye_targets_and_mark_draining_routes() {
5718        let (forwarding, module_connection, endpoint, client, sink, _client_rx) =
5719            route_fixture("census");
5720        let pending = begin_test_route(&forwarding, client, sink, 1, "census");
5721        forwarding
5722            .complete_pending_relay(
5723                module_connection,
5724                pending.corr,
5725                RouteBindRelayOutcome::Accepted,
5726            )
5727            .unwrap();
5728
5729        let routes = forwarding.endpoint_routes(endpoint).unwrap();
5730        assert_eq!(routes.len(), 1);
5731        assert!(matches!(routes[0].principal, Principal::Direct));
5732        assert_eq!(routes[0].goodbye_target.connection_id, client);
5733        assert_eq!(routes[0].goodbye_target.channel, pending.client_channel);
5734        assert_eq!(routes[0].goodbye_target.epoch, pending.client_epoch);
5735        assert!(!routes[0].draining);
5736
5737        forwarding
5738            .begin_module_drain("census", RouteCloseReason::Restart)
5739            .unwrap();
5740        let draining_routes = forwarding.endpoint_routes(endpoint).unwrap();
5741        assert_eq!(draining_routes.len(), 1);
5742        assert!(draining_routes[0].draining);
5743    }
5744
5745    #[test]
5746    fn aborted_reservation_consumes_both_epochs_and_reuse_advances_them() {
5747        let (forwarding, _, endpoint, client, sink, _client_rx) = route_fixture("epoch-abort");
5748        let first = begin_test_route(&forwarding, client, sink.clone(), 1, "epoch-abort");
5749        assert_eq!((first.client_epoch, first.module_epoch), (1, 1));
5750        forwarding
5751            .abort_pending_relay(
5752                first.endpoint,
5753                first.corr,
5754                RouteBindRelayOutcome::ModuleGone("abort".into()),
5755            )
5756            .unwrap();
5757        forwarding.inject_client_slot_epoch(client, first.client_channel, first.client_epoch);
5758        forwarding.inject_module_slot_epoch(endpoint, first.module_channel, first.module_epoch);
5759
5760        let second = begin_test_route(&forwarding, client, sink, 2, "epoch-abort");
5761        assert_eq!(second.client_channel, first.client_channel);
5762        assert_eq!(second.module_channel, first.module_channel);
5763        assert_eq!((second.client_epoch, second.module_epoch), (2, 2));
5764    }
5765
5766    #[test]
5767    fn stale_release_cannot_remove_reused_successor_and_status_is_epoch_fenced() {
5768        let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
5769            route_fixture("epoch-release");
5770        let first = begin_test_route(&forwarding, client, sink.clone(), 10, "epoch-release");
5771        forwarding
5772            .complete_pending_relay(
5773                module_connection,
5774                first.corr,
5775                RouteBindRelayOutcome::Accepted,
5776            )
5777            .unwrap();
5778        assert_eq!(client_rx.try_recv().unwrap().header.corr, 10);
5779        assert!(matches!(
5780            forwarding
5781                .release_client_route(client, first.client_channel, first.client_epoch)
5782                .unwrap(),
5783            RouteRelease::Removed(_)
5784        ));
5785        forwarding.inject_client_slot_epoch(client, first.client_channel, first.client_epoch);
5786        forwarding.inject_module_slot_epoch(endpoint, first.module_channel, first.module_epoch);
5787
5788        let second = begin_test_route(&forwarding, client, sink, 11, "epoch-release");
5789        forwarding
5790            .complete_pending_relay(
5791                module_connection,
5792                second.corr,
5793                RouteBindRelayOutcome::Accepted,
5794            )
5795            .unwrap();
5796        assert_eq!(client_rx.try_recv().unwrap().header.corr, 11);
5797        assert!(matches!(
5798            forwarding
5799                .release_client_route(client, second.client_channel, first.client_epoch)
5800                .unwrap(),
5801            RouteRelease::Stale
5802        ));
5803        assert!(!forwarding
5804            .cache_status(
5805                endpoint,
5806                second.module_channel,
5807                first.module_epoch,
5808                "stale".into(),
5809            )
5810            .unwrap());
5811        assert!(forwarding
5812            .cache_status(
5813                endpoint,
5814                second.module_channel,
5815                second.module_epoch,
5816                "current".into(),
5817            )
5818            .unwrap());
5819        match forwarding
5820            .route_poll_snapshot(client, second.client_channel, second.client_epoch)
5821            .unwrap()
5822        {
5823            RoutePollSnapshot::Bound { status, .. } => {
5824                assert_eq!(status.as_deref(), Some("current"));
5825            }
5826            RoutePollSnapshot::Absent => panic!("successor binding was removed"),
5827        }
5828        let counters = forwarding.counters().snapshot();
5829        assert_eq!(counters["route_released_epoch_fenced"], 1);
5830        assert_eq!(counters["route_release_stale_skipped"], 1);
5831    }
5832
5833    #[test]
5834    fn max_epoch_reservation_retires_only_that_slot() {
5835        let (forwarding, _, endpoint, client, sink, _client_rx) = route_fixture("epoch-max");
5836        forwarding.inject_client_slot_epoch(client, 7, u32::MAX - 1);
5837        forwarding.inject_module_slot_epoch(endpoint, 9, u32::MAX - 1);
5838        let final_use = begin_test_route(&forwarding, client, sink.clone(), 20, "epoch-max");
5839        assert_eq!(
5840            (final_use.client_channel, final_use.client_epoch),
5841            (7, u32::MAX)
5842        );
5843        assert_eq!(
5844            (final_use.module_channel, final_use.module_epoch),
5845            (9, u32::MAX)
5846        );
5847        forwarding
5848            .abort_pending_relay(
5849                endpoint,
5850                final_use.corr,
5851                RouteBindRelayOutcome::ModuleGone("abort".into()),
5852            )
5853            .unwrap();
5854        forwarding.inject_client_slot_epoch(client, 7, u32::MAX);
5855        forwarding.inject_module_slot_epoch(endpoint, 9, u32::MAX);
5856        let next = begin_test_route(&forwarding, client, sink, 21, "epoch-max");
5857        assert_ne!(next.client_channel, 7);
5858        assert_ne!(next.module_channel, 9);
5859        assert_eq!((next.client_epoch, next.module_epoch), (1, 1));
5860    }
5861
5862    #[test]
5863    fn bind_and_module_control_share_monotonic_corr_and_deadline_arbitration() {
5864        let (forwarding, module_connection, endpoint, client, sink, _client_rx) =
5865            route_fixture("corr-shared");
5866        let bind = begin_test_route(&forwarding, client, sink, 30, "corr-shared");
5867        assert_eq!(bind.corr, 1);
5868        forwarding
5869            .abort_pending_relay(
5870                endpoint,
5871                bind.corr,
5872                RouteBindRelayOutcome::ModuleGone("abort".into()),
5873            )
5874            .unwrap();
5875        let rpc = forwarding
5876            .begin_module_control_rpc_for(
5877                "corr-shared",
5878                "health.check",
5879                Instant::now() - Duration::from_millis(1),
5880            )
5881            .unwrap();
5882        assert_eq!(rpc.corr, 2);
5883        assert_eq!(
5884            forwarding
5885                .complete_module_control_rpc(
5886                    module_connection,
5887                    rpc.corr,
5888                    Some("health.check"),
5889                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
5890                        status: subc_protocol::session::HealthStatus::Ok,
5891                        detail: None,
5892                        metrics: None,
5893                    }),
5894                )
5895                .unwrap(),
5896            ModuleControlRpcCompletion::Settled
5897        );
5898        assert!(matches!(
5899            rpc.receiver.blocking_recv().unwrap(),
5900            ModuleControlRpcOutcome::DeadlineElapsed
5901        ));
5902    }
5903
5904    #[tokio::test(start_paused = true)]
5905    async fn health_probe_tombstone_ttl_removes_an_endpoint_that_stops_probing() {
5906        let (forwarding, _, endpoint, _, _, _) = route_fixture("tombstone-ttl");
5907        let probe_started_at = Instant::now();
5908        let rpc = forwarding
5909            .begin_health_probe_rpc_for(
5910                "tombstone-ttl",
5911                "health.check",
5912                probe_started_at,
5913                probe_started_at + Duration::from_secs(5),
5914            )
5915            .unwrap();
5916        assert!(forwarding
5917            .tombstone_health_probe_rpc(endpoint, rpc.corr)
5918            .unwrap());
5919        assert_eq!(forwarding.health_probe_tombstone_count().unwrap(), 1);
5920
5921        tokio::time::advance(HEALTH_PROBE_TOMBSTONE_TTL).await;
5922        tokio::task::yield_now().await;
5923
5924        assert_eq!(forwarding.health_probe_tombstone_count().unwrap(), 0);
5925    }
5926
5927    #[test]
5928    fn correlation_exhaustion_emits_max_once_then_closes_endpoint() {
5929        let (forwarding, _, endpoint, _, _, _) = route_fixture("corr-max");
5930        let mut close = forwarding.register_connection_close(endpoint.connection_id);
5931        forwarding.inject_control_corr(endpoint, u64::MAX);
5932        let final_rpc = forwarding
5933            .begin_module_control_rpc_for(
5934                "corr-max",
5935                "health.check",
5936                Instant::now() + Duration::from_secs(1),
5937            )
5938            .unwrap();
5939        assert_eq!(final_rpc.corr, u64::MAX);
5940        forwarding
5941            .cancel_module_control_rpc(endpoint, final_rpc.corr)
5942            .unwrap();
5943        assert!(matches!(
5944            forwarding.begin_module_control_rpc_for(
5945                "corr-max",
5946                "health.check",
5947                Instant::now() + Duration::from_secs(1),
5948            ),
5949            Err(ForwardingError::RelayCorrelationExhausted)
5950        ));
5951        assert!(close.try_recv().is_ok());
5952    }
5953
5954    #[test]
5955    fn publication_epoch_controls_delivery_failure_escalation() {
5956        fn setup_successor(
5957            commit_successor: Option<bool>,
5958        ) -> (ForwardingTable, ConnectionId, u16, u32) {
5959            let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
5960                route_fixture("escalation");
5961            let first = begin_test_route(&forwarding, client, sink.clone(), 40, "escalation");
5962            forwarding
5963                .complete_pending_relay(
5964                    module_connection,
5965                    first.corr,
5966                    RouteBindRelayOutcome::Accepted,
5967                )
5968                .unwrap();
5969            client_rx.try_recv().unwrap();
5970            assert!(matches!(
5971                forwarding
5972                    .release_client_route(client, first.client_channel, first.client_epoch)
5973                    .unwrap(),
5974                RouteRelease::Removed(_)
5975            ));
5976            if let Some(commit_successor) = commit_successor {
5977                forwarding.inject_client_slot_epoch(
5978                    client,
5979                    first.client_channel,
5980                    first.client_epoch,
5981                );
5982                forwarding.inject_module_slot_epoch(
5983                    endpoint,
5984                    first.module_channel,
5985                    first.module_epoch,
5986                );
5987                let successor = begin_test_route(&forwarding, client, sink, 41, "escalation");
5988                if commit_successor {
5989                    forwarding
5990                        .complete_pending_relay(
5991                            module_connection,
5992                            successor.corr,
5993                            RouteBindRelayOutcome::Accepted,
5994                        )
5995                        .unwrap();
5996                    client_rx.try_recv().unwrap();
5997                } else {
5998                    forwarding
5999                        .abort_pending_relay(
6000                            endpoint,
6001                            successor.corr,
6002                            RouteBindRelayOutcome::ModuleGone("abort".into()),
6003                        )
6004                        .unwrap();
6005                }
6006            }
6007            (forwarding, client, first.client_channel, first.client_epoch)
6008        }
6009
6010        let probe_sink = FrameSink::new(mpsc::channel(1).0);
6011        let (no_successor, client, channel, epoch) = setup_successor(None);
6012        let mut close = no_successor.register_connection_close(client);
6013        assert!(no_successor
6014            .escalate_client_delivery_failure(
6015                client,
6016                channel,
6017                epoch,
6018                CloseReason::new("delivery", "failed"),
6019                UndeliveredFrame {
6020                    module_id: None,
6021                    sink: &probe_sink,
6022                },
6023            )
6024            .unwrap());
6025        assert!(close.try_recv().is_ok());
6026
6027        let (aborted, client, channel, epoch) = setup_successor(Some(false));
6028        let mut close = aborted.register_connection_close(client);
6029        assert!(aborted
6030            .escalate_client_delivery_failure(
6031                client,
6032                channel,
6033                epoch,
6034                CloseReason::new("delivery", "failed"),
6035                UndeliveredFrame {
6036                    module_id: None,
6037                    sink: &probe_sink,
6038                },
6039            )
6040            .unwrap());
6041        assert!(close.try_recv().is_ok());
6042
6043        let (published, client, channel, epoch) = setup_successor(Some(true));
6044        let mut close = published.register_connection_close(client);
6045        assert!(!published
6046            .escalate_client_delivery_failure(
6047                client,
6048                channel,
6049                epoch,
6050                CloseReason::new("delivery", "stale failure"),
6051                UndeliveredFrame {
6052                    module_id: None,
6053                    sink: &probe_sink,
6054                },
6055            )
6056            .unwrap());
6057        assert!(close.try_recv().is_err());
6058    }
6059
6060    #[test]
6061    fn route_concentration_separates_client_count_from_routes_per_client() {
6062        // The distinction this asserts is the one a bare connection count cannot
6063        // make: two connections holding one route each and one connection
6064        // holding two are the same total, and have opposite causes.
6065        let (forwarding, module_connection, _, client, sink, _client_rx) =
6066            route_fixture("concentration");
6067        assert_eq!(forwarding.client_route_concentration().unwrap(), (0, 0));
6068
6069        for corr in [70_u64, 71] {
6070            let pending =
6071                begin_test_route(&forwarding, client, sink.clone(), corr, "concentration");
6072            forwarding
6073                .complete_pending_relay(
6074                    module_connection,
6075                    pending.corr,
6076                    RouteBindRelayOutcome::Accepted,
6077                )
6078                .unwrap();
6079        }
6080
6081        // One connection, two routes — not two connections with a route each.
6082        assert_eq!(forwarding.active_binding_count().unwrap(), 2);
6083        assert_eq!(forwarding.client_route_concentration().unwrap(), (1, 2));
6084    }
6085
6086    #[test]
6087    fn cleanup_and_accepted_resolution_have_one_lock_winner() {
6088        let (forwarding, module_connection, _, client, sink, mut client_rx) =
6089            route_fixture("cleanup-race");
6090        let pending = begin_test_route(&forwarding, client, sink, 45, "cleanup-race");
6091        forwarding
6092            .mark_route_bind_relay_enqueued(pending.endpoint, pending.corr)
6093            .unwrap();
6094        let released = forwarding.cleanup_connection(client).unwrap();
6095        assert_eq!(released.len(), 1);
6096        let completion = forwarding
6097            .complete_pending_relay(
6098                module_connection,
6099                pending.corr,
6100                RouteBindRelayOutcome::Accepted,
6101            )
6102            .unwrap();
6103        assert!(!completion.settled);
6104        assert!(client_rx.try_recv().is_err());
6105        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6106
6107        let (forwarding, module_connection, _, client, sink, mut client_rx) =
6108            route_fixture("accepted-race");
6109        let pending = begin_test_route(&forwarding, client, sink, 46, "accepted-race");
6110        forwarding
6111            .complete_pending_relay(
6112                module_connection,
6113                pending.corr,
6114                RouteBindRelayOutcome::Accepted,
6115            )
6116            .unwrap();
6117        assert_eq!(client_rx.try_recv().unwrap().header.corr, 46);
6118        let released = forwarding.cleanup_connection(client).unwrap();
6119        assert_eq!(released.len(), 1);
6120        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6121    }
6122
6123    #[test]
6124    fn drain_marks_block_reservation_commit_and_live_request_admission_until_phase_two() {
6125        let (forwarding, module_connection, _, client, sink, mut client_rx) =
6126            route_fixture("drain-gap");
6127        let live = begin_test_route(&forwarding, client, sink.clone(), 47, "drain-gap");
6128        forwarding
6129            .complete_pending_relay(
6130                module_connection,
6131                live.corr,
6132                RouteBindRelayOutcome::Accepted,
6133            )
6134            .unwrap();
6135        client_rx.try_recv().unwrap();
6136        let binding = match forwarding
6137            .lookup_data_route(client, live.client_channel, live.client_epoch)
6138            .unwrap()
6139        {
6140            DataRoute::Client(DataRouteState::Bound(binding)) => binding,
6141            other => panic!("expected live route, got {other:?}"),
6142        };
6143
6144        let pending = begin_test_route(&forwarding, client, sink.clone(), 48, "drain-gap");
6145        forwarding
6146            .mark_route_bind_relay_enqueued(pending.endpoint, pending.corr)
6147            .unwrap();
6148        let control_rpc = forwarding
6149            .begin_module_control_rpc_for(
6150                "drain-gap",
6151                "health.check",
6152                Instant::now() + Duration::from_secs(1),
6153            )
6154            .unwrap();
6155        let target = forwarding
6156            .begin_module_drain("drain-gap", RouteCloseReason::Reload)
6157            .unwrap()
6158            .unwrap();
6159        assert!(matches!(
6160            control_rpc.receiver.blocking_recv().unwrap(),
6161            ModuleControlRpcOutcome::ModuleGone(_)
6162        ));
6163        assert_eq!(target.abandoned_bindings.len(), 1);
6164        assert!(binding.flow.sem.is_closed());
6165        assert!(
6166            !forwarding
6167                .complete_pending_relay(
6168                    module_connection,
6169                    pending.corr,
6170                    RouteBindRelayOutcome::Accepted,
6171                )
6172                .unwrap()
6173                .settled
6174        );
6175        assert!(matches!(
6176            forwarding.begin_route_bind_relay_for_test(client, sink, 49, "drain-gap"),
6177            Err(ForwardingError::ModuleReloading { .. })
6178        ));
6179        let released = forwarding
6180            .release_module_endpoint_routes(target.endpoint)
6181            .unwrap();
6182        assert_eq!(released.len(), 1);
6183        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6184    }
6185
6186    /// A client can be marked closing while its egress is still open: the daemon
6187    /// asks a connection to close (here through the production path, a module
6188    /// frame that its egress refused) and the connection loop tears down a moment
6189    /// later. A route.bind ack that lands inside that window is answered on the
6190    /// MODULE connection's frame handler, so resolving it must not produce an
6191    /// error -- an error there ends the module connection, and that connection
6192    /// carries every other client's routes to the module.
6193    #[test]
6194    fn accepted_bind_for_a_closing_client_releases_the_route_instead_of_failing_the_module() {
6195        let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
6196            route_fixture("closing-client");
6197
6198        // A published route on this client: escalate_client_delivery_failure only
6199        // marks a connection closing for a route it has already published.
6200        let live = begin_test_route(&forwarding, client, sink.clone(), 60, "closing-client");
6201        forwarding
6202            .complete_pending_relay(
6203                module_connection,
6204                live.corr,
6205                RouteBindRelayOutcome::Accepted,
6206            )
6207            .unwrap();
6208        client_rx.try_recv().unwrap();
6209
6210        // A second route.open from the same client, relayed and awaiting its ack.
6211        let pending = begin_test_route(&forwarding, client, sink.clone(), 61, "closing-client");
6212        forwarding
6213            .mark_route_bind_relay_enqueued(pending.endpoint, pending.corr)
6214            .unwrap();
6215
6216        // The window: closing, but the sink is still open.
6217        assert!(forwarding
6218            .escalate_client_delivery_failure(
6219                client,
6220                live.client_channel,
6221                live.client_epoch,
6222                CloseReason::new(
6223                    "module_to_client_delivery_failed",
6224                    "client egress refused a module frame",
6225                ),
6226                UndeliveredFrame {
6227                    module_id: None,
6228                    sink: &sink,
6229                },
6230            )
6231            .unwrap());
6232        assert!(!sink.is_closed());
6233
6234        let completion = forwarding
6235            .complete_pending_relay(
6236                module_connection,
6237                pending.corr,
6238                RouteBindRelayOutcome::Accepted,
6239            )
6240            .expect("a closing client must not turn a module's ack into an error");
6241
6242        assert!(completion.settled);
6243        let abandoned = completion
6244            .abandoned
6245            .expect("the module must be told to drop the binding it just created");
6246        assert_eq!(abandoned.connection_id, module_connection);
6247        assert_eq!(abandoned.channel, pending.module_channel);
6248        assert_eq!(abandoned.epoch, pending.module_epoch);
6249        assert!(matches!(abandoned.kind, GoodbyeTargetKind::Module));
6250        assert!(matches!(
6251            pending.receiver.blocking_recv().unwrap(),
6252            RouteBindRelayOutcome::ModuleGone(_)
6253        ));
6254        // No route was published to a client that is on its way out, and the
6255        // reserved handle pair went back.
6256        assert!(client_rx.try_recv().is_err());
6257        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
6258
6259        // The module endpoint is untouched: still live, and still able to take a
6260        // route from another client.
6261        assert!(forwarding
6262            .has_live_module_connection("closing-client")
6263            .unwrap());
6264        let cotenant = ConnectionId::new(201);
6265        let (cotenant_tx, mut cotenant_rx) = mpsc::channel(8);
6266        let cotenant_route = begin_test_route(
6267            &forwarding,
6268            cotenant,
6269            FrameSink::new(cotenant_tx),
6270            62,
6271            "closing-client",
6272        );
6273        assert_eq!(cotenant_route.endpoint, endpoint);
6274        forwarding
6275            .complete_pending_relay(
6276                module_connection,
6277                cotenant_route.corr,
6278                RouteBindRelayOutcome::Accepted,
6279            )
6280            .unwrap();
6281        assert_eq!(cotenant_rx.try_recv().unwrap().header.corr, 62);
6282        assert_eq!(forwarding.active_binding_count().unwrap(), 2);
6283    }
6284
6285    #[test]
6286    fn pending_route_permit_is_released_on_rejection_and_abort() {
6287        let forwarding = ForwardingTable::default();
6288        let module_connection = ConnectionId::new(300);
6289        let client = ConnectionId::new(301);
6290        let (module_tx, _module_rx) = mpsc::channel(1);
6291        let endpoint = forwarding
6292            .register_module_connection(
6293                module_connection,
6294                "permit".into(),
6295                2,
6296                Concurrency::ModuleManaged,
6297                FrameSink::new(module_tx),
6298            )
6299            .unwrap();
6300        let (client_tx, mut client_rx) = mpsc::channel(1);
6301        let sink = FrameSink::new(client_tx);
6302        let rejected = begin_test_route(&forwarding, client, sink.clone(), 50, "permit");
6303        assert!(sink.try_send(test_ping(999)).is_err());
6304        forwarding
6305            .complete_pending_relay(
6306                module_connection,
6307                rejected.corr,
6308                RouteBindRelayOutcome::Rejected(ErrorBody {
6309                    code: "no".into(),
6310                    message: "rejected".into(),
6311                    detail: None,
6312                }),
6313            )
6314            .unwrap();
6315        sink.try_send(test_ping(1000)).unwrap();
6316        assert_eq!(client_rx.try_recv().unwrap().header.corr, 1000);
6317
6318        let aborted = begin_test_route(&forwarding, client, sink.clone(), 51, "permit");
6319        assert!(sink.try_send(test_ping(1001)).is_err());
6320        forwarding
6321            .abort_pending_relay(
6322                endpoint,
6323                aborted.corr,
6324                RouteBindRelayOutcome::ModuleGone("abort".into()),
6325            )
6326            .unwrap();
6327        sink.try_send(test_ping(1002)).unwrap();
6328        assert_eq!(client_rx.try_recv().unwrap().header.corr, 1002);
6329
6330        let receiver_closed = begin_test_route(&forwarding, client, sink, 52, "permit");
6331        forwarding
6332            .mark_route_bind_relay_enqueued(endpoint, receiver_closed.corr)
6333            .unwrap();
6334        drop(client_rx);
6335        let completion = forwarding
6336            .complete_pending_relay(
6337                module_connection,
6338                receiver_closed.corr,
6339                RouteBindRelayOutcome::Accepted,
6340            )
6341            .unwrap();
6342        assert!(completion.abandoned.is_some());
6343        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6344    }
6345
6346    /// Every connection teardown passes through `cleanup_connection`, and
6347    /// connection ids come from a monotonic counter that never hands an id out
6348    /// twice. If the closing mark survives teardown, the set grows by one entry
6349    /// per connection for the life of the daemon -- the self-watchdog alone
6350    /// reconnects once a minute.
6351    #[test]
6352    fn cleaned_up_connections_do_not_stay_in_the_closing_set() {
6353        let (forwarding, module_connection, _endpoint, _fixture_client, _sink, _rx) =
6354            route_fixture("closing-set-leak");
6355
6356        const CONNECTIONS: u64 = 32;
6357        for index in 0..CONNECTIONS {
6358            let client = ConnectionId::new(1000 + index);
6359            let (client_tx, _client_rx) = mpsc::channel(8);
6360            let route = begin_test_route(
6361                &forwarding,
6362                client,
6363                FrameSink::new(client_tx),
6364                index + 1,
6365                "closing-set-leak",
6366            );
6367            forwarding
6368                .complete_pending_relay(
6369                    module_connection,
6370                    route.corr,
6371                    RouteBindRelayOutcome::Accepted,
6372                )
6373                .unwrap();
6374            forwarding.cleanup_connection(client).unwrap();
6375        }
6376        forwarding.cleanup_connection(module_connection).unwrap();
6377
6378        assert_eq!(forwarding.closing_connection_count().unwrap(), 0);
6379    }
6380
6381    /// The closing mark exists to refuse new work for a connection that is on
6382    /// its way out but whose teardown has not run yet: the daemon asks the
6383    /// connection loop to end, and only when the loop reacts does
6384    /// `cleanup_connection` strip the connection's state. Inside that window an
6385    /// operation for the dying connection must still be refused; only after
6386    /// cleanup completes may the mark go.
6387    #[test]
6388    fn closing_connection_is_refused_new_work_until_cleanup_completes() {
6389        let (forwarding, module_connection, _endpoint, client, sink, mut client_rx) =
6390            route_fixture("closing-gate");
6391
6392        // A published route: escalate_client_delivery_failure only marks a
6393        // connection closing for a route it has already published.
6394        let live = begin_test_route(&forwarding, client, sink.clone(), 80, "closing-gate");
6395        forwarding
6396            .complete_pending_relay(
6397                module_connection,
6398                live.corr,
6399                RouteBindRelayOutcome::Accepted,
6400            )
6401            .unwrap();
6402        client_rx.try_recv().unwrap();
6403
6404        // Mark the connection closing through the production path without
6405        // running teardown, pinning the window open.
6406        assert!(forwarding
6407            .escalate_client_delivery_failure(
6408                client,
6409                live.client_channel,
6410                live.client_epoch,
6411                CloseReason::new(
6412                    "module_to_client_delivery_failed",
6413                    "client egress refused a module frame",
6414                ),
6415                UndeliveredFrame {
6416                    module_id: None,
6417                    sink: &sink,
6418                },
6419            )
6420            .unwrap());
6421        assert_eq!(forwarding.closing_connection_count().unwrap(), 1);
6422
6423        // A late route.open for the closing client is refused ...
6424        assert!(matches!(
6425            forwarding.begin_route_bind_relay_for_test(client, sink, 81, "closing-gate"),
6426            Err(ForwardingError::ConnectionClosing { connection_id })
6427                if connection_id == client
6428        ));
6429        // ... and so is a late attempt to register the connection as a module.
6430        let (late_tx, _late_rx) = mpsc::channel(1);
6431        assert!(matches!(
6432            forwarding.register_module_connection(
6433                client,
6434                "late-module".into(),
6435                2,
6436                Concurrency::ModuleManaged,
6437                FrameSink::new(late_tx),
6438            ),
6439            Err(ForwardingError::ConnectionClosing { connection_id })
6440                if connection_id == client
6441        ));
6442
6443        // Teardown is the point that lifts the mark: it has just removed every
6444        // per-connection entry under the same lock, so the gate has nothing
6445        // left to protect for this id.
6446        forwarding.cleanup_connection(client).unwrap();
6447        assert_eq!(forwarding.closing_connection_count().unwrap(), 0);
6448    }
6449
6450    mod audit_measurements {
6451        use super::*;
6452        include!("forwarding_audit_measurements.rs");
6453    }
6454
6455    mod waiting_requests {
6456        use super::*;
6457        include!("forwarding_waiting_requests_tests.rs");
6458    }
6459}
6460
6461/// Blue/green swap slots: a candidate registered beside the active endpoint,
6462/// promoted by `cutover_candidate`, with the old incumbent drained by endpoint.
6463#[cfg(test)]
6464mod swap_slot_tests {
6465    use std::time::Duration;
6466
6467    use super::*;
6468    use tokio::sync::mpsc;
6469
6470    const MODULE_ID: &str = "swapped";
6471
6472    struct SwapFixture {
6473        forwarding: ForwardingTable,
6474        incumbent_connection: ConnectionId,
6475        incumbent: ModuleEndpointId,
6476        candidate_connection: ConnectionId,
6477        candidate: ModuleEndpointId,
6478        _module_rxs: Vec<mpsc::Receiver<crate::router::OutboundFrame>>,
6479    }
6480
6481    fn swap_fixture() -> SwapFixture {
6482        let forwarding = ForwardingTable::default();
6483        let incumbent_connection = ConnectionId::new(100);
6484        let candidate_connection = ConnectionId::new(110);
6485        let (incumbent_tx, incumbent_rx) = mpsc::channel(8);
6486        let incumbent = forwarding
6487            .register_module_connection(
6488                incumbent_connection,
6489                MODULE_ID.to_string(),
6490                2,
6491                Concurrency::ModuleManaged,
6492                FrameSink::new(incumbent_tx),
6493            )
6494            .unwrap();
6495        let (candidate_tx, candidate_rx) = mpsc::channel(8);
6496        let candidate = forwarding
6497            .register_candidate_module_connection(
6498                candidate_connection,
6499                MODULE_ID.to_string(),
6500                2,
6501                Concurrency::ModuleManaged,
6502                FrameSink::new(candidate_tx),
6503            )
6504            .unwrap();
6505        SwapFixture {
6506            forwarding,
6507            incumbent_connection,
6508            incumbent,
6509            candidate_connection,
6510            candidate,
6511            _module_rxs: vec![incumbent_rx, candidate_rx],
6512        }
6513    }
6514
6515    fn client(
6516        raw: u64,
6517    ) -> (
6518        ConnectionId,
6519        FrameSink,
6520        mpsc::Receiver<crate::router::OutboundFrame>,
6521    ) {
6522        let (tx, rx) = mpsc::channel(8);
6523        (ConnectionId::new(raw), FrameSink::new(tx), rx)
6524    }
6525
6526    fn committed_endpoints(forwarding: &ForwardingTable) -> Vec<ModuleEndpointId> {
6527        forwarding
6528            .read_inner()
6529            .unwrap()
6530            .client_to_module
6531            .values()
6532            .map(|route| route.module_endpoint)
6533            .collect()
6534    }
6535
6536    #[test]
6537    fn candidate_is_unroutable_until_cutover_and_by_id_lookups_resolve_the_active_slot() {
6538        let fixture = swap_fixture();
6539        let forwarding = &fixture.forwarding;
6540        assert_ne!(fixture.incumbent, fixture.candidate);
6541
6542        // Every by-id consumer still resolves the incumbent.
6543        assert!(forwarding.has_live_module_connection(MODULE_ID).unwrap());
6544        assert!(!forwarding.module_is_draining(MODULE_ID).unwrap());
6545        let (client_connection, client_sink, _client_rx) = client(200);
6546        let pending = forwarding
6547            .begin_route_bind_relay_for_test(client_connection, client_sink, 1, MODULE_ID)
6548            .unwrap();
6549        assert_eq!(pending.endpoint, fixture.incumbent);
6550        let rpc = forwarding
6551            .begin_module_control_rpc_for(
6552                MODULE_ID,
6553                "health.check",
6554                Instant::now() + Duration::from_secs(1),
6555            )
6556            .unwrap();
6557        assert_eq!(rpc.endpoint, fixture.incumbent);
6558        let census = forwarding.route_census(Some(MODULE_ID)).unwrap();
6559        assert_eq!(census.len(), 1, "the census lists one endpoint per id");
6560
6561        // Connection-keyed lookups see the candidate, so its own frames resolve.
6562        assert_eq!(
6563            forwarding
6564                .module_endpoint_for_connection(fixture.candidate_connection)
6565                .unwrap(),
6566            Some(fixture.candidate)
6567        );
6568        assert_eq!(
6569            forwarding
6570                .module_id_for_connection(fixture.candidate_connection)
6571                .unwrap()
6572                .as_deref(),
6573            Some(MODULE_ID)
6574        );
6575
6576        // One candidate per id.
6577        let (other_tx, _other_rx) = mpsc::channel(1);
6578        assert_eq!(
6579            forwarding.register_candidate_module_connection(
6580                ConnectionId::new(120),
6581                MODULE_ID.to_string(),
6582                2,
6583                Concurrency::ModuleManaged,
6584                FrameSink::new(other_tx),
6585            ),
6586            Err(ForwardingError::CandidateSlotOccupied {
6587                module_id: MODULE_ID.to_string()
6588            })
6589        );
6590    }
6591
6592    /// The cutover linearization point. A relay reserved on the incumbent before
6593    /// cutover must never become a route on the incumbent, and every relay
6594    /// reserved after it must land on the promoted candidate.
6595    #[test]
6596    fn relay_reserved_before_cutover_never_commits_and_later_relays_land_on_the_candidate() {
6597        let fixture = swap_fixture();
6598        let forwarding = &fixture.forwarding;
6599        let (early_client, early_sink, _early_rx) = client(200);
6600        let mut early = forwarding
6601            .begin_route_bind_relay_for_test(early_client, early_sink, 1, MODULE_ID)
6602            .unwrap();
6603        assert_eq!(early.endpoint, fixture.incumbent);
6604        assert_eq!(
6605            forwarding
6606                .mark_route_bind_relay_enqueued(early.endpoint, early.corr)
6607                .unwrap(),
6608            RouteBindRelayMark::Marked
6609        );
6610
6611        let cutover = forwarding.cutover_candidate(MODULE_ID).unwrap().unwrap();
6612        assert_eq!(
6613            cutover,
6614            ForwardingCutover {
6615                promoted: fixture.candidate,
6616                incumbent: Some(fixture.incumbent),
6617            }
6618        );
6619
6620        // A route.open reserved after cutover goes to the promoted candidate.
6621        let (late_client, late_sink, _late_rx) = client(201);
6622        let late = forwarding
6623            .begin_route_bind_relay_for_test(late_client, late_sink, 2, MODULE_ID)
6624            .unwrap();
6625        assert_eq!(
6626            late.endpoint, fixture.candidate,
6627            "a route.open after cutover was reserved on the incumbent"
6628        );
6629
6630        // The incumbent acks the early relay after cutover.
6631        let completion = forwarding
6632            .complete_pending_relay(
6633                fixture.incumbent_connection,
6634                early.corr,
6635                RouteBindRelayOutcome::Accepted,
6636            )
6637            .expect("a superseded endpoint's ack is not an error on its connection");
6638        assert!(completion.settled);
6639        assert!(
6640            !committed_endpoints(forwarding).contains(&fixture.incumbent),
6641            "a relay reserved before cutover committed a route on the incumbent"
6642        );
6643        let goodbye = completion
6644            .abandoned
6645            .expect("the incumbent is told to drop the binding it just created");
6646        assert_eq!(goodbye.connection_id, fixture.incumbent_connection);
6647        assert_eq!(goodbye.channel, early.module_channel);
6648        assert_eq!(goodbye.epoch, early.module_epoch);
6649        assert_eq!(goodbye.kind, GoodbyeTargetKind::Module);
6650        match early.receiver.try_recv() {
6651            Ok(RouteBindRelayOutcome::DaemonRejected(body)) => {
6652                assert_eq!(body.code, "module_reloading")
6653            }
6654            other => panic!("expected a retryable module_reloading answer, got {other:?}"),
6655        }
6656        assert!(matches!(
6657            forwarding
6658                .lookup_data_route(early_client, early.client_channel, early.client_epoch)
6659                .unwrap(),
6660            DataRoute::Client(DataRouteState::Absent)
6661        ));
6662
6663        // The late relay commits on the candidate; only its pair stays reserved
6664        // until then.
6665        assert_eq!(forwarding.reserved_route_count().unwrap(), (1, 1));
6666        forwarding
6667            .complete_pending_relay(
6668                fixture.candidate_connection,
6669                late.corr,
6670                RouteBindRelayOutcome::Accepted,
6671            )
6672            .unwrap();
6673        assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
6674        assert_eq!(committed_endpoints(forwarding), vec![fixture.candidate]);
6675    }
6676
6677    #[test]
6678    fn endpoint_drain_after_cutover_drains_the_incumbent_not_the_promoted_candidate() {
6679        let fixture = swap_fixture();
6680        let forwarding = &fixture.forwarding;
6681        // One bound route and one in-flight relay on the incumbent.
6682        let (bound_client, bound_sink, _bound_rx) = client(200);
6683        let bound = forwarding
6684            .begin_route_bind_relay_for_test(bound_client, bound_sink, 1, MODULE_ID)
6685            .unwrap();
6686        forwarding
6687            .complete_pending_relay(
6688                fixture.incumbent_connection,
6689                bound.corr,
6690                RouteBindRelayOutcome::Accepted,
6691            )
6692            .unwrap();
6693        let (pending_client, pending_sink, _pending_rx) = client(201);
6694        let mut in_flight = forwarding
6695            .begin_route_bind_relay_for_test(pending_client, pending_sink, 2, MODULE_ID)
6696            .unwrap();
6697        forwarding
6698            .mark_route_bind_relay_enqueued(in_flight.endpoint, in_flight.corr)
6699            .unwrap();
6700
6701        let incumbent = forwarding
6702            .cutover_candidate(MODULE_ID)
6703            .unwrap()
6704            .unwrap()
6705            .incumbent
6706            .unwrap();
6707        let target = forwarding
6708            .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
6709            .unwrap()
6710            .expect("the superseded incumbent is still registered");
6711
6712        assert_eq!(target.endpoint, fixture.incumbent);
6713        assert!(forwarding.endpoint_is_draining(fixture.incumbent).unwrap());
6714        assert!(!forwarding.endpoint_is_draining(fixture.candidate).unwrap());
6715        assert!(!forwarding.module_is_draining(MODULE_ID).unwrap());
6716        assert_eq!(target.abandoned_bindings.len(), 1);
6717        assert_eq!(
6718            target.abandoned_bindings[0].channel,
6719            in_flight.module_channel
6720        );
6721        assert!(matches!(
6722            in_flight.receiver.try_recv(),
6723            Ok(RouteBindRelayOutcome::DaemonRejected(body)) if body.code == "module_reloading"
6724        ));
6725        assert_eq!(
6726            forwarding.endpoint_routes(fixture.incumbent).unwrap().len(),
6727            1,
6728            "the incumbent's bound route stays until its drain finishes"
6729        );
6730
6731        let (next_client, next_sink, _next_rx) = client(202);
6732        let next = forwarding
6733            .begin_route_bind_relay_for_test(next_client, next_sink, 3, MODULE_ID)
6734            .expect("the promoted candidate keeps accepting routes");
6735        assert_eq!(next.endpoint, fixture.candidate);
6736    }
6737
6738    /// An endpoint replaced WITHOUT a promotion (a successor registered over it
6739    /// as an ordinary active HELLO) is stale, not superseded, and its ack still
6740    /// fails the acking connection exactly as it did before swap slots existed:
6741    /// `StaleModuleEndpoint`, the reservation indexes already stripped, and the
6742    /// waiting client's sender dropped unanswered.
6743    #[test]
6744    fn stale_endpoint_ack_without_a_promotion_still_fails_as_before() {
6745        let forwarding = ForwardingTable::default();
6746        let first_connection = ConnectionId::new(70);
6747        let (first_tx, _first_rx) = mpsc::channel(8);
6748        forwarding
6749            .register_module_connection(
6750                first_connection,
6751                MODULE_ID.to_string(),
6752                2,
6753                Concurrency::ModuleManaged,
6754                FrameSink::new(first_tx),
6755            )
6756            .unwrap();
6757        let (client_connection, client_sink, _client_rx) = client(200);
6758        let mut pending = forwarding
6759            .begin_route_bind_relay_for_test(client_connection, client_sink, 1, MODULE_ID)
6760            .unwrap();
6761        let (second_tx, _second_rx) = mpsc::channel(8);
6762        forwarding
6763            .register_module_connection(
6764                ConnectionId::new(80),
6765                MODULE_ID.to_string(),
6766                2,
6767                Concurrency::ModuleManaged,
6768                FrameSink::new(second_tx),
6769            )
6770            .unwrap();
6771
6772        assert_eq!(
6773            forwarding
6774                .complete_pending_relay(
6775                    first_connection,
6776                    pending.corr,
6777                    RouteBindRelayOutcome::Accepted
6778                )
6779                .unwrap_err(),
6780            ForwardingError::StaleModuleEndpoint
6781        );
6782        assert!(committed_endpoints(&forwarding).is_empty());
6783        assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
6784        assert!(matches!(
6785            pending.receiver.try_recv(),
6786            Err(oneshot::error::TryRecvError::Closed)
6787        ));
6788    }
6789
6790    #[test]
6791    fn cleanup_releases_candidate_and_superseded_slots_without_touching_the_active_one() {
6792        // A candidate whose connection drops leaves the incumbent routable.
6793        let fixture = swap_fixture();
6794        let forwarding = &fixture.forwarding;
6795        assert!(forwarding
6796            .cleanup_connection(fixture.candidate_connection)
6797            .unwrap()
6798            .is_empty());
6799        assert_eq!(forwarding.cutover_candidate(MODULE_ID).unwrap(), None);
6800        let (client_connection, client_sink, _client_rx) = client(200);
6801        assert_eq!(
6802            forwarding
6803                .begin_route_bind_relay_for_test(client_connection, client_sink, 1, MODULE_ID)
6804                .unwrap()
6805                .endpoint,
6806            fixture.incumbent
6807        );
6808
6809        // After a cutover, the incumbent's teardown releases its own routes and
6810        // leaves the promoted candidate in place.
6811        let fixture = swap_fixture();
6812        let forwarding = &fixture.forwarding;
6813        let (bound_client, bound_sink, _bound_rx) = client(200);
6814        let bound = forwarding
6815            .begin_route_bind_relay_for_test(bound_client, bound_sink, 1, MODULE_ID)
6816            .unwrap();
6817        forwarding
6818            .complete_pending_relay(
6819                fixture.incumbent_connection,
6820                bound.corr,
6821                RouteBindRelayOutcome::Accepted,
6822            )
6823            .unwrap();
6824        forwarding.cutover_candidate(MODULE_ID).unwrap().unwrap();
6825        let released = forwarding
6826            .cleanup_connection(fixture.incumbent_connection)
6827            .unwrap();
6828        assert_eq!(released.len(), 1);
6829        assert_eq!(released[0].connection_id, bound_client);
6830        assert!(forwarding
6831            .read_inner()
6832            .unwrap()
6833            .superseded_endpoints
6834            .is_empty());
6835        assert!(forwarding.has_live_module_connection(MODULE_ID).unwrap());
6836        let (next_client, next_sink, _next_rx) = client(201);
6837        assert_eq!(
6838            forwarding
6839                .begin_route_bind_relay_for_test(next_client, next_sink, 2, MODULE_ID)
6840                .unwrap()
6841                .endpoint,
6842            fixture.candidate
6843        );
6844    }
6845}