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