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