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