Skip to main content

subc_daemon/
forwarding.rs

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