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    /// Attach the stamp chosen for the reserved endpoint's actual registration,
2053    /// before the module can reply and commit the pending route.
2054    pub(crate) fn set_pending_operator_app(
2055        &self,
2056        endpoint: ModuleEndpointId,
2057        corr: u64,
2058        stamp: crate::operator_apps::OperatorAppStamp,
2059    ) -> Result<bool, ForwardingError> {
2060        let mut inner = self.write_inner()?;
2061        let Some(pending) = inner.pending_relays.get_mut(&(endpoint, corr)) else {
2062            return Ok(false);
2063        };
2064        pending.operator_app = Some(stamp);
2065        Ok(true)
2066    }
2067
2068    /// Called by `route.open` right after the route.bind entered the module's
2069    /// egress queue.
2070    ///
2071    /// The module reader runs concurrently with `route.open`, so a fast module
2072    /// can receive the bind, ack it, and have the reader commit the route
2073    /// before this runs. A missing entry therefore does not mean the bind was
2074    /// abandoned: only a removal recorded in `relays_released_before_enqueue`
2075    /// does. Telling the two apart is what stops `route.open` from sending a
2076    /// GOODBYE for a route that was just committed.
2077    pub(crate) fn mark_route_bind_relay_enqueued(
2078        &self,
2079        endpoint: ModuleEndpointId,
2080        corr: u64,
2081    ) -> Result<RouteBindRelayMark, ForwardingError> {
2082        let mut inner = self.write_inner()?;
2083        if let Some(pending) = inner.pending_relays.get_mut(&(endpoint, corr)) {
2084            pending.relay_enqueued = true;
2085            return Ok(RouteBindRelayMark::Marked);
2086        }
2087        if inner
2088            .relays_released_before_enqueue
2089            .remove(&(endpoint, corr))
2090        {
2091            return Ok(RouteBindRelayMark::ReleasedWithoutReply);
2092        }
2093        Ok(RouteBindRelayMark::SettledByReply)
2094    }
2095
2096    pub(crate) fn release_client_route(
2097        &self,
2098        client_connection_id: ConnectionId,
2099        client_channel: u16,
2100        expected_epoch: u32,
2101    ) -> Result<RouteRelease, ForwardingError> {
2102        let mut inner = self.write_inner()?;
2103        let release = release_client_route_locked(
2104            &mut inner,
2105            ClientRouteKey {
2106                connection_id: client_connection_id,
2107                channel: client_channel,
2108            },
2109            expected_epoch,
2110        );
2111        self.record_route_release(&release);
2112        Ok(release)
2113    }
2114
2115    pub(crate) fn release_module_route(
2116        &self,
2117        module_connection_id: ConnectionId,
2118        module_channel: u16,
2119        expected_epoch: u32,
2120    ) -> Result<RouteRelease, ForwardingError> {
2121        let mut inner = self.write_inner()?;
2122        let Some(endpoint) = inner
2123            .endpoint_by_connection
2124            .get(&module_connection_id)
2125            .copied()
2126        else {
2127            return Ok(RouteRelease::Absent);
2128        };
2129        let release = release_module_route_locked(
2130            &mut inner,
2131            ModuleRouteKey {
2132                endpoint,
2133                channel: module_channel,
2134            },
2135            expected_epoch,
2136        );
2137        self.record_route_release(&release);
2138        Ok(release)
2139    }
2140
2141    pub(crate) fn abort_pending_relay(
2142        &self,
2143        endpoint: ModuleEndpointId,
2144        corr: u64,
2145        outcome: RouteBindRelayOutcome,
2146    ) -> Result<Option<GoodbyeTarget>, ForwardingError> {
2147        let mut inner = self.write_inner()?;
2148        let Some(pending) = inner.pending_relays.remove(&(endpoint, corr)) else {
2149            // If another path dropped the relay while `route.open` was still
2150            // sending the bind, and that open is now giving up without marking
2151            // it (its send failed or it was cancelled), forget the record so it
2152            // cannot outlive the open.
2153            inner
2154                .relays_released_before_enqueue
2155                .remove(&(endpoint, corr));
2156            return Ok(None);
2157        };
2158        release_reserved_route_locked(
2159            &mut inner,
2160            pending.reservation.client_key,
2161            pending.reservation.module_key,
2162        );
2163        let target = pending
2164            .relay_enqueued
2165            .then(|| abandoned_route_target(&inner, &pending.reservation));
2166        let _ = pending.sender.send(outcome);
2167        Ok(target.flatten())
2168    }
2169
2170    pub(crate) fn cancel_module_control_rpc(
2171        &self,
2172        endpoint: ModuleEndpointId,
2173        corr: u64,
2174    ) -> Result<(), ForwardingError> {
2175        self.write_inner()?
2176            .pending_control_rpcs
2177            .remove(&(endpoint, corr));
2178        Ok(())
2179    }
2180
2181    pub(crate) fn tombstone_health_probe_rpc(
2182        &self,
2183        endpoint: ModuleEndpointId,
2184        corr: u64,
2185    ) -> Result<bool, ForwardingError> {
2186        let key = (endpoint, corr);
2187        let expires_at = Instant::now() + HEALTH_PROBE_TOMBSTONE_TTL;
2188        {
2189            let mut inner = self.write_inner()?;
2190            let Some(pending) = inner.pending_control_rpcs.remove(&key) else {
2191                return Ok(false);
2192            };
2193            let Some(probe_started_at) = pending.health_probe_started_at else {
2194                inner.pending_control_rpcs.insert(key, pending);
2195                return Ok(false);
2196            };
2197            let module_id = inner
2198                .module_id_by_endpoint
2199                .get(&endpoint)
2200                .cloned()
2201                .unwrap_or_else(|| "unknown".to_string());
2202            inner.health_probe_tombstones.insert(
2203                key,
2204                HealthProbeTombstone {
2205                    expected_op: pending.expected_op,
2206                    module_id,
2207                    probe_started_at,
2208                    expires_at,
2209                },
2210            );
2211        }
2212        self.schedule_health_probe_tombstone_expiration(key, expires_at);
2213        Ok(true)
2214    }
2215
2216    fn schedule_health_probe_tombstone_expiration(
2217        &self,
2218        key: (ModuleEndpointId, u64),
2219        expires_at: Instant,
2220    ) {
2221        let inner = Arc::downgrade(&self.inner);
2222        tokio::spawn(async move {
2223            tokio::time::sleep_until(expires_at).await;
2224            let Some(inner) = inner.upgrade() else {
2225                return;
2226            };
2227            let Ok(mut inner) = inner.write() else {
2228                return;
2229            };
2230            let expired = inner
2231                .health_probe_tombstones
2232                .get(&key)
2233                .is_some_and(|tombstone| tombstone.expires_at <= Instant::now());
2234            if expired {
2235                inner.health_probe_tombstones.remove(&key);
2236            }
2237        });
2238    }
2239
2240    pub(crate) fn complete_pending_relay(
2241        &self,
2242        connection_id: ConnectionId,
2243        corr: u64,
2244        outcome: RouteBindRelayOutcome,
2245    ) -> Result<PendingRelayCompletion, ForwardingError> {
2246        self.complete_pending_relay_fenced(connection_id, corr, outcome, |_| None)
2247    }
2248
2249    /// Settle a route.bind reply. An accepted bind with a capability fence
2250    /// commits only if `fence_refusal` finds nothing wrong with it now.
2251    pub(crate) fn complete_pending_relay_fenced(
2252        &self,
2253        connection_id: ConnectionId,
2254        corr: u64,
2255        outcome: RouteBindRelayOutcome,
2256        fence_refusal: impl FnOnce(&CapabilityFence) -> Option<ErrorBody>,
2257    ) -> Result<PendingRelayCompletion, ForwardingError> {
2258        let mut inner = self.write_inner()?;
2259        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2260            return Ok(PendingRelayCompletion {
2261                settled: false,
2262                abandoned: None,
2263            });
2264        };
2265        let Some(pending) = inner.pending_relays.remove(&(endpoint, corr)) else {
2266            return Ok(PendingRelayCompletion {
2267                settled: false,
2268                abandoned: None,
2269            });
2270        };
2271
2272        if Instant::now() >= pending.deadline {
2273            release_reserved_route_locked(
2274                &mut inner,
2275                pending.reservation.client_key,
2276                pending.reservation.module_key,
2277            );
2278            let abandoned = matches!(outcome, RouteBindRelayOutcome::Accepted)
2279                .then(|| abandoned_route_target(&inner, &pending.reservation))
2280                .flatten();
2281            let _ = pending
2282                .sender
2283                .send(RouteBindRelayOutcome::DaemonRejected(ErrorBody {
2284                    code: "module_timeout".to_string(),
2285                    message: "route.bind response arrived after its daemon deadline".to_string(),
2286                    detail: None,
2287                }));
2288            return Ok(PendingRelayCompletion {
2289                settled: true,
2290                abandoned,
2291            });
2292        }
2293
2294        let fence_refusal = match (&outcome, &pending.capability_fence) {
2295            (RouteBindRelayOutcome::Accepted, Some(fence)) => fence_refusal(fence),
2296            _ => None,
2297        };
2298        // Read once: the scope check reads the wall clock, which can step
2299        // backwards, so a guard and a body that each read it could disagree.
2300        let scope_refusal = match (&outcome, &pending.scope) {
2301            (RouteBindRelayOutcome::Accepted, Some(scope)) => scope_refusal_locked(&inner, scope),
2302            _ => None,
2303        };
2304        // These readiness reads are not atomic with publication: a route may
2305        // commit after Dead. Taking a spawn transition lock here would invert
2306        // the publication lock order. Retirement, in one critical section,
2307        // stops every connection bound by the launch's claims and its own
2308        // registration channel from reading or sending frames, and shuts that
2309        // channel.
2310        // Once that step completes, no new request can cross the transient route
2311        // to or from the retired launch; connection teardown removes the route.
2312        match outcome {
2313            // Three shapes of "the client is not there to receive this route" that
2314            // must resolve identically: its egress is already closed, or it is
2315            // marked closing (its connection loop has been asked to end, but has
2316            // not drained yet, so the sink is still open), or its spawn is dead
2317            // before connection-close notifications have reached that loop.
2318            //
2319            // Only the first used to be caught here. The second fell through to
2320            // `commit_route_locked`, which refuses a closing client with
2321            // `ConnectionClosing` -- and this function is called from the MODULE
2322            // connection's frame handler, so that refusal ended the module's
2323            // connection instead of this one client's route. One dying client's
2324            // route.open then took down a connection carrying every other
2325            // client's routes to that module.
2326            //
2327            // The remedy for both is the same, which is why they share an arm:
2328            // give back the reserved handle pair, tell the waiting route.open the
2329            // route is gone, and report the module-side channel so the caller can
2330            // send a channel-scoped GOODBYE for the binding the module just
2331            // created. Nothing here touches the module connection.
2332            RouteBindRelayOutcome::Accepted
2333                if pending.client_sink.is_closed()
2334                    || spawn_connection_dead(
2335                        &inner,
2336                        pending.reservation.client_key.connection_id,
2337                    )
2338                    || inner
2339                        .closing_connections
2340                        .contains(&pending.reservation.client_key.connection_id) =>
2341            {
2342                let reason = if pending.client_sink.is_closed() {
2343                    "client egress closed before route publication"
2344                } else {
2345                    "client connection is closing before route publication"
2346                };
2347                release_reserved_route_locked(
2348                    &mut inner,
2349                    pending.reservation.client_key,
2350                    pending.reservation.module_key,
2351                );
2352                // Not gated on `relay_enqueued`: an ack proves the module
2353                // received the bind, and `route.open` sends nothing for a
2354                // relay a reply already settled, so this is the only GOODBYE.
2355                let abandoned = abandoned_route_target(&inner, &pending.reservation);
2356                let _ = pending
2357                    .sender
2358                    .send(RouteBindRelayOutcome::ModuleGone(reason.to_string()));
2359                return Ok(PendingRelayCompletion {
2360                    settled: true,
2361                    abandoned,
2362                });
2363            }
2364            // The endpoint that acked this bind is no longer accepting new
2365            // routes, for one of two reasons. Either it was the module's active
2366            // endpoint when this relay was reserved and a blue/green swap has
2367            // since promoted a candidate (the replacement process registered
2368            // beside it) into the active slot, superseding it; or a daemon
2369            // drain has gated it, and the ack arrived before the ordered module
2370            // drain settled pending relays. The module did nothing wrong: it
2371            // bound the route it was asked to bind, and the endpoint still
2372            // carries every other client's routes until it is drained. So the
2373            // ack is settled here, while the pending entry still holds the
2374            // client's sender and the reserved handle pair: release the pair,
2375            // refuse the waiting route.open with `module_reloading`, which
2376            // callers retry (after a swap the retry reserves on the promoted
2377            // endpoint), and hand back the module-side channel so the caller
2378            // sends one channel-scoped GOODBYE for the binding the module just
2379            // created. Returning an error instead would end the module
2380            // connection all those other routes share; nothing here touches it.
2381            //
2382            // An endpoint that stopped being active any other way is stale
2383            // (replaced, but not by a swap and not draining). It still falls
2384            // through to `commit_route_locked`, which refuses it with
2385            // `StaleModuleEndpoint` exactly as before swaps existed.
2386            RouteBindRelayOutcome::Accepted
2387                if inner.superseded_endpoints.contains_key(&endpoint)
2388                    || spawn_connection_dead(&inner, connection_id)
2389                    || inner.draining_endpoints.contains_key(&endpoint) =>
2390            {
2391                release_reserved_route_locked(
2392                    &mut inner,
2393                    pending.reservation.client_key,
2394                    pending.reservation.module_key,
2395                );
2396                // Not gated on `relay_enqueued`: an ack proves the module
2397                // received the bind, whether or not the enqueue mark was set.
2398                let abandoned = abandoned_route_target(&inner, &pending.reservation);
2399                let module_id = inner
2400                    .module_id_by_endpoint
2401                    .get(&endpoint)
2402                    .cloned()
2403                    .unwrap_or_else(|| "unknown".to_string());
2404                let _ = pending
2405                    .sender
2406                    .send(RouteBindRelayOutcome::DaemonRejected(ErrorBody::new(
2407                        "module_reloading",
2408                        format!("module_id '{module_id}' is reloading"),
2409                    )));
2410                return Ok(PendingRelayCompletion {
2411                    settled: true,
2412                    abandoned,
2413                });
2414            }
2415            // The scope the open was admitted under ended or changed after
2416            // admission. The module bound a route under a stamp that is no
2417            // longer true, so it must not become routable. Settled here like
2418            // the superseded arm above, never as an error from
2419            // `commit_route_locked`, which would close the module's whole
2420            // connection and every other client's routes to it: release the
2421            // pair, answer the waiting route.open by name, and hand back the
2422            // module-side channel for one channel-scoped GOODBYE.
2423            RouteBindRelayOutcome::Accepted if scope_refusal.is_some() => {
2424                let refusal = scope_refusal.expect("guard checked the refusal");
2425                let refused = RouteBindRelayOutcome::DaemonRejected(refusal);
2426                return Ok(refuse_acked_bind_locked(&mut inner, pending, refused));
2427            }
2428            // The caller's or the target's authority changed after the open
2429            // was attested, so the attestation the module bound on is no
2430            // longer true. Settled like the scope arm, never as an error from
2431            // `commit_route_locked`, which would close the module's shared
2432            // connection: release the pair, refuse the open by name, and hand
2433            // back the module-side channel for one channel-scoped GOODBYE.
2434            RouteBindRelayOutcome::Accepted
2435                if authority_stale_locked(&inner, pending.caller_authority.as_ref())
2436                    || authority_stale_locked(&inner, pending.target_authority.pair()) =>
2437            {
2438                let refused = RouteBindRelayOutcome::DaemonRejected(ErrorBody::new(
2439                    subc_protocol::error_codes::STALE_AUTHORITY_EPOCH,
2440                    "the caller's or target's authority changed while the route was binding",
2441                ));
2442                return Ok(refuse_acked_bind_locked(&mut inner, pending, refused));
2443            }
2444            // The opener's capability deny check no longer holds: the target
2445            // now provides a capability the opener must never reach, or the
2446            // admitted registration is gone. Settled like the arms above.
2447            RouteBindRelayOutcome::Accepted if fence_refusal.is_some() => {
2448                let refusal = fence_refusal.expect("guard checked the refusal");
2449                let refused = RouteBindRelayOutcome::DaemonRejected(refusal);
2450                return Ok(refuse_acked_bind_locked(&mut inner, pending, refused));
2451            }
2452            RouteBindRelayOutcome::Accepted => {
2453                #[cfg(all(test, target_os = "linux"))]
2454                if let Some(pause) = self.route_commit_pause.lock().unwrap().take() {
2455                    let _ = pause.reached.send(());
2456                    pause
2457                        .release
2458                        .recv_timeout(Duration::from_secs(5))
2459                        .expect("test must release bind publication");
2460                }
2461                let abandoned = commit_route_locked(&mut inner, pending)?;
2462                return Ok(PendingRelayCompletion {
2463                    settled: true,
2464                    abandoned,
2465                });
2466            }
2467            terminal => {
2468                release_reserved_route_locked(
2469                    &mut inner,
2470                    pending.reservation.client_key,
2471                    pending.reservation.module_key,
2472                );
2473                let _ = pending.sender.send(terminal);
2474            }
2475        }
2476        Ok(PendingRelayCompletion {
2477            settled: true,
2478            abandoned: None,
2479        })
2480    }
2481
2482    pub(crate) fn pending_module_control_op(
2483        &self,
2484        connection_id: ConnectionId,
2485        corr: u64,
2486    ) -> Result<Option<String>, ForwardingError> {
2487        let inner = self.read_inner()?;
2488        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2489            return Ok(None);
2490        };
2491        let key = (endpoint, corr);
2492        Ok(inner
2493            .pending_control_rpcs
2494            .get(&key)
2495            .map(|pending| pending.expected_op.clone())
2496            .or_else(|| {
2497                inner
2498                    .health_probe_tombstones
2499                    .get(&key)
2500                    .filter(|tombstone| tombstone.expires_at > Instant::now())
2501                    .map(|tombstone| tombstone.expected_op.clone())
2502            }))
2503    }
2504
2505    pub(crate) fn complete_module_control_rpc(
2506        &self,
2507        connection_id: ConnectionId,
2508        corr: u64,
2509        actual_op: Option<&str>,
2510        outcome: ModuleControlRpcOutcome,
2511    ) -> Result<ModuleControlRpcCompletion, ForwardingError> {
2512        let now = Instant::now();
2513        let mut inner = self.write_inner()?;
2514        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2515            return Ok(ModuleControlRpcCompletion::Unknown);
2516        };
2517        let key = (endpoint, corr);
2518        if let Some(pending) = inner.pending_control_rpcs.remove(&key) {
2519            if now >= pending.deadline {
2520                let late_health_answer = pending.health_probe_started_at.map(|probe_started_at| {
2521                    ModuleControlRpcCompletion::LateHealthAnswer {
2522                        module_id: inner
2523                            .module_id_by_endpoint
2524                            .get(&endpoint)
2525                            .cloned()
2526                            .unwrap_or_else(|| "unknown".to_string()),
2527                        latency: now.saturating_duration_since(probe_started_at),
2528                    }
2529                });
2530                let _ = pending
2531                    .sender
2532                    .send(ModuleControlRpcOutcome::DeadlineElapsed);
2533                return Ok(late_health_answer.unwrap_or(ModuleControlRpcCompletion::Settled));
2534            }
2535            let outcome = match actual_op {
2536                Some(actual) if actual != pending.expected_op => {
2537                    ModuleControlRpcOutcome::UnexpectedOp {
2538                        expected: pending.expected_op,
2539                        actual: actual.to_string(),
2540                    }
2541                }
2542                _ => outcome,
2543            };
2544            let _ = pending.sender.send(outcome);
2545            return Ok(ModuleControlRpcCompletion::Settled);
2546        }
2547
2548        let Some(tombstone) = inner.health_probe_tombstones.remove(&key) else {
2549            return Ok(ModuleControlRpcCompletion::Unknown);
2550        };
2551        if tombstone.expires_at <= now {
2552            return Ok(ModuleControlRpcCompletion::Unknown);
2553        }
2554        Ok(ModuleControlRpcCompletion::LateHealthAnswer {
2555            module_id: tombstone.module_id,
2556            latency: now.saturating_duration_since(tombstone.probe_started_at),
2557        })
2558    }
2559
2560    #[cfg(test)]
2561    pub(crate) fn health_probe_tombstone_count(&self) -> Result<usize, ForwardingError> {
2562        Ok(self.read_inner()?.health_probe_tombstones.len())
2563    }
2564
2565    #[cfg(test)]
2566    pub(crate) fn closing_connection_count(&self) -> Result<usize, ForwardingError> {
2567        Ok(self.read_inner()?.closing_connections.len())
2568    }
2569
2570    /// Reserved-but-uncommitted route handles, counted on both index sides, so
2571    /// a test can assert a reservation pair was actually given back.
2572    #[cfg(test)]
2573    pub(crate) fn reserved_route_count(&self) -> Result<(usize, usize), ForwardingError> {
2574        let inner = self.read_inner()?;
2575        Ok((inner.reserved_client.len(), inner.reserved_module.len()))
2576    }
2577
2578    pub(crate) fn module_endpoint_for_connection(
2579        &self,
2580        connection_id: ConnectionId,
2581    ) -> Result<Option<ModuleEndpointId>, ForwardingError> {
2582        Ok(self
2583            .read_inner()?
2584            .endpoint_by_connection
2585            .get(&connection_id)
2586            .copied())
2587    }
2588
2589    /// Looks up the module registered on a data-plane connection so route-drop
2590    /// diagnostics name the emitter instead of only reporting a daemon total.
2591    pub(crate) fn module_id_for_connection(
2592        &self,
2593        connection_id: ConnectionId,
2594    ) -> Result<Option<String>, ForwardingError> {
2595        let inner = self.read_inner()?;
2596        Ok(inner
2597            .endpoint_by_connection
2598            .get(&connection_id)
2599            .and_then(|endpoint| inner.module_id_by_endpoint.get(endpoint))
2600            .cloned())
2601    }
2602
2603    /// Whether the daemon ever allocated `(channel, epoch)` on this module
2604    /// connection. Epochs on a module channel are handed out as 1, 2, 3, ...
2605    /// and the last one handed out is remembered until the connection ends, so
2606    /// every epoch from 1 up to that one was a real route at some point. Used
2607    /// only on the drop path, to tell a module still sending on a route the
2608    /// daemon released from one sending on a route that never existed.
2609    pub(crate) fn module_route_epoch_was_allocated(
2610        &self,
2611        connection_id: ConnectionId,
2612        channel: u16,
2613        epoch: u32,
2614    ) -> Result<bool, ForwardingError> {
2615        let inner = self.read_inner()?;
2616        let Some(endpoint) = inner.endpoint_by_connection.get(&connection_id).copied() else {
2617            return Ok(false);
2618        };
2619        Ok(inner
2620            .module_slot_epochs
2621            .get(&ModuleRouteKey { endpoint, channel })
2622            .is_some_and(|last| epoch != 0 && epoch <= *last))
2623    }
2624
2625    pub(crate) fn has_live_module_connection(
2626        &self,
2627        module_id: &str,
2628    ) -> Result<bool, ForwardingError> {
2629        Ok(self.read_inner()?.modules_by_id.contains_key(module_id))
2630    }
2631
2632    /// Admission and route teardown share the forwarding-then-flow lock order.
2633    /// No asynchronous work may split validation from recording the credits.
2634    pub(crate) fn try_admit_request(
2635        &self,
2636        route: &Arc<RouteBinding>,
2637        epoch: u32,
2638        corr: u64,
2639        subscription: bool,
2640    ) -> Result<RequestAdmission, ForwardingError> {
2641        let inner = self.read_inner()?;
2642        if inner.upgrade_fenced {
2643            return Ok(RequestAdmission::DaemonUpgrade);
2644        }
2645        let key = ClientRouteKey {
2646            connection_id: route.client_connection_id,
2647            channel: route.client_channel,
2648        };
2649        if epoch != route.client_epoch
2650            || !inner
2651                .client_to_module
2652                .get(&key)
2653                .is_some_and(|current| Arc::ptr_eq(current, route))
2654        {
2655            return Ok(RequestAdmission::Stale);
2656        }
2657        let admission = route.flow.try_acquire_tagged(corr, subscription);
2658        Ok(match admission {
2659            RequestAdmission::Stale
2660                if inner
2661                    .draining_endpoints
2662                    .contains_key(&route.module_endpoint) =>
2663            {
2664                RequestAdmission::ModuleReloading
2665            }
2666            admission => admission,
2667        })
2668    }
2669
2670    pub(crate) fn lookup_data_route(
2671        &self,
2672        connection_id: ConnectionId,
2673        channel: u16,
2674        epoch: u32,
2675    ) -> Result<DataRoute, ForwardingError> {
2676        let inner = self.read_inner()?;
2677        let state = if let Some(endpoint) =
2678            inner.endpoint_by_connection.get(&connection_id).copied()
2679        {
2680            let key = ModuleRouteKey { endpoint, channel };
2681            match inner.module_to_client.get(&key) {
2682                Some(route) if route.module_epoch == epoch => {
2683                    DataRouteState::Bound(Arc::clone(route))
2684                }
2685                Some(_) => DataRouteState::EpochMismatch,
2686                None if inner.reserved_module.contains_key(&key)
2687                    && inner.module_slot_epochs.get(&key).copied() == Some(epoch) =>
2688                {
2689                    DataRouteState::Reserved
2690                }
2691                None if inner.reserved_module.contains_key(&key) => DataRouteState::EpochMismatch,
2692                None => DataRouteState::Absent,
2693            }
2694        } else {
2695            let key = ClientRouteKey {
2696                connection_id,
2697                channel,
2698            };
2699            match inner.client_to_module.get(&key) {
2700                Some(route) if route.client_epoch == epoch => {
2701                    DataRouteState::Bound(Arc::clone(route))
2702                }
2703                Some(_) => DataRouteState::EpochMismatch,
2704                None if inner.reserved_client.contains_key(&key)
2705                    && inner.client_slot_epochs.get(&key).copied() == Some(epoch) =>
2706                {
2707                    DataRouteState::Reserved
2708                }
2709                None if inner.reserved_client.contains_key(&key) => DataRouteState::EpochMismatch,
2710                None => DataRouteState::Absent,
2711            }
2712        };
2713        Ok(
2714            if inner.endpoint_by_connection.contains_key(&connection_id) {
2715                DataRoute::Module(state)
2716            } else {
2717                DataRoute::Client(state)
2718            },
2719        )
2720    }
2721
2722    #[cfg(test)]
2723    pub(crate) fn inject_client_slot_epoch(
2724        &self,
2725        connection_id: ConnectionId,
2726        channel: u16,
2727        last_epoch: u32,
2728    ) {
2729        let mut inner = self.write_inner().expect("forwarding lock");
2730        inner.client_slot_epochs.insert(
2731            ClientRouteKey {
2732                connection_id,
2733                channel,
2734            },
2735            last_epoch,
2736        );
2737        inner.next_client_channel.insert(connection_id, channel);
2738    }
2739
2740    #[cfg(test)]
2741    pub(crate) fn inject_module_slot_epoch(
2742        &self,
2743        endpoint: ModuleEndpointId,
2744        channel: u16,
2745        last_epoch: u32,
2746    ) {
2747        let mut inner = self.write_inner().expect("forwarding lock");
2748        inner
2749            .module_slot_epochs
2750            .insert(ModuleRouteKey { endpoint, channel }, last_epoch);
2751        inner.next_module_channel.insert(endpoint, channel);
2752    }
2753
2754    #[cfg(test)]
2755    pub(crate) fn inject_control_corr(&self, endpoint: ModuleEndpointId, next_corr: u64) {
2756        self.write_inner()
2757            .expect("forwarding lock")
2758            .next_control_corr
2759            .insert(endpoint, next_corr);
2760    }
2761
2762    pub(crate) fn cache_status(
2763        &self,
2764        endpoint: ModuleEndpointId,
2765        module_channel: u16,
2766        module_epoch: u32,
2767        status: String,
2768    ) -> Result<bool, ForwardingError> {
2769        let mut inner = self.write_inner()?;
2770        if !inner.module_id_by_endpoint.contains_key(&endpoint) {
2771            return Err(ForwardingError::StaleModuleEndpoint);
2772        }
2773
2774        let module_key = ModuleRouteKey {
2775            endpoint,
2776            channel: module_channel,
2777        };
2778        let handle = if let Some(route) = inner.module_to_client.get(&module_key) {
2779            (route.module_epoch == module_epoch).then_some((
2780                ClientRouteKey {
2781                    connection_id: route.client_connection_id,
2782                    channel: route.client_channel,
2783                },
2784                route.client_epoch,
2785            ))
2786        } else if let Some(client_key) = inner.reserved_module.get(&module_key).copied() {
2787            (inner.module_slot_epochs.get(&module_key).copied() == Some(module_epoch)).then_some((
2788                client_key,
2789                inner
2790                    .client_slot_epochs
2791                    .get(&client_key)
2792                    .copied()
2793                    .unwrap_or(0),
2794            ))
2795        } else {
2796            None
2797        };
2798
2799        if let Some(handle) = handle {
2800            inner.status.insert(handle, status);
2801            Ok(true)
2802        } else {
2803            debug!(
2804                module_channel,
2805                module_epoch,
2806                generation = endpoint.generation,
2807                connection_id = endpoint.connection_id.get(),
2808                "dropping stale status update for module route handle"
2809            );
2810            Ok(false)
2811        }
2812    }
2813
2814    pub(crate) fn route_poll_snapshot(
2815        &self,
2816        client_connection_id: ConnectionId,
2817        client_channel: u16,
2818        client_epoch: u32,
2819    ) -> Result<RoutePollSnapshot, ForwardingError> {
2820        let inner = self.read_inner()?;
2821        let client_key = ClientRouteKey {
2822            connection_id: client_connection_id,
2823            channel: client_channel,
2824        };
2825        let Some(route) = inner.client_to_module.get(&client_key) else {
2826            return Ok(RoutePollSnapshot::Absent);
2827        };
2828        if route.client_epoch != client_epoch
2829            || !inner
2830                .module_id_by_endpoint
2831                .contains_key(&route.module_endpoint)
2832        {
2833            return Ok(RoutePollSnapshot::Absent);
2834        }
2835        Ok(RoutePollSnapshot::Bound {
2836            module_id: route.module_id.clone(),
2837            status: inner.status.get(&(client_key, client_epoch)).cloned(),
2838        })
2839    }
2840
2841    pub fn active_binding_count(&self) -> Result<usize, ForwardingError> {
2842        Ok(self.read_inner()?.client_to_module.len())
2843    }
2844
2845    /// How many distinct client connections hold at least one committed route,
2846    /// alongside the largest number of routes any single connection holds.
2847    ///
2848    /// `connected_clients` alone cannot distinguish many clients with a route
2849    /// each from one client accumulating hundreds, and those have opposite
2850    /// causes. Reading it required an out-of-band `lsof` during a live
2851    /// investigation, and the count of connections was mistaken for a count of
2852    /// client processes — which sent two of us after cleanup paths that were
2853    /// working correctly.
2854    pub fn client_route_concentration(&self) -> Result<(usize, usize), ForwardingError> {
2855        let inner = self.read_inner()?;
2856        let mut per_connection: HashMap<ConnectionId, usize> = HashMap::new();
2857        for key in inner.client_to_module.keys() {
2858            *per_connection.entry(key.connection_id).or_insert(0) += 1;
2859        }
2860        let max = per_connection.values().copied().max().unwrap_or(0);
2861        Ok((per_connection.len(), max))
2862    }
2863
2864    pub fn has_route_channel(&self, route_channel: u16) -> Result<bool, ForwardingError> {
2865        let inner = self.read_inner()?;
2866        Ok(inner
2867            .client_to_module
2868            .keys()
2869            .any(|key| key.channel == route_channel))
2870    }
2871
2872    /// Whether daemon-wide shutdown has begun draining all providers.
2873    /// `None` means normal operation; during daemon shutdown, return the
2874    /// endpoint's measured result, or false if no completed measurement exists.
2875    pub(crate) fn daemon_drain_result_for_connection(
2876        &self,
2877        connection_id: ConnectionId,
2878    ) -> Result<Option<bool>, ForwardingError> {
2879        let inner = self.read_inner()?;
2880        Ok(inner.daemon_draining.then(|| {
2881            inner
2882                .endpoint_by_connection
2883                .get(&connection_id)
2884                .and_then(|endpoint| inner.daemon_drain_results.get(endpoint))
2885                .copied()
2886                .unwrap_or(false)
2887        }))
2888    }
2889
2890    #[cfg(unix)]
2891    pub(crate) fn record_daemon_drain_result(
2892        &self,
2893        endpoint: ModuleEndpointId,
2894        drained: bool,
2895    ) -> Result<(), ForwardingError> {
2896        let mut inner = self.write_inner()?;
2897        // Only update an endpoint captured at the start of daemon shutdown.
2898        // Teardown removes its entry, so a late wait cannot recreate the result
2899        // or attribute it to a replacement connection.
2900        if let Some(result) = inner.daemon_drain_results.get_mut(&endpoint) {
2901            *result = drained;
2902        }
2903        Ok(())
2904    }
2905
2906    /// Gate every provider atomically, including registrations racing shutdown.
2907    /// No supervisor lock is held while taking the forwarding lock.
2908    #[cfg(unix)]
2909    pub(crate) fn begin_daemon_drain(
2910        &self,
2911    ) -> Result<Vec<(String, ModuleEndpointId)>, ForwardingError> {
2912        let mut inner = self.write_inner()?;
2913        if inner.daemon_draining {
2914            return Ok(Vec::new());
2915        }
2916        inner.daemon_draining = true;
2917        let modules = inner
2918            .modules_by_id
2919            .iter()
2920            .map(|(id, module)| (id.clone(), module.endpoint))
2921            .collect::<Vec<_>>();
2922        for (_, endpoint) in &modules {
2923            inner.daemon_drain_results.insert(*endpoint, false);
2924            inner
2925                .draining_endpoints
2926                .insert(*endpoint, RouteCloseReason::Restart);
2927        }
2928        // Swap candidates and superseded incumbents are not routable, but they
2929        // are live endpoints that could still be sent module-control work, so
2930        // the daemon-wide gate covers them too. Only the active endpoints are
2931        // returned to the supervisor for measurement, one per module id.
2932        let off_slot_endpoints = inner
2933            .candidates_by_id
2934            .values()
2935            .map(|module| module.endpoint)
2936            .chain(inner.superseded_endpoints.keys().copied())
2937            .collect::<Vec<_>>();
2938        for endpoint in off_slot_endpoints {
2939            inner
2940                .draining_endpoints
2941                .insert(endpoint, RouteCloseReason::Restart);
2942        }
2943        accepting_drain::wake_accepting_drains_for_shutdown_locked(&inner);
2944        Ok(modules)
2945    }
2946
2947    /// Begin draining whatever endpoint is ACTIVE for `module_id`.
2948    ///
2949    /// After a swap's cutover the active endpoint is the promoted candidate, so
2950    /// this must not be used to drain the incumbent; use
2951    /// [`Self::begin_endpoint_drain`] with the endpoint `cutover_candidate`
2952    /// returned.
2953    pub(crate) fn begin_module_drain(
2954        &self,
2955        module_id: &str,
2956        reason: RouteCloseReason,
2957    ) -> Result<Option<ModuleDrainTarget>, ForwardingError> {
2958        let mut inner = self.write_inner()?;
2959        let Some(module) = inner.modules_by_id.get(module_id).cloned() else {
2960            return Ok(None);
2961        };
2962        Ok(Some(begin_drain_locked(
2963            &mut inner, module_id, module, reason,
2964        )))
2965    }
2966
2967    /// Begin draining one specific endpoint, whichever slot it is in.
2968    ///
2969    /// This is how a swap drains its incumbent after cutover: the incumbent's
2970    /// endpoint is captured by `cutover_candidate`, and resolving it by module id
2971    /// instead would find the promoted candidate and leave neither process
2972    /// routable. Returns `Ok(None)` when the endpoint is no longer registered.
2973    pub(crate) fn begin_endpoint_drain(
2974        &self,
2975        endpoint: ModuleEndpointId,
2976        reason: RouteCloseReason,
2977    ) -> Result<Option<ModuleDrainTarget>, ForwardingError> {
2978        let mut inner = self.write_inner()?;
2979        let Some(module) = module_connection_for_endpoint_locked(&inner, endpoint).cloned() else {
2980            return Ok(None);
2981        };
2982        let module_id = inner
2983            .module_id_by_endpoint
2984            .get(&endpoint)
2985            .cloned()
2986            .expect("an endpoint resolved to a module connection has a module id");
2987        Ok(Some(begin_drain_locked(
2988            &mut inner, &module_id, module, reason,
2989        )))
2990    }
2991}
2992
2993/// Mark `module`'s endpoint draining and settle everything still pending on it.
2994/// Shared by the by-id and by-endpoint drain entry points, which differ only in
2995/// how they find the endpoint.
2996fn begin_drain_locked(
2997    inner: &mut ForwardingInner,
2998    module_id: &str,
2999    module: ModuleConnection,
3000    reason: RouteCloseReason,
3001) -> ModuleDrainTarget {
3002    {
3003        let endpoint = module.endpoint;
3004        inner.draining_endpoints.insert(endpoint, reason);
3005
3006        let flows = inner
3007            .client_to_module
3008            .values()
3009            .filter(|route| route.module_endpoint == endpoint)
3010            .map(|route| Arc::clone(&route.flow))
3011            .collect::<Vec<_>>();
3012        let excluded_subscriptions = flows
3013            .into_iter()
3014            .map(|flow| flow.begin_drain())
3015            .fold(0u32, u32::saturating_add);
3016
3017        let pending_keys = inner
3018            .pending_relays
3019            .keys()
3020            .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
3021            .copied()
3022            .collect::<Vec<_>>();
3023        let mut abandoned_bindings = Vec::new();
3024        for key in pending_keys {
3025            let Some(pending) = inner.pending_relays.remove(&key) else {
3026                continue;
3027            };
3028            release_reserved_route_locked(
3029                inner,
3030                pending.reservation.client_key,
3031                pending.reservation.module_key,
3032            );
3033            if pending.relay_enqueued {
3034                if let Some(target) = abandoned_route_target(inner, &pending.reservation) {
3035                    abandoned_bindings.push(target);
3036                }
3037            } else {
3038                // The bind may still be on its way into the module's queue;
3039                // a GOODBYE sent now could overtake it. `route.open` sends
3040                // it once its send completes.
3041                inner.relays_released_before_enqueue.insert(key);
3042            }
3043            let _ = pending
3044                .sender
3045                .send(RouteBindRelayOutcome::DaemonRejected(ErrorBody::new(
3046                    "module_reloading",
3047                    format!("module_id '{module_id}' is reloading"),
3048                )));
3049        }
3050
3051        let pending_control_keys = inner
3052            .pending_control_rpcs
3053            .keys()
3054            .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
3055            .copied()
3056            .collect::<Vec<_>>();
3057        for key in pending_control_keys {
3058            if let Some(pending) = inner.pending_control_rpcs.remove(&key) {
3059                let _ = pending
3060                    .sender
3061                    .send(ModuleControlRpcOutcome::ModuleGone(format!(
3062                        "module '{module_id}' began draining during module-control RPC"
3063                    )));
3064            }
3065        }
3066
3067        ModuleDrainTarget {
3068            endpoint,
3069            sink: module.sink,
3070            negotiated_ver: module.negotiated_ver,
3071            abandoned_bindings,
3072            excluded_subscriptions,
3073        }
3074    }
3075}
3076
3077/// What a drain that timed out was still waiting on, for the log line that
3078/// reports the timeout. Per-request ages are not tracked.
3079#[derive(Debug, Default, PartialEq, Eq)]
3080pub(crate) struct DrainHoldouts {
3081    /// Requests still counted against the drain (subscriptions flagged as
3082    /// such are excluded from the drain and not counted here).
3083    pub(crate) requests: usize,
3084    /// Routes holding at least one of those requests.
3085    pub(crate) routes: usize,
3086    /// Every route on the endpoint, for scale.
3087    pub(crate) total_routes: usize,
3088    /// The client connections holding the most requests, largest first, at
3089    /// most three: enough to name the consumer without listing every route.
3090    pub(crate) top_connections: Vec<(u64, usize)>,
3091    /// The held requests themselves, as the module saw them, so its own log
3092    /// can say what each one was: `(module channel, corr)`, ordered by channel
3093    /// then corr, at most [`DRAIN_HELD_REQUESTS_LISTED`]. The daemon never reads
3094    /// request bodies, so it cannot name a request's method; the module can,
3095    /// from the channel and corr. A request is released only when the module
3096    /// sends a terminal frame (Response, Error or StreamEnd) with its corr on
3097    /// its route, so every pair listed here is one the module ended, if at all,
3098    /// without sending that frame.
3099    pub(crate) held: Vec<(u16, u64)>,
3100}
3101
3102/// How many held requests the drain-timeout line lists by channel and corr.
3103pub(crate) const DRAIN_HELD_REQUESTS_LISTED: usize = 32;
3104
3105impl ForwardingTable {
3106    /// Summarise the requests one endpoint's drain is still waiting on.
3107    pub(crate) fn endpoint_drain_holdouts(
3108        &self,
3109        endpoint: ModuleEndpointId,
3110    ) -> Result<DrainHoldouts, ForwardingError> {
3111        let inner = self.read_inner()?;
3112        let mut holdouts = DrainHoldouts::default();
3113        let mut by_connection: HashMap<u64, usize> = HashMap::new();
3114        for (key, route) in &inner.client_to_module {
3115            if route.module_endpoint != endpoint {
3116                continue;
3117            }
3118            holdouts.total_routes += 1;
3119            let held = route.flow.drain_in_flight();
3120            if held == 0 {
3121                continue;
3122            }
3123            holdouts.requests += held;
3124            holdouts.routes += 1;
3125            *by_connection.entry(key.connection_id.get()).or_default() += held;
3126            holdouts.held.extend(
3127                route
3128                    .flow
3129                    .drain_held_corrs()
3130                    .into_iter()
3131                    .map(|corr| (route.module_channel, corr)),
3132            );
3133        }
3134        holdouts.held.sort_unstable();
3135        holdouts.held.truncate(DRAIN_HELD_REQUESTS_LISTED);
3136        let mut connections = by_connection.into_iter().collect::<Vec<_>>();
3137        connections.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(&right.0)));
3138        connections.truncate(3);
3139        holdouts.top_connections = connections;
3140        Ok(holdouts)
3141    }
3142
3143    pub(crate) fn endpoint_in_flight_count(
3144        &self,
3145        endpoint: ModuleEndpointId,
3146    ) -> Result<usize, ForwardingError> {
3147        let inner = self.read_inner()?;
3148        Ok(inner
3149            .client_to_module
3150            .values()
3151            .filter(|route| route.module_endpoint == endpoint)
3152            .map(|route| route.flow.drain_in_flight())
3153            .sum())
3154    }
3155
3156    pub(crate) fn endpoint_is_draining(
3157        &self,
3158        endpoint: ModuleEndpointId,
3159    ) -> Result<bool, ForwardingError> {
3160        Ok(self
3161            .read_inner()?
3162            .draining_endpoints
3163            .contains_key(&endpoint))
3164    }
3165
3166    pub(crate) fn module_is_draining(&self, module_id: &str) -> Result<bool, ForwardingError> {
3167        let inner = self.read_inner()?;
3168        Ok(inner
3169            .modules_by_id
3170            .get(module_id)
3171            .is_some_and(|module| inner.draining_endpoints.contains_key(&module.endpoint)))
3172    }
3173
3174    pub(crate) fn release_module_endpoint_routes(
3175        &self,
3176        endpoint: ModuleEndpointId,
3177    ) -> Result<Vec<GoodbyeTarget>, ForwardingError> {
3178        let mut inner = self.write_inner()?;
3179        let routes = inner
3180            .module_to_client
3181            .iter()
3182            .filter(|(module_key, _)| module_key.endpoint == endpoint)
3183            .map(|(module_key, route)| (*module_key, route.module_epoch))
3184            .collect::<Vec<_>>();
3185        let mut released = Vec::with_capacity(routes.len());
3186        for (module_key, epoch) in routes {
3187            if let RouteRelease::Removed(target) =
3188                release_module_route_locked(&mut inner, module_key, epoch)
3189            {
3190                released.push(target);
3191            }
3192        }
3193        Ok(released)
3194    }
3195
3196    /// Revoke old bind decisions atomically, including binds still in flight.
3197    /// The provider stays available: its acknowledged config governs new binds.
3198    pub(crate) fn rebind_module_policy(
3199        &self,
3200        module_id: &str,
3201        expected_connection: Option<ConnectionId>,
3202        authorized: impl FnOnce() -> bool,
3203    ) -> Result<Option<PolicyRevocation>, ForwardingError> {
3204        #[cfg(test)]
3205        if let Some(hold) = self.policy_rebind_before_write.lock().unwrap().take() {
3206            hold.wait();
3207            hold.wait();
3208        }
3209        let mut inner = self.write_inner()?;
3210        let module = inner
3211            .modules_by_id
3212            .get(module_id)
3213            .cloned()
3214            .ok_or(ForwardingError::NoModuleConnection)?;
3215        if expected_connection.is_some_and(|connection| module.endpoint.connection_id != connection)
3216            || !authorized()
3217        {
3218            return Ok(None);
3219        }
3220        let endpoint = module.endpoint;
3221        if inner.draining_endpoints.contains_key(&endpoint) {
3222            return Err(ForwardingError::ModuleReloading {
3223                module_id: module_id.to_owned(),
3224            });
3225        }
3226        let target = begin_drain_locked(&mut inner, module_id, module, RouteCloseReason::Reload);
3227        let routes = endpoint_routes_locked(&inner, endpoint);
3228        let mut goodbyes = target.abandoned_bindings;
3229        for route in &routes {
3230            let target = &route.goodbye_target;
3231            if let RouteRelease::Removed(module) = release_client_route_locked(
3232                &mut inner,
3233                ClientRouteKey {
3234                    connection_id: target.connection_id,
3235                    channel: target.channel,
3236                },
3237                target.epoch,
3238            ) {
3239                goodbyes.push(module);
3240                goodbyes.push(target.clone());
3241            }
3242        }
3243        inner.draining_endpoints.remove(&endpoint);
3244        Ok(Some((routes, goodbyes)))
3245    }
3246
3247    #[cfg(test)]
3248    pub(crate) fn pause_policy_rebind_before_write(&self, hold: Arc<std::sync::Barrier>) {
3249        *self.policy_rebind_before_write.lock().unwrap() = Some(hold);
3250    }
3251
3252    #[cfg(test)]
3253    pub(crate) fn with_forwarding_write_lock_for_test(&self, work: impl FnOnce()) {
3254        let _guard = self.write_inner().unwrap();
3255        work();
3256    }
3257
3258    /// Enumerate one endpoint's current routes without contacting the module.
3259    ///
3260    /// The read lock makes this safe while the endpoint drains: the returned
3261    /// `draining` marker describes the same table state that owns the route,
3262    /// rather than inferring liveness from a module that may be stopping.
3263    pub(crate) fn endpoint_routes(
3264        &self,
3265        endpoint: ModuleEndpointId,
3266    ) -> Result<Vec<EndpointRoute>, ForwardingError> {
3267        let inner = self.read_inner()?;
3268        Ok(endpoint_routes_locked(&inner, endpoint))
3269    }
3270
3271    /// Snapshot all live endpoint route sets under one forwarding-table read lock.
3272    pub(crate) fn route_census(
3273        &self,
3274        module_id: Option<&str>,
3275    ) -> Result<Vec<(String, Vec<EndpointRoute>)>, ForwardingError> {
3276        let inner = self.read_inner()?;
3277        let mut endpoints = inner
3278            .modules_by_id
3279            .iter()
3280            .filter(|(id, _)| module_id.is_none_or(|requested| requested == id.as_str()))
3281            .map(|(id, module)| (id.clone(), module.endpoint))
3282            .collect::<Vec<_>>();
3283        endpoints.sort_by(|left, right| left.0.cmp(&right.0));
3284        Ok(endpoints
3285            .into_iter()
3286            .map(|(id, endpoint)| (id, endpoint_routes_locked(&inner, endpoint)))
3287            .collect())
3288    }
3289
3290    /// Snapshot only the endpoint currently routable under this module id.
3291    pub(crate) fn live_roots(
3292        &self,
3293        module_id: &str,
3294    ) -> Result<ModuleControlResponseToModule, ForwardingError> {
3295        let inner = self.read_inner()?;
3296        let endpoint = inner
3297            .modules_by_id
3298            .get(module_id)
3299            .map(|module| module.endpoint);
3300        let mut roots = BTreeMap::new();
3301        let mut unknown_root_bindings = 0;
3302        let mut total_bindings = 0;
3303        if let Some(endpoint) = endpoint {
3304            for binding in inner
3305                .module_to_client
3306                .values()
3307                .filter(|binding| binding.module_endpoint == endpoint)
3308            {
3309                total_bindings += 1;
3310                let workdir = binding
3311                    .scope
3312                    .as_ref()
3313                    .and_then(|scope| scope.workdir.as_deref())
3314                    .map(std::path::Path::new);
3315                if let Some(root) = &binding.project_root {
3316                    let entry = roots.entry(root.as_path().to_path_buf()).or_insert((0, 0));
3317                    entry.0 += 1;
3318                } else if workdir.is_none() {
3319                    unknown_root_bindings += 1;
3320                }
3321                if let Some(workdir) = workdir.filter(|workdir| {
3322                    binding.project_root.as_ref().map(ProjectRootId::as_path) != Some(*workdir)
3323                }) {
3324                    roots.entry(workdir.to_path_buf()).or_insert((0, 0)).0 += 1;
3325                }
3326            }
3327            for pending in inner
3328                .pending_relays
3329                .values()
3330                .filter(|pending| pending.reservation.module_key.endpoint == endpoint)
3331            {
3332                total_bindings += 1;
3333                if let Some(root) = &pending.reservation.project_root {
3334                    let entry = roots.entry(root.as_path().to_path_buf()).or_insert((0, 0));
3335                    entry.1 += 1;
3336                } else {
3337                    unknown_root_bindings += 1;
3338                }
3339            }
3340        }
3341        Ok(ModuleControlResponseToModule::LiveRoots {
3342            roots: roots
3343                .into_iter()
3344                .map(|(project_root, (bound, pending))| LiveRoot {
3345                    project_root,
3346                    bound,
3347                    pending,
3348                })
3349                .collect(),
3350            unknown_root_bindings,
3351            total_bindings,
3352        })
3353    }
3354
3355    /// True if this connection already owns committed or reserved CLIENT routes.
3356    /// A module registers (HELLO) before serving and never opens client routes, so
3357    /// a connection that has client routes must not also become a module endpoint
3358    /// — otherwise one connection holds both client and module state and cleanup
3359    /// only releases one side.
3360    pub(crate) fn connection_has_client_routes(
3361        &self,
3362        connection_id: ConnectionId,
3363    ) -> Result<bool, ForwardingError> {
3364        let inner = self.read_inner()?;
3365        Ok(connection_has_client_routes_locked(&inner, connection_id))
3366    }
3367
3368    pub(crate) fn cleanup_connection(
3369        &self,
3370        connection_id: ConnectionId,
3371    ) -> Result<Vec<GoodbyeTarget>, ForwardingError> {
3372        self.cleanup_connection_counted(connection_id)
3373            .map(|cleanup| cleanup.released)
3374    }
3375
3376    /// [`Self::cleanup_connection`], also reporting how many pending
3377    /// route.bind relays to the closed module were aborted. That count is the
3378    /// `abandoned` figure of the `route.closed` push sent for a lost module
3379    /// connection; it is always zero for a client connection.
3380    pub(crate) fn cleanup_connection_counted(
3381        &self,
3382        connection_id: ConnectionId,
3383    ) -> Result<ConnectionCleanup, ForwardingError> {
3384        self.frame_drop_warnings
3385            .lock()
3386            .unwrap_or_else(std::sync::PoisonError::into_inner)
3387            .remove(&connection_id);
3388        let mut inner = self.write_inner()?;
3389        inner.closing_connections.insert(connection_id);
3390        #[cfg(all(test, target_os = "linux"))]
3391        if let Some(pause) = self.cleanup_pause.lock().unwrap().take() {
3392            let _ = pause.reached.send(());
3393            pause
3394                .release
3395                .recv_timeout(Duration::from_secs(5))
3396                .expect("test must release connection cleanup");
3397        }
3398        #[cfg(all(test, target_os = "linux"))]
3399        if let Some(observe) = self.cleanup_tie_observer.lock().unwrap().take() {
3400            let pending = inner
3401                .pending_relays
3402                .values()
3403                .filter(|relay| relay.reservation.client_key.connection_id == connection_id)
3404                .count();
3405            let _ = observe.send((
3406                inner.spawn_connections.contains_key(&connection_id),
3407                pending,
3408            ));
3409        }
3410        let cleanup = if let Some(endpoint) = inner.endpoint_by_connection.remove(&connection_id) {
3411            remove_module_connection_locked(&mut inner, endpoint)
3412        } else {
3413            ConnectionCleanup {
3414                released: Self::cleanup_client_connection_locked(&mut inner, connection_id),
3415                abandoned_relays: 0,
3416            }
3417        };
3418        // The closing mark refuses new work for a connection whose teardown is
3419        // still pending. This is the latest point at which lifting it is safe:
3420        // teardown has just removed every per-connection entry above, under
3421        // this same write lock, so no lookup can still find live state for the
3422        // id; and ids come from a monotonic counter that never reissues one,
3423        // so the id can never name a future connection either. Keeping the
3424        // mark past this point only grew the set by one entry per connection
3425        // for the life of the daemon.
3426        inner.closing_connections.remove(&connection_id);
3427        Ok(cleanup)
3428    }
3429
3430    fn cleanup_client_connection_locked(
3431        inner: &mut ForwardingInner,
3432        connection_id: ConnectionId,
3433    ) -> Vec<GoodbyeTarget> {
3434        let routes = inner
3435            .client_to_module
3436            .iter()
3437            .filter(|(key, _)| key.connection_id == connection_id)
3438            .map(|(key, route)| (*key, route.client_epoch))
3439            .collect::<Vec<_>>();
3440        let mut released = Vec::with_capacity(routes.len());
3441        for (client_key, epoch) in routes {
3442            if let RouteRelease::Removed(target) =
3443                release_client_route_locked(inner, client_key, epoch)
3444            {
3445                released.push(target);
3446            }
3447        }
3448
3449        let pending_keys = inner
3450            .pending_relays
3451            .iter()
3452            .filter(|(_, pending)| pending.reservation.client_key.connection_id == connection_id)
3453            .map(|(key, _)| *key)
3454            .collect::<Vec<_>>();
3455        for key in pending_keys {
3456            let Some(pending) = inner.pending_relays.remove(&key) else {
3457                continue;
3458            };
3459            release_reserved_route_locked(
3460                inner,
3461                pending.reservation.client_key,
3462                pending.reservation.module_key,
3463            );
3464            if pending.relay_enqueued {
3465                if let Some(target) = abandoned_route_target(inner, &pending.reservation) {
3466                    released.push(target);
3467                }
3468            } else {
3469                // The bind may still be on its way into the module's queue;
3470                // a GOODBYE sent now could overtake it. `route.open` sends
3471                // it once its send completes.
3472                inner.relays_released_before_enqueue.insert(key);
3473            }
3474            let _ = pending.sender.send(RouteBindRelayOutcome::ModuleGone(
3475                "client connection closed during route.bind relay".to_string(),
3476            ));
3477        }
3478
3479        let orphaned = inner
3480            .reserved_client
3481            .iter()
3482            .filter(|(key, _)| key.connection_id == connection_id)
3483            .map(|(client, module)| (*client, *module))
3484            .collect::<Vec<_>>();
3485        for (client_key, module_key) in orphaned {
3486            release_reserved_route_locked(inner, client_key, module_key);
3487        }
3488        inner.next_client_channel.remove(&connection_id);
3489        inner
3490            .client_slot_epochs
3491            .retain(|key, _| key.connection_id != connection_id);
3492        inner
3493            .last_published_epoch
3494            .retain(|key, _| key.connection_id != connection_id);
3495        inner
3496            .status
3497            .retain(|(key, _), _| key.connection_id != connection_id);
3498
3499        released
3500    }
3501
3502    /// Close a client connection whose egress queue refused a frame for the
3503    /// route `(connection_id, channel)` at `expected_epoch`. The whole
3504    /// connection closes because its queue is shared by every route on it.
3505    ///
3506    /// The first request that actually closes the connection logs one WARN with
3507    /// the diagnosis: which principals the connection's routes belonged to,
3508    /// which module's frame did not fit and on which client channel, and what
3509    /// the queue held at that moment.
3510    pub(crate) fn escalate_client_delivery_failure(
3511        &self,
3512        connection_id: ConnectionId,
3513        channel: u16,
3514        expected_epoch: u32,
3515        reason: CloseReason,
3516        undelivered: UndeliveredFrame<'_>,
3517    ) -> Result<bool, ForwardingError> {
3518        self.escalate_client_delivery_failure_diagnosed(
3519            connection_id,
3520            channel,
3521            expected_epoch,
3522            reason,
3523            undelivered,
3524            None,
3525        )
3526    }
3527
3528    pub(crate) fn escalate_client_delivery_failure_diagnosed(
3529        &self,
3530        connection_id: ConnectionId,
3531        channel: u16,
3532        expected_epoch: u32,
3533        reason: CloseReason,
3534        undelivered: UndeliveredFrame<'_>,
3535        diagnosis: Option<&crate::router::ClientDeliveryDiagnosis>,
3536    ) -> Result<bool, ForwardingError> {
3537        let principals = {
3538            let mut inner = self.write_inner()?;
3539            let key = ClientRouteKey {
3540                connection_id,
3541                channel,
3542            };
3543            if inner.last_published_epoch.get(&key).copied() != Some(expected_epoch) {
3544                None
3545            } else {
3546                inner.closing_connections.insert(connection_id);
3547                Some(connection_principals_locked(&inner, connection_id))
3548            }
3549        };
3550        let Some(principals) = principals else {
3551            // A concurrent release can remove the epoch before escalation.
3552            // The frame was still lost, even though this route can no longer
3553            // authorize closing the shared client connection.
3554            self.warn_frame_drop(
3555                connection_id,
3556                channel,
3557                expected_epoch,
3558                "module_to_client",
3559                diagnosis
3560                    .map(|failure| failure.cause)
3561                    .unwrap_or("delivery_failed"),
3562            );
3563            return Ok(false);
3564        };
3565        let backlog = undelivered.sink.backlog();
3566        let close_reason = reason.to_string();
3567        if self.request_connection_close(connection_id, reason) {
3568            warn!(
3569                connection_id = connection_id.get(),
3570                principals = %principals,
3571                module_id = undelivered.module_id.unwrap_or("unknown"),
3572                client_channel = channel,
3573                queued_bytes = backlog.queued_bytes,
3574                queued_frames = backlog.queued_frames,
3575                frame_type = ?diagnosis.map(|failure| failure.frame_type),
3576                frame_flags = ?diagnosis.map(|failure| failure.flags.0),
3577                close_cause = diagnosis.map(|failure| failure.cause).unwrap_or("delivery_failed"),
3578                oldest_queued_ms = backlog
3579                    .oldest_age
3580                    .map(|age| age.as_millis() as u64)
3581                    .unwrap_or(0),
3582                close_reason = %close_reason,
3583                "closing client connection: its egress queue could not take a frame"
3584            );
3585        }
3586        Ok(true)
3587    }
3588
3589    /// Publish the tags a scope sync changed and close the live routes its
3590    /// drain table selects, in one critical section.
3591    ///
3592    /// The caller holds the scope table's write lock (scope table, then this
3593    /// table, always). Publishing and selecting under one lock is what closes
3594    /// the race with a bind commit: a commit before this sees the old tag and
3595    /// its route is selected here like any other; a commit after it sees the
3596    /// new tag and is refused.
3597    ///
3598    /// Every client route index entry is scanned, which includes routes on a
3599    /// swap's superseded endpoint (the old process of a module being replaced
3600    /// blue/green, which keeps its existing routes until they drain): those
3601    /// stay indexed until drained, so ending a scope reaches them too.
3602    pub(crate) fn publish_scope_changes(
3603        &self,
3604        changes: &[ScopeTagChange],
3605    ) -> Result<Vec<ScopeDrainedRoute>, ForwardingError> {
3606        let mut inner = self.write_inner()?;
3607        let mut by_scope: HashMap<(&str, &str), &ScopeTagChange> = HashMap::new();
3608        for change in changes {
3609            let key = (change.owner.clone(), change.scope_ref.clone());
3610            match change.after {
3611                Some(tag) => {
3612                    inner.scope_tags.insert(key, tag);
3613                }
3614                None => {
3615                    inner.scope_tags.remove(&key);
3616                }
3617            }
3618            by_scope.insert((change.owner.as_str(), change.scope_ref.as_str()), change);
3619        }
3620        let mut selected = Vec::new();
3621        for (client_key, route) in &inner.client_to_module {
3622            let Some(scope) = &route.scope else {
3623                continue;
3624            };
3625            let Some(change) = by_scope.get(&(scope.owner.as_str(), scope.scope_ref.as_str()))
3626            else {
3627                continue;
3628            };
3629            if change.before.map(|tag| tag.scope_epoch) != Some(scope.tag.scope_epoch) {
3630                continue;
3631            }
3632            let reason = match &change.drain {
3633                ScopeDrain::Nothing => continue,
3634                ScopeDrain::All(reason) => *reason,
3635                ScopeDrain::Carriers(narrowed) => {
3636                    let owner = Principal::Reserved {
3637                        module_id: scope.owner.clone(),
3638                    };
3639                    let hit = route.principal != owner
3640                        && narrowed.iter().any(|(principal, allowed)| {
3641                            *principal == route.principal
3642                                && allowed
3643                                    .as_ref()
3644                                    .is_none_or(|targets| !targets.contains(&route.module_id))
3645                        });
3646                    if !hit {
3647                        continue;
3648                    }
3649                    RouteCloseReason::ScopeCarrierRemoved
3650                }
3651            };
3652            selected.push((*client_key, route.client_epoch, reason));
3653        }
3654        let mut drained = Vec::new();
3655        for (client_key, client_epoch, reason) in selected {
3656            let Some(route) = inner.client_to_module.get(&client_key).cloned() else {
3657                continue;
3658            };
3659            let release = release_client_route_locked(&mut inner, client_key, client_epoch);
3660            self.record_route_release(&release);
3661            if let RouteRelease::Removed(module) = release {
3662                drained.push(ScopeDrainedRoute {
3663                    reason,
3664                    scope: route
3665                        .scope
3666                        .clone()
3667                        .expect("selected scope drain has a bound scope"),
3668                    module_id: route.module_id.clone(),
3669                    client: GoodbyeTarget {
3670                        connection_id: route.client_connection_id,
3671                        sink: route.client_sink.clone(),
3672                        negotiated_ver: route.client_negotiated_ver,
3673                        channel: route.client_channel,
3674                        epoch: route.client_epoch,
3675                        kind: GoodbyeTargetKind::Client,
3676                        module_id: Some(route.module_id.clone()),
3677                    },
3678                    module,
3679                    accepts_close_reasons: route.accepts_close_reasons.clone(),
3680                });
3681            }
3682        }
3683        Ok(drained)
3684    }
3685
3686    /// Publish a spawn's new authority epoch and release every live route
3687    /// whose recorded caller or target is that spawn at an older epoch, in one
3688    /// critical section.
3689    ///
3690    /// The caller holds the spawn's authority record state (record, then this
3691    /// table, always; see `SpawnAuthorityRecord::change_authority`). A bind
3692    /// that commits before this is selected here like any other route; one
3693    /// that commits after it sees the new epoch and is refused as stale.
3694    ///
3695    /// Unlike [`Self::publish_scope_changes`], every client route is scanned,
3696    /// scoped or not. Once a spawn is dead (`alive` false), its own mark and
3697    /// approved set are dropped and its epoch stays as a tombstone, so a bind
3698    /// still naming it is refused as stale. Another spawn of the same module
3699    /// is never touched: a blue/green swap candidate takes a higher spawn
3700    /// number than the incumbent that keeps serving beside it, so spawn order
3701    /// says nothing about which of them is still alive. `first_party` is the
3702    /// spawn's mark after the change; a lowering withdraws it here, in the
3703    /// same critical section as the epoch.
3704    pub(crate) fn publish_authority_change(
3705        &self,
3706        key: &SpawnKey,
3707        epoch: u64,
3708        alive: bool,
3709        first_party: bool,
3710    ) -> Result<Vec<AuthorityClosedRoute>, ForwardingError> {
3711        self.publish_approved_authority_change(key, epoch, alive, Some(first_party), None)
3712    }
3713
3714    /// Publish changed mark or approval facts with the new epoch. `None`
3715    /// leaves that fact unchanged; a dead spawn always loses its mark.
3716    pub(crate) fn publish_approved_authority_change(
3717        &self,
3718        key: &SpawnKey,
3719        epoch: u64,
3720        alive: bool,
3721        first_party: Option<bool>,
3722        approved: Option<&ApprovedDeclarations>,
3723    ) -> Result<Vec<AuthorityClosedRoute>, ForwardingError> {
3724        let mut inner = self.write_inner()?;
3725        if !alive {
3726            inner.spawn_approved.remove(key);
3727            inner.dead_spawns.insert(key.clone());
3728            prune_dead_spawn_tombstones_locked(&mut inner, key);
3729        } else if let Some(approved) = approved {
3730            inner.spawn_approved.insert(key.clone(), approved.clone());
3731        }
3732        // A record's epoch only rises; taking the larger keeps a published
3733        // epoch from ever moving backwards, whatever order publications land.
3734        let published = inner.spawn_epochs.entry(key.clone()).or_insert(epoch);
3735        *published = (*published).max(epoch);
3736        if !alive || first_party == Some(false) {
3737            inner.spawn_marks.remove(key);
3738        } else if first_party == Some(true) {
3739            inner.spawn_marks.insert(key.clone());
3740        }
3741        let older = |pair: &Option<AuthorityPair>| {
3742            pair.as_ref()
3743                .is_some_and(|pair| pair.key == *key && pair.epoch < epoch)
3744        };
3745        let selected = inner
3746            .client_to_module
3747            .iter()
3748            .filter(|(_, route)| older(&route.caller_authority) || older(&route.target_authority))
3749            .map(|(client_key, route)| (*client_key, route.client_epoch))
3750            .collect::<Vec<_>>();
3751        let mut closed = Vec::new();
3752        for (client_key, client_epoch) in selected {
3753            let Some(route) = inner.client_to_module.get(&client_key).cloned() else {
3754                continue;
3755            };
3756            let release = release_client_route_locked(&mut inner, client_key, client_epoch);
3757            self.record_route_release(&release);
3758            if let RouteRelease::Removed(module) = release {
3759                closed.push(AuthorityClosedRoute {
3760                    client: GoodbyeTarget {
3761                        connection_id: route.client_connection_id,
3762                        sink: route.client_sink.clone(),
3763                        negotiated_ver: route.client_negotiated_ver,
3764                        channel: route.client_channel,
3765                        epoch: route.client_epoch,
3766                        kind: GoodbyeTargetKind::Client,
3767                        module_id: Some(route.module_id.clone()),
3768                    },
3769                    module,
3770                    route,
3771                });
3772            }
3773        }
3774        Ok(closed)
3775    }
3776
3777    /// Publish a spawn's activated first-party mark, so `route.open` replies
3778    /// reserved from now on report it. The caller holds the spawn's authority
3779    /// record state. The epoch is unchanged and no route is closed: routes
3780    /// bound before activation keep the `first_party: false` they were
3781    /// attested with.
3782    pub(crate) fn publish_spawn_mark(&self, key: &SpawnKey) -> Result<(), ForwardingError> {
3783        self.write_inner()?.spawn_marks.insert(key.clone());
3784        Ok(())
3785    }
3786
3787    /// The epoch published for a spawn, for tests of the commit re-check.
3788    #[cfg(all(test, unix, feature = "test-support"))]
3789    pub(crate) fn published_spawn_epoch(&self, key: &SpawnKey) -> u64 {
3790        published_epoch_locked(&self.read_inner().unwrap(), key)
3791    }
3792
3793    /// The caller and target authority each live route opened by `client`
3794    /// recorded at commit.
3795    #[cfg(all(test, unix, feature = "test-support"))]
3796    pub(crate) fn route_authority_for_test(
3797        &self,
3798        client: ConnectionId,
3799    ) -> Vec<(Option<AuthorityPair>, Option<AuthorityPair>)> {
3800        self.read_inner()
3801            .unwrap()
3802            .client_to_module
3803            .iter()
3804            .filter(|(key, _)| key.connection_id == client)
3805            .map(|(_, route)| {
3806                (
3807                    route.caller_authority.clone(),
3808                    route.target_authority.clone(),
3809                )
3810            })
3811            .collect()
3812    }
3813
3814    /// The published tag of one scope, for tests of the commit re-check.
3815    #[cfg(test)]
3816    pub(crate) fn published_scope_tag(&self, owner: &str, scope_ref: &str) -> Option<ScopeTag> {
3817        self.read_inner()
3818            .ok()?
3819            .scope_tags
3820            .get(&(owner.to_string(), scope_ref.to_string()))
3821            .copied()
3822    }
3823
3824    fn record_route_release(&self, release: &RouteRelease) {
3825        match release {
3826            RouteRelease::Removed(_) => self.counters.increment_route_released_epoch_fenced(),
3827            RouteRelease::Stale => self.counters.increment_route_release_stale_skipped(),
3828            RouteRelease::Absent => {}
3829        }
3830    }
3831
3832    fn read_inner(
3833        &self,
3834    ) -> Result<InnerGuard<RwLockReadGuard<'_, ForwardingInner>>, ForwardingError> {
3835        self.inner
3836            .read()
3837            .map(InnerGuard::new)
3838            .map_err(|_| ForwardingError::Poisoned)
3839    }
3840
3841    fn write_inner(
3842        &self,
3843    ) -> Result<InnerGuard<RwLockWriteGuard<'_, ForwardingInner>>, ForwardingError> {
3844        self.inner
3845            .write()
3846            .map(InnerGuard::new)
3847            .map_err(|_| ForwardingError::Poisoned)
3848    }
3849
3850    fn lock_close_registry(&self) -> MutexGuard<'_, HashMap<ConnectionId, ConnectionCloseSender>> {
3851        self.close_registry
3852            .lock()
3853            .unwrap_or_else(|poisoned| poisoned.into_inner())
3854    }
3855}
3856
3857impl ForwardingInner {
3858    fn allocate_route_slots(
3859        &mut self,
3860        connection_id: ConnectionId,
3861        endpoint: ModuleEndpointId,
3862    ) -> Result<(u16, u32, u16, u32), ForwardingError> {
3863        let client_start = *self.next_client_channel.entry(connection_id).or_insert(1);
3864        let mut client_channel = client_start;
3865        let client_channel = loop {
3866            let key = ClientRouteKey {
3867                connection_id,
3868                channel: client_channel,
3869            };
3870            let eligible = !self.client_to_module.contains_key(&key)
3871                && !self.reserved_client.contains_key(&key)
3872                && self.client_slot_epochs.get(&key).copied().unwrap_or(0) < u32::MAX;
3873            if eligible {
3874                break client_channel;
3875            }
3876            client_channel = next_channel(client_channel);
3877            if client_channel == client_start {
3878                return Err(ForwardingError::ClientRouteChannelExhausted { connection_id });
3879            }
3880        };
3881
3882        let module_start = *self.next_module_channel.entry(endpoint).or_insert(1);
3883        let mut module_channel = module_start;
3884        let module_channel = loop {
3885            let key = ModuleRouteKey {
3886                endpoint,
3887                channel: module_channel,
3888            };
3889            let eligible = !self.module_to_client.contains_key(&key)
3890                && !self.reserved_module.contains_key(&key)
3891                && self.module_slot_epochs.get(&key).copied().unwrap_or(0) < u32::MAX;
3892            if eligible {
3893                break module_channel;
3894            }
3895            module_channel = next_channel(module_channel);
3896            if module_channel == module_start {
3897                return Err(ForwardingError::ModuleRouteChannelExhausted { endpoint });
3898            }
3899        };
3900
3901        let client_key = ClientRouteKey {
3902            connection_id,
3903            channel: client_channel,
3904        };
3905        let module_key = ModuleRouteKey {
3906            endpoint,
3907            channel: module_channel,
3908        };
3909        let client_epoch = self
3910            .client_slot_epochs
3911            .get(&client_key)
3912            .copied()
3913            .unwrap_or(0)
3914            + 1;
3915        let module_epoch = self
3916            .module_slot_epochs
3917            .get(&module_key)
3918            .copied()
3919            .unwrap_or(0)
3920            + 1;
3921        self.client_slot_epochs.insert(client_key, client_epoch);
3922        self.module_slot_epochs.insert(module_key, module_epoch);
3923        self.next_client_channel
3924            .insert(connection_id, next_channel(client_channel));
3925        self.next_module_channel
3926            .insert(endpoint, next_channel(module_channel));
3927        Ok((client_channel, client_epoch, module_channel, module_epoch))
3928    }
3929
3930    fn allocate_control_corr(
3931        &mut self,
3932        endpoint: ModuleEndpointId,
3933    ) -> Result<u64, ForwardingError> {
3934        let candidate = self.next_control_corr.get(&endpoint).copied().unwrap_or(1);
3935        if candidate == 0 {
3936            self.closing_connections.insert(endpoint.connection_id);
3937            return Err(ForwardingError::RelayCorrelationExhausted);
3938        }
3939        self.next_control_corr.insert(
3940            endpoint,
3941            if candidate == u64::MAX {
3942                0
3943            } else {
3944                candidate + 1
3945            },
3946        );
3947        Ok(candidate)
3948    }
3949}
3950
3951fn connection_has_client_routes_locked(
3952    inner: &ForwardingInner,
3953    connection_id: ConnectionId,
3954) -> bool {
3955    inner
3956        .client_to_module
3957        .keys()
3958        .any(|key| key.connection_id == connection_id)
3959        || inner
3960            .reserved_client
3961            .keys()
3962            .any(|key| key.connection_id == connection_id)
3963}
3964
3965fn check_module_connection_role_locked(
3966    inner: &ForwardingInner,
3967    connection_id: ConnectionId,
3968) -> Result<(), ForwardingError> {
3969    if inner.endpoint_by_connection.contains_key(&connection_id)
3970        || connection_has_client_routes_locked(inner, connection_id)
3971    {
3972        return Err(ForwardingError::ConnectionRoleConflict { connection_id });
3973    }
3974    Ok(())
3975}
3976
3977fn next_channel(channel: u16) -> u16 {
3978    let next = channel.wrapping_add(1);
3979    if next == 0 {
3980        1
3981    } else {
3982        next
3983    }
3984}
3985
3986fn endpoint_routes_locked(
3987    inner: &ForwardingInner,
3988    endpoint: ModuleEndpointId,
3989) -> Vec<EndpointRoute> {
3990    let drain_reason = inner.draining_endpoints.get(&endpoint).copied();
3991    let draining = drain_reason.is_some();
3992    let mut routes = inner
3993        .module_to_client
3994        .iter()
3995        .filter(|(module_key, _)| module_key.endpoint == endpoint)
3996        .map(|(_, route)| EndpointRoute {
3997            goodbye_target: GoodbyeTarget {
3998                connection_id: route.client_connection_id,
3999                sink: route.client_sink.clone(),
4000                negotiated_ver: route.client_negotiated_ver,
4001                channel: route.client_channel,
4002                epoch: route.client_epoch,
4003                kind: GoodbyeTargetKind::Client,
4004                module_id: Some(route.module_id.clone()),
4005            },
4006            principal: route.principal.clone(),
4007            accepts_close_reasons: route.accepts_close_reasons.clone(),
4008            bound_at: route.bound_at,
4009            draining,
4010            drain_reason,
4011        })
4012        .collect::<Vec<_>>();
4013    routes.sort_by_key(|route| {
4014        (
4015            route.goodbye_target.connection_id.get(),
4016            route.goodbye_target.channel,
4017            route.goodbye_target.epoch,
4018        )
4019    });
4020    routes
4021}
4022
4023/// Why a bind admitted under `scope` may no longer commit: its absolute
4024/// deadline has passed (whether or not a sweep has published that yet), or,
4025/// read from the published tags, `scope_ended` when the scope is gone or at
4026/// another epoch, `scope_changed` (retryable) when only its content moved.
4027fn scope_refusal_locked(inner: &ForwardingInner, scope: &BoundScope) -> Option<ErrorBody> {
4028    if let Some(expired) = scope.deadline_refusal() {
4029        return Some(expired);
4030    }
4031    let key = (scope.owner.clone(), scope.scope_ref.clone());
4032    match inner.scope_tags.get(&key) {
4033        Some(current) if *current == scope.tag => None,
4034        Some(current) if current.scope_epoch == scope.tag.scope_epoch => Some(ErrorBody::new(
4035            subc_protocol::error_codes::SCOPE_CHANGED,
4036            format!(
4037                "scope '{}' of {} changed while the route was being bound; re-open it",
4038                scope.scope_ref, scope.owner
4039            ),
4040        )),
4041        _ => Some(ErrorBody::new(
4042            subc_protocol::error_codes::SCOPE_ENDED,
4043            format!(
4044                "scope '{}' of {} at scope_epoch {} ended while the route was being bound",
4045                scope.scope_ref, scope.owner, scope.tag.scope_epoch
4046            ),
4047        )),
4048    }
4049}
4050
4051fn release_reserved_route_locked(
4052    inner: &mut ForwardingInner,
4053    client_key: ClientRouteKey,
4054    module_key: ModuleRouteKey,
4055) {
4056    if inner.reserved_client.get(&client_key).copied() == Some(module_key) {
4057        inner.reserved_client.remove(&client_key);
4058    }
4059    if inner.reserved_module.get(&module_key).copied() == Some(client_key) {
4060        inner.reserved_module.remove(&module_key);
4061    }
4062    inner.status.retain(|(key, _), _| *key != client_key);
4063}
4064
4065fn release_client_route_locked(
4066    inner: &mut ForwardingInner,
4067    client_key: ClientRouteKey,
4068    expected_epoch: u32,
4069) -> RouteRelease {
4070    let Some(route) = inner.client_to_module.get(&client_key) else {
4071        return RouteRelease::Absent;
4072    };
4073    if route.client_epoch != expected_epoch {
4074        return RouteRelease::Stale;
4075    }
4076    let route = inner
4077        .client_to_module
4078        .remove(&client_key)
4079        .expect("route checked under the same forwarding lock");
4080    route.flow.close();
4081    if let Some(scope) = &route.scope {
4082        scope.release_bind();
4083    }
4084    inner.module_to_client.remove(&ModuleRouteKey {
4085        endpoint: route.module_endpoint,
4086        channel: route.module_channel,
4087    });
4088    inner.operator_confirms.route_closed(ModuleRouteKey {
4089        endpoint: route.module_endpoint,
4090        channel: route.module_channel,
4091    });
4092    inner.status.remove(&(client_key, expected_epoch));
4093    RouteRelease::Removed(GoodbyeTarget {
4094        connection_id: route.module_endpoint.connection_id,
4095        sink: route.module_sink.clone(),
4096        negotiated_ver: route.module_negotiated_ver,
4097        channel: route.module_channel,
4098        epoch: route.module_epoch,
4099        kind: GoodbyeTargetKind::Module,
4100        module_id: Some(route.module_id.clone()),
4101    })
4102}
4103
4104fn release_module_route_locked(
4105    inner: &mut ForwardingInner,
4106    module_key: ModuleRouteKey,
4107    expected_epoch: u32,
4108) -> RouteRelease {
4109    let Some(route) = inner.module_to_client.get(&module_key) else {
4110        return RouteRelease::Absent;
4111    };
4112    if route.module_epoch != expected_epoch {
4113        return RouteRelease::Stale;
4114    }
4115    let route = inner
4116        .module_to_client
4117        .remove(&module_key)
4118        .expect("route checked under the same forwarding lock");
4119    inner.operator_confirms.route_closed(module_key);
4120    route.flow.close();
4121    if let Some(scope) = &route.scope {
4122        scope.release_bind();
4123    }
4124    let client_key = ClientRouteKey {
4125        connection_id: route.client_connection_id,
4126        channel: route.client_channel,
4127    };
4128    inner.client_to_module.remove(&client_key);
4129    inner.status.remove(&(client_key, route.client_epoch));
4130    RouteRelease::Removed(GoodbyeTarget {
4131        connection_id: route.client_connection_id,
4132        sink: route.client_sink.clone(),
4133        negotiated_ver: route.client_negotiated_ver,
4134        channel: route.client_channel,
4135        epoch: route.client_epoch,
4136        kind: GoodbyeTargetKind::Client,
4137        module_id: Some(route.module_id.clone()),
4138    })
4139}
4140
4141fn commit_route_locked(
4142    inner: &mut ForwardingInner,
4143    mut pending: PendingRouteBindRelayEntry,
4144) -> Result<Option<GoodbyeTarget>, ForwardingError> {
4145    let reservation = pending.reservation;
4146    if inner
4147        .closing_connections
4148        .contains(&reservation.client_key.connection_id)
4149    {
4150        return Err(ForwardingError::ConnectionClosing {
4151            connection_id: reservation.client_key.connection_id,
4152        });
4153    }
4154    let module_id = inner
4155        .module_id_by_endpoint
4156        .get(&reservation.module_key.endpoint)
4157        .cloned()
4158        .ok_or(ForwardingError::StaleModuleEndpoint)?;
4159    if inner
4160        .draining_endpoints
4161        .contains_key(&reservation.module_key.endpoint)
4162    {
4163        return Err(ForwardingError::ModuleReloading { module_id });
4164    }
4165    if pending.busy_refusals {
4166        let body = route_open_reply_body(
4167            &ClientControlResponse::RouteOpen {
4168                route_channel: reservation.client_key.channel,
4169                route_epoch: reservation.client_epoch,
4170                request_window: Some(pending.request_window),
4171                watch_window: pending.watch_window,
4172            },
4173            &pending.target_authority,
4174            &pending.incarnation,
4175        )?;
4176        pending.route_open_frame = Frame::build_with_version(
4177            pending.client_negotiated_ver,
4178            FrameType::Response,
4179            pending.route_open_frame.header.flags,
4180            0,
4181            0,
4182            pending.route_open_frame.header.corr,
4183            body,
4184        )
4185        .map_err(|err| ForwardingError::RouteOpenBuild(err.to_string()))?;
4186    }
4187    if inner.reserved_client.remove(&reservation.client_key) != Some(reservation.module_key)
4188        || inner.reserved_module.remove(&reservation.module_key) != Some(reservation.client_key)
4189    {
4190        return Err(ForwardingError::UnknownReservation {
4191            client_channel: reservation.client_key.channel,
4192            module_channel: reservation.module_key.channel,
4193        });
4194    }
4195    let module = inner
4196        .modules_by_id
4197        .get(&module_id)
4198        .filter(|module| module.endpoint == reservation.module_key.endpoint)
4199        .cloned()
4200        .ok_or(ForwardingError::StaleModuleEndpoint)?;
4201    let binding = Arc::new(RouteBinding {
4202        client_connection_id: reservation.client_key.connection_id,
4203        client_sink: pending.client_sink,
4204        client_negotiated_ver: pending.client_negotiated_ver,
4205        client_channel: reservation.client_key.channel,
4206        client_epoch: reservation.client_epoch,
4207        module_id,
4208        module_endpoint: reservation.module_key.endpoint,
4209        module_sink: module.sink,
4210        module_negotiated_ver: module.negotiated_ver,
4211        module_channel: reservation.module_key.channel,
4212        module_epoch: reservation.module_epoch,
4213        principal: pending.principal,
4214        harness: pending.harness,
4215        build_class: pending.build_class,
4216        operator_app: pending.operator_app,
4217        project_root: reservation.project_root.clone(),
4218        bound_at: Instant::now(),
4219        flow: Arc::new(if pending.busy_refusals {
4220            ChannelFlow::with_admission(pending.request_window, true, pending.watch_window)
4221        } else {
4222            ChannelFlow::new(pending.request_window)
4223        }),
4224        scope: pending.scope,
4225        caller_authority: pending.caller_authority,
4226        target_authority: pending.target_authority.pair().cloned(),
4227        accepts_close_reasons: pending.accepts_close_reasons,
4228    });
4229    inner
4230        .client_to_module
4231        .insert(reservation.client_key, Arc::clone(&binding));
4232    inner
4233        .module_to_client
4234        .insert(reservation.module_key, Arc::clone(&binding));
4235    let previous_published = inner
4236        .last_published_epoch
4237        .insert(reservation.client_key, reservation.client_epoch);
4238
4239    // This point is reachable only through an accepted route.bind acknowledgement.
4240    // Publish history before notifying the opener, so a subsequent
4241    // `scope.served_by` query sees the acknowledged bind.
4242    if let Some(scope) = &binding.scope {
4243        scope.record_served(&binding.module_id, module.verified_prefix_owner.as_deref());
4244    }
4245
4246    // Sending through the reserved slot cannot fail, but it reports a receiver
4247    // that closed after reservation and before this locked publication point.
4248    // The frame is stamped and charged to the queued-byte count here, when it
4249    // actually enters the queue, not when the slot was reserved.
4250    let client_writer_closed = pending.client_permit.send(pending.route_open_frame);
4251    if client_writer_closed {
4252        // Not gated on `relay_enqueued`: only a module ack reaches this
4253        // commit, which proves the module holds the binding, and `route.open`
4254        // sends nothing for a relay a reply already settled.
4255        let abandoned = abandoned_route_target(inner, &reservation);
4256        if let Some(route) = inner.client_to_module.remove(&reservation.client_key) {
4257            route.flow.close();
4258        }
4259        inner.module_to_client.remove(&reservation.module_key);
4260        inner
4261            .status
4262            .remove(&(reservation.client_key, reservation.client_epoch));
4263        match previous_published {
4264            Some(epoch) => {
4265                inner
4266                    .last_published_epoch
4267                    .insert(reservation.client_key, epoch);
4268            }
4269            None => {
4270                inner.last_published_epoch.remove(&reservation.client_key);
4271            }
4272        }
4273        let _ = pending.sender.send(RouteBindRelayOutcome::ModuleGone(
4274            "client egress closed during route publication".to_string(),
4275        ));
4276        return Ok(abandoned);
4277    }
4278
4279    if let Some(scope) = &binding.scope {
4280        scope.commit_presence();
4281    }
4282    let _ = pending.sender.send(RouteBindRelayOutcome::Accepted);
4283    Ok(None)
4284}
4285
4286/// What serves `module`'s endpoint: a prefix child, a supervised spawn's own
4287/// registration at its published epoch, or an unsupervised registration.
4288fn target_authority_locked(inner: &ForwardingInner, module: &ModuleConnection) -> TargetAuthority {
4289    if module.verified_prefix_owner.is_some() {
4290        return TargetAuthority::Prefix;
4291    }
4292    match inner
4293        .target_authority_by_connection
4294        .get(&module.endpoint.connection_id)
4295    {
4296        Some(record) => {
4297            let key = record.key();
4298            TargetAuthority::Spawn(
4299                AuthorityPair {
4300                    epoch: published_epoch_locked(inner, &key),
4301                    key: key.clone(),
4302                },
4303                inner
4304                    .spawn_approved
4305                    .get(&record.key())
4306                    .cloned()
4307                    .unwrap_or_else(ApprovedDeclarations::none_approved),
4308                inner.spawn_marks.contains(&key),
4309            )
4310        }
4311        None => TargetAuthority::Unsupervised,
4312    }
4313}
4314
4315fn published_epoch_locked(inner: &ForwardingInner, key: &SpawnKey) -> u64 {
4316    inner
4317        .spawn_epochs
4318        .get(key)
4319        .copied()
4320        .unwrap_or(crate::spawn_authority::INITIAL_AUTHORITY_EPOCH)
4321}
4322
4323/// Drop the epoch tombstones of `newest`'s module's earlier dead spawns that
4324/// no pending bind names any more. A tombstone a pending bind still names is
4325/// kept, so that bind is refused as stale at commit rather than compared with
4326/// the initial epoch an absent entry reads as. Live spawns are never in
4327/// `dead_spawns`, so their entries are never touched here.
4328fn prune_dead_spawn_tombstones_locked(inner: &mut ForwardingInner, newest: &SpawnKey) {
4329    let named = inner
4330        .pending_relays
4331        .values()
4332        .flat_map(|pending| {
4333            [
4334                pending.caller_authority.as_ref(),
4335                pending.target_authority.pair(),
4336            ]
4337        })
4338        .flatten()
4339        .map(|pair| pair.key.clone())
4340        .collect::<HashSet<_>>();
4341    let expired = inner
4342        .dead_spawns
4343        .iter()
4344        .filter(|dead| {
4345            dead.module_id == newest.module_id && *dead != newest && !named.contains(*dead)
4346        })
4347        .cloned()
4348        .collect::<Vec<_>>();
4349    for dead in expired {
4350        inner.dead_spawns.remove(&dead);
4351        inner.spawn_epochs.remove(&dead);
4352    }
4353}
4354
4355fn authority_stale_locked(inner: &ForwardingInner, pair: Option<&AuthorityPair>) -> bool {
4356    pair.is_some_and(|pair| published_epoch_locked(inner, &pair.key) > pair.epoch)
4357}
4358
4359fn spawn_connection_dead(inner: &ForwardingInner, connection: ConnectionId) -> bool {
4360    inner
4361        .spawn_connections
4362        .get(&connection)
4363        .is_some_and(|spawn| spawn.upgrade().is_none_or(|spawn| !spawn.launch_ready()))
4364}
4365
4366/// The live module connection registered under exactly `endpoint`, whichever
4367/// slot holds it: active, swap candidate, or superseded incumbent.
4368///
4369/// Resolving by endpoint rather than by module id is what keeps an incumbent
4370/// addressable after a swap promoted a candidate over its id. An endpoint that
4371/// is in none of the three (a stale one, replaced without a promotion) resolves
4372/// to nothing, as it always has.
4373fn module_connection_for_endpoint_locked(
4374    inner: &ForwardingInner,
4375    endpoint: ModuleEndpointId,
4376) -> Option<&ModuleConnection> {
4377    let module_id = inner.module_id_by_endpoint.get(&endpoint)?;
4378    inner
4379        .modules_by_id
4380        .get(module_id)
4381        .filter(|module| module.endpoint == endpoint)
4382        .or_else(|| {
4383            inner
4384                .candidates_by_id
4385                .get(module_id)
4386                .filter(|module| module.endpoint == endpoint)
4387        })
4388        .or_else(|| inner.superseded_endpoints.get(&endpoint))
4389}
4390
4391fn abandoned_route_target(
4392    inner: &ForwardingInner,
4393    reservation: &RouteReservation,
4394) -> Option<GoodbyeTarget> {
4395    let module_id = inner
4396        .module_id_by_endpoint
4397        .get(&reservation.module_key.endpoint)?;
4398    let module = module_connection_for_endpoint_locked(inner, reservation.module_key.endpoint)?;
4399    (module.endpoint == reservation.module_key.endpoint).then(|| GoodbyeTarget {
4400        connection_id: module.endpoint.connection_id,
4401        sink: module.sink.clone(),
4402        negotiated_ver: module.negotiated_ver,
4403        channel: reservation.module_key.channel,
4404        epoch: reservation.module_epoch,
4405        kind: GoodbyeTargetKind::Module,
4406        module_id: Some(module_id.clone()),
4407    })
4408}
4409
4410fn remove_module_connection_locked(
4411    inner: &mut ForwardingInner,
4412    endpoint: ModuleEndpointId,
4413) -> ConnectionCleanup {
4414    // Commit the disconnect before its routes are released, so their teardown
4415    // cannot replace module_closed with route_closed.
4416    inner.operator_confirms.module_closed(endpoint);
4417    inner.draining_endpoints.remove(&endpoint);
4418    inner.accepting_drains.remove(&endpoint);
4419    inner.daemon_drain_results.remove(&endpoint);
4420    let module_id = inner.module_id_by_endpoint.remove(&endpoint);
4421    if let Some(module_id) = module_id.as_ref() {
4422        if inner
4423            .modules_by_id
4424            .get(module_id)
4425            .is_some_and(|module| module.endpoint == endpoint)
4426        {
4427            inner.modules_by_id.remove(module_id);
4428        }
4429        if inner
4430            .candidates_by_id
4431            .get(module_id)
4432            .is_some_and(|module| module.endpoint == endpoint)
4433        {
4434            inner.candidates_by_id.remove(module_id);
4435        }
4436    }
4437    inner.superseded_endpoints.remove(&endpoint);
4438    inner.endpoint_by_connection.remove(&endpoint.connection_id);
4439    inner.next_module_channel.remove(&endpoint);
4440    inner.next_control_corr.remove(&endpoint);
4441    inner
4442        .health_probe_tombstones
4443        .retain(|(pending_endpoint, _), _| *pending_endpoint != endpoint);
4444    inner
4445        .module_slot_epochs
4446        .retain(|key, _| key.endpoint != endpoint);
4447    let reserved_module_keys: Vec<ModuleRouteKey> = inner
4448        .reserved_module
4449        .keys()
4450        .filter(|module_key| module_key.endpoint == endpoint)
4451        .copied()
4452        .collect();
4453    for module_key in reserved_module_keys {
4454        if let Some(client_key) = inner.reserved_module.get(&module_key).copied() {
4455            release_reserved_route_locked(inner, client_key, module_key);
4456        }
4457    }
4458
4459    let pending_keys: Vec<_> = inner
4460        .pending_relays
4461        .keys()
4462        .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
4463        .copied()
4464        .collect();
4465    let pending: Vec<_> = pending_keys
4466        .into_iter()
4467        .filter_map(|key| {
4468            inner
4469                .pending_relays
4470                .remove(&key)
4471                .map(|pending| (key, pending))
4472        })
4473        .collect();
4474    let abandoned_relays = u32::try_from(pending.len()).unwrap_or(u32::MAX);
4475    for (key, pending) in pending {
4476        // Recorded like every other removal without a reply, so a `route.open`
4477        // still sending the bind learns the relay was released rather than
4478        // settled by the module.
4479        if !pending.relay_enqueued {
4480            inner.relays_released_before_enqueue.insert(key);
4481        }
4482        let module_label = module_id.as_deref().unwrap_or("unknown");
4483        let _ = pending
4484            .sender
4485            .send(RouteBindRelayOutcome::ModuleGone(format!(
4486                "module '{module_label}' connection closed during route.bind relay"
4487            )));
4488    }
4489
4490    let pending_control_keys: Vec<_> = inner
4491        .pending_control_rpcs
4492        .keys()
4493        .filter(|(pending_endpoint, _)| *pending_endpoint == endpoint)
4494        .copied()
4495        .collect();
4496    let pending_control: Vec<_> = pending_control_keys
4497        .into_iter()
4498        .filter_map(|key| inner.pending_control_rpcs.remove(&key))
4499        .collect();
4500    for pending in pending_control {
4501        let module_label = module_id.as_deref().unwrap_or("unknown");
4502        let _ = pending
4503            .sender
4504            .send(ModuleControlRpcOutcome::ModuleGone(format!(
4505                "module '{module_label}' connection closed during module-control RPC"
4506            )));
4507    }
4508
4509    let module_routes = inner
4510        .module_to_client
4511        .iter()
4512        .filter(|(module_key, _)| module_key.endpoint == endpoint)
4513        .map(|(module_key, route)| (*module_key, route.module_epoch))
4514        .collect::<Vec<_>>();
4515    let mut released = Vec::with_capacity(module_routes.len());
4516    for (module_key, epoch) in module_routes {
4517        if let RouteRelease::Removed(target) = release_module_route_locked(inner, module_key, epoch)
4518        {
4519            released.push(target);
4520        }
4521    }
4522    ConnectionCleanup {
4523        released,
4524        abandoned_relays,
4525    }
4526}
4527
4528mod credit_ledger;
4529mod stalled_cancels;
4530use credit_ledger::CreditLedger;
4531pub(crate) use stalled_cancels::StalledCancels;
4532
4533#[derive(Debug, Default)]
4534struct ChannelFlowState {
4535    closed: bool,
4536    credits: CreditLedger,
4537    last_busy_warn: Option<tokio::time::Instant>,
4538    /// Requests whose client delivery ended with `frame_too_large` while the
4539    /// module may still be running them; see `refused_streams`.
4540    refused: std::collections::HashSet<u64>,
4541    /// Client frames waiting for this legacy route's credit.
4542    waiting: waiting_requests::WaitingRequests,
4543}
4544
4545#[path = "forwarding_refused_streams.rs"]
4546mod refused_streams;
4547#[path = "forwarding_upgrade.rs"]
4548mod upgrade;
4549#[path = "forwarding_waiting_requests.rs"]
4550mod waiting_requests;
4551pub(crate) use waiting_requests::LegacyArrival;
4552#[cfg(test)]
4553pub(crate) use waiting_requests::WAITING_REQUESTS_PER_ROUTE;
4554
4555/// Per-channel request-credit accounting shared by the client and module route halves.
4556#[derive(Debug)]
4557pub(crate) struct ChannelFlow {
4558    sem: Semaphore,
4559    window: usize,
4560    busy_refusals: bool,
4561    watch_sem: Option<Semaphore>,
4562    watch_window: Option<usize>,
4563    state: Mutex<ChannelFlowState>,
4564    /// How many entries `ChannelFlowState::refused` holds, read without the lock.
4565    refused_count: std::sync::atomic::AtomicUsize,
4566    /// How many frames wait in `ChannelFlowState::waiting`, and the wake-up
4567    /// for a reader waiting for room there.
4568    waiting_len: std::sync::atomic::AtomicUsize,
4569    waiting_room: tokio::sync::Notify,
4570}
4571
4572impl ChannelFlow {
4573    pub(crate) fn new(window: usize) -> Self {
4574        Self::with_admission(window, false, None)
4575    }
4576
4577    fn with_admission(window: usize, busy_refusals: bool, watch_window: Option<usize>) -> Self {
4578        debug_assert!(window > 0, "flow-control window must be non-zero");
4579        Self {
4580            sem: Semaphore::new(window),
4581            window,
4582            busy_refusals,
4583            watch_sem: watch_window.map(Semaphore::new),
4584            watch_window,
4585            state: Mutex::new(ChannelFlowState::default()),
4586            refused_count: std::sync::atomic::AtomicUsize::new(0),
4587            waiting_len: std::sync::atomic::AtomicUsize::new(0),
4588            waiting_room: tokio::sync::Notify::new(),
4589        }
4590    }
4591
4592    pub(crate) fn busy_refusals(&self) -> bool {
4593        self.busy_refusals
4594    }
4595
4596    fn try_acquire_tagged(&self, corr: u64, subscription: bool) -> RequestAdmission {
4597        let mut state = self
4598            .state
4599            .lock()
4600            .unwrap_or_else(|poisoned| poisoned.into_inner());
4601        if state.closed {
4602            return RequestAdmission::Stale;
4603        }
4604        let busy = |state: &ChannelFlowState| {
4605            RequestAdmission::Busy(subc_protocol::RouteBusyDetail {
4606                reason: "no_credit".into(),
4607                request_in_flight: state.credits.in_flight(),
4608                watch_in_flight: state.credits.subscriptions,
4609                request_window: self.window,
4610                watch_window: self.watch_window,
4611            })
4612        };
4613        let Ok(total) = self.sem.try_acquire() else {
4614            return busy(&state);
4615        };
4616        // A watch takes the total credit first. Dropping it on watch-lane
4617        // exhaustion rolls back before any ledger entry becomes visible.
4618        let watch = if subscription {
4619            if let Some(sem) = &self.watch_sem {
4620                match sem.try_acquire() {
4621                    Ok(permit) => Some(permit),
4622                    Err(_) => return busy(&state),
4623                }
4624            } else {
4625                None
4626            }
4627        } else {
4628            None
4629        };
4630        state.credits.acquire(corr, subscription, watch.is_some());
4631        total.forget();
4632        if let Some(watch) = watch {
4633            watch.forget();
4634        }
4635        RequestAdmission::Admitted
4636    }
4637
4638    pub(crate) fn should_warn_busy(&self) -> bool {
4639        let mut state = self
4640            .state
4641            .lock()
4642            .unwrap_or_else(|poisoned| poisoned.into_inner());
4643        let now = tokio::time::Instant::now();
4644        if state
4645            .last_busy_warn
4646            .is_some_and(|last| now.duration_since(last) < std::time::Duration::from_secs(60))
4647        {
4648            return false;
4649        }
4650        state.last_busy_warn = Some(now);
4651        true
4652    }
4653
4654    #[cfg(test)]
4655    pub(crate) async fn acquire(&self) -> Result<(), ChannelFlowClosed> {
4656        self.acquire_tagged(0, false).await
4657    }
4658
4659    pub(crate) async fn acquire_tagged(
4660        &self,
4661        corr: u64,
4662        subscription: bool,
4663    ) -> Result<(), ChannelFlowClosed> {
4664        let permit = self.sem.acquire().await.map_err(|_| ChannelFlowClosed)?;
4665        let mut state = self
4666            .state
4667            .lock()
4668            .unwrap_or_else(|poisoned| poisoned.into_inner());
4669        if state.closed {
4670            return Err(ChannelFlowClosed);
4671        }
4672        state.credits.acquire(corr, subscription, false);
4673        permit.forget();
4674        Ok(())
4675    }
4676
4677    #[cfg(test)]
4678    pub(crate) fn release(&self) {
4679        self.release_corr(0);
4680    }
4681
4682    pub(crate) fn release_corr(&self, corr: u64) {
4683        let mut state = self
4684            .state
4685            .lock()
4686            .unwrap_or_else(|poisoned| poisoned.into_inner());
4687        let Some(released) = state.credits.release(corr) else {
4688            // Protocol-conforming modules emit exactly one terminal per request.
4689            // This guard is a best-effort safety net against window growth, not a
4690            // security boundary against malicious peers.
4691            warn!(
4692                window = self.window,
4693                available = self.sem.available_permits(),
4694                "flow-control over-release ignored"
4695            );
4696            return;
4697        };
4698        if !self.sem.is_closed() {
4699            self.sem.add_permits(1);
4700        }
4701        if released.watch_credit {
4702            if let Some(watch_sem) = self.watch_sem.as_ref().filter(|sem| !sem.is_closed()) {
4703                watch_sem.add_permits(1);
4704            }
4705        }
4706    }
4707
4708    #[cfg(test)]
4709    pub(crate) fn in_flight(&self) -> usize {
4710        self.state
4711            .lock()
4712            .unwrap_or_else(|poisoned| poisoned.into_inner())
4713            .credits
4714            .in_flight()
4715    }
4716
4717    pub(crate) fn drain_in_flight(&self) -> usize {
4718        self.state
4719            .lock()
4720            .unwrap_or_else(|poisoned| poisoned.into_inner())
4721            .credits
4722            .drain_in_flight()
4723    }
4724
4725    pub(crate) fn drain_held_corrs(&self) -> Vec<u64> {
4726        self.state
4727            .lock()
4728            .unwrap_or_else(|poisoned| poisoned.into_inner())
4729            .credits
4730            .drain_held_corrs()
4731    }
4732
4733    #[cfg(test)]
4734    pub(crate) fn available_permits(&self) -> usize {
4735        self.sem.available_permits()
4736    }
4737
4738    pub(crate) fn begin_drain(&self) -> u32 {
4739        let mut state = self
4740            .state
4741            .lock()
4742            .unwrap_or_else(|poisoned| poisoned.into_inner());
4743        state.closed = true;
4744        self.sem.close();
4745        if let Some(sem) = &self.watch_sem {
4746            sem.close();
4747        }
4748        state.credits.capture_subscription_exclusions()
4749    }
4750
4751    pub(crate) fn close(&self) {
4752        let mut state = self
4753            .state
4754            .lock()
4755            .unwrap_or_else(|poisoned| poisoned.into_inner());
4756        state.closed = true;
4757        state.credits.close_cancel_tracking();
4758        self.sem.close();
4759        if let Some(sem) = &self.watch_sem {
4760            sem.close();
4761        }
4762        // Ends the wait of a task forwarding this route's waiting requests.
4763        self.waiting_room.notify_waiters();
4764    }
4765}
4766
4767#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4768pub(crate) struct ChannelFlowClosed;
4769
4770#[derive(Debug, Clone, PartialEq, Eq)]
4771pub(crate) enum RequestAdmission {
4772    DaemonUpgrade,
4773    Admitted,
4774    Busy(subc_protocol::RouteBusyDetail),
4775    ModuleReloading,
4776    Stale,
4777}
4778
4779impl fmt::Display for ChannelFlowClosed {
4780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4781        write!(f, "flow-control window closed")
4782    }
4783}
4784
4785impl Error for ChannelFlowClosed {}
4786
4787#[cfg(test)]
4788#[path = "route_busy_flow_tests.rs"]
4789mod route_busy_flow_tests;
4790
4791fn window_for(concurrency: &Concurrency) -> usize {
4792    match concurrency {
4793        Concurrency::Serial => 1,
4794        Concurrency::ModuleManaged => DEFAULT_MODULE_MANAGED_WINDOW,
4795        Concurrency::StatelessParallel => STATELESS_PARALLEL_WINDOW,
4796    }
4797}
4798
4799#[derive(Debug, Clone, PartialEq, Eq)]
4800pub enum ForwardingError {
4801    /// A connection cannot hold both client routes and a module endpoint, or
4802    /// replace a module identity while that endpoint is still registered.
4803    ConnectionRoleConflict {
4804        connection_id: ConnectionId,
4805    },
4806    NoModuleConnection,
4807    ModuleReloading {
4808        module_id: String,
4809    },
4810    StaleModuleEndpoint,
4811    UnknownReservation {
4812        client_channel: u16,
4813        module_channel: u16,
4814    },
4815    ClientRouteChannelExhausted {
4816        connection_id: ConnectionId,
4817    },
4818    ModuleRouteChannelExhausted {
4819        endpoint: ModuleEndpointId,
4820    },
4821    RelayCorrelationExhausted,
4822    ConnectionClosing {
4823        connection_id: ConnectionId,
4824    },
4825    ClientEgressClosed {
4826        connection_id: ConnectionId,
4827    },
4828    RouteOpenBuild(String),
4829    /// A swap candidate is already registered for this module id.
4830    CandidateSlotOccupied {
4831        module_id: String,
4832    },
4833    /// A registering module's HELLO_ACK could not be queued because its
4834    /// outbound queue is closed or full.
4835    ModuleEgressUnavailable {
4836        connection_id: ConnectionId,
4837    },
4838    HelloRegistrationRefused(&'static str),
4839    /// A capability-fenced bind's admitted target registration was replaced
4840    /// before the bind was reserved.
4841    TargetRegistrationChanged(String),
4842    /// `route.open`'s relay deadline passed before the bind could be reserved.
4843    RelayDeadlineElapsed,
4844    Poisoned,
4845}
4846
4847impl fmt::Display for ForwardingError {
4848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4849        match self {
4850            Self::ConnectionRoleConflict { connection_id } => write!(f, "connection {} already holds an incompatible role", connection_id.get()),
4851            Self::NoModuleConnection => write!(f, "no module connection is registered"),
4852            Self::ModuleReloading { module_id } => {
4853                write!(f, "module_id '{module_id}' is reloading")
4854            }
4855            Self::StaleModuleEndpoint => write!(f, "module connection generation is stale"),
4856            Self::UnknownReservation {
4857                client_channel,
4858                module_channel,
4859            } => write!(
4860                f,
4861                "route reservation client channel {client_channel} / module channel {module_channel} was not found"
4862            ),
4863            Self::ClientRouteChannelExhausted { connection_id } => write!(
4864                f,
4865                "no client route channels are available for connection {}",
4866                connection_id.get()
4867            ),
4868            Self::ModuleRouteChannelExhausted { endpoint } => write!(
4869                f,
4870                "no module route channels are available for endpoint generation {} on connection {}",
4871                endpoint.generation,
4872                endpoint.connection_id.get()
4873            ),
4874            Self::RelayCorrelationExhausted => {
4875                write!(f, "module control correlation ids are exhausted")
4876            }
4877            Self::ConnectionClosing { connection_id } => write!(
4878                f,
4879                "connection {} is closing and cannot accept route allocation",
4880                connection_id.get()
4881            ),
4882            Self::ClientEgressClosed { connection_id } => write!(
4883                f,
4884                "client connection {} egress is closed",
4885                connection_id.get()
4886            ),
4887            Self::RouteOpenBuild(message) => {
4888                write!(f, "failed to prebuild route.open response: {message}")
4889            }
4890            Self::CandidateSlotOccupied { module_id } => write!(
4891                f,
4892                "module_id '{module_id}' already has a swap candidate registered"
4893            ),
4894            Self::HelloRegistrationRefused(code) => write!(f, "module registration refused: {code}"),
4895            Self::ModuleEgressUnavailable { connection_id } => write!(
4896                f,
4897                "module connection {} egress is unavailable; HELLO_ACK could not be queued",
4898                connection_id.get()
4899            ),
4900            Self::TargetRegistrationChanged(message) => write!(f, "{message}"),
4901            Self::RelayDeadlineElapsed => write!(
4902                f,
4903                "the route.bind relay deadline passed while waiting for client egress"
4904            ),
4905            Self::Poisoned => write!(f, "forwarding table lock was poisoned"),
4906        }
4907    }
4908}
4909
4910impl Error for ForwardingError {}
4911
4912#[cfg(test)]
4913mod tests {
4914    use std::time::Duration;
4915
4916    use super::*;
4917    use tokio::sync::mpsc;
4918
4919    #[test]
4920    fn ordinary_long_running_request_is_not_excluded_from_drain() {
4921        let mut ledger = CreditLedger::default();
4922        ledger.acquire(1, false, false);
4923
4924        assert_eq!(ledger.capture_subscription_exclusions(), 0);
4925        assert_eq!(ledger.drain_in_flight(), 1);
4926    }
4927
4928    #[test]
4929    fn bit_set_subscription_is_excluded_and_counted() {
4930        let mut ledger = CreditLedger::default();
4931        ledger.acquire(1, true, false);
4932
4933        assert_eq!(ledger.capture_subscription_exclusions(), 1);
4934        assert_eq!(ledger.drain_in_flight(), 0);
4935    }
4936
4937    #[test]
4938    fn subscription_opened_after_drain_snapshot_is_not_excluded() {
4939        let mut ledger = CreditLedger::default();
4940        ledger.acquire(1, true, false);
4941        assert_eq!(ledger.capture_subscription_exclusions(), 1);
4942
4943        ledger.acquire(2, true, false);
4944
4945        assert_eq!(ledger.drain_in_flight(), 1);
4946    }
4947
4948    #[test]
4949    fn drain_with_no_subscriptions_reports_zero_excluded() {
4950        let mut ledger = CreditLedger::default();
4951        assert_eq!(ledger.capture_subscription_exclusions(), 0);
4952    }
4953
4954    fn test_hello_ack(corr: u64) -> Frame {
4955        Frame::build(
4956            FrameType::HelloAck,
4957            Flags::new(false, Priority::Passive, false),
4958            0,
4959            0,
4960            corr,
4961            Vec::new(),
4962        )
4963        .unwrap()
4964    }
4965
4966    /// An acked registration whose HELLO_ACK cannot be queued must leave no
4967    /// endpoint behind: a routable module that never got its ack would read a
4968    /// route.bind first and exit. A closed queue and a full one both refuse.
4969    #[test]
4970    fn acked_registration_that_cannot_queue_its_hello_ack_inserts_nothing() {
4971        let forwarding = ForwardingTable::default();
4972
4973        let (closed_tx, closed_rx) = mpsc::channel(8);
4974        drop(closed_rx);
4975        let closed = ConnectionId::new(1);
4976        assert_eq!(
4977            forwarding.register_module_connection_acked(
4978                closed,
4979                "closed".to_string(),
4980                2,
4981                Concurrency::ModuleManaged,
4982                FrameSink::new(closed_tx),
4983                ModuleHelloAck {
4984                    frame: test_hello_ack(1).into(),
4985                    verified_prefix_owner: None
4986                },
4987            ),
4988            Err(ForwardingError::ModuleEgressUnavailable {
4989                connection_id: closed
4990            })
4991        );
4992
4993        let (full_tx, _full_rx) = mpsc::channel(1);
4994        let full_sink = FrameSink::new(full_tx);
4995        full_sink.try_send(test_hello_ack(99)).unwrap();
4996        let full = ConnectionId::new(2);
4997        assert_eq!(
4998            forwarding.register_module_connection_acked(
4999                full,
5000                "full".to_string(),
5001                2,
5002                Concurrency::ModuleManaged,
5003                full_sink.clone(),
5004                ModuleHelloAck {
5005                    frame: test_hello_ack(2).into(),
5006                    verified_prefix_owner: None
5007                },
5008            ),
5009            Err(ForwardingError::ModuleEgressUnavailable {
5010                connection_id: full
5011            })
5012        );
5013        assert_eq!(
5014            forwarding.register_candidate_module_connection_acked(
5015                full,
5016                "full".to_string(),
5017                2,
5018                Concurrency::ModuleManaged,
5019                full_sink,
5020                test_hello_ack(3).into(),
5021            ),
5022            Err(ForwardingError::ModuleEgressUnavailable {
5023                connection_id: full
5024            })
5025        );
5026
5027        for (connection, module_id) in [(closed, "closed"), (full, "full")] {
5028            assert_eq!(
5029                forwarding
5030                    .module_endpoint_for_connection(connection)
5031                    .unwrap(),
5032                None
5033            );
5034            let (client_tx, _client_rx) = mpsc::channel(8);
5035            assert_eq!(
5036                forwarding
5037                    .begin_route_bind_relay_for_test(
5038                        ConnectionId::new(50),
5039                        FrameSink::new(client_tx),
5040                        1,
5041                        module_id,
5042                    )
5043                    .err(),
5044                Some(ForwardingError::NoModuleConnection)
5045            );
5046        }
5047        assert!(forwarding.read_inner().unwrap().candidates_by_id.is_empty());
5048    }
5049
5050    /// Both acked registration forms put the HELLO_ACK on the module's queue
5051    /// by the time the endpoint can be resolved.
5052    #[test]
5053    fn acked_registration_queues_the_hello_ack_first() {
5054        let forwarding = ForwardingTable::default();
5055        let (active_tx, mut active_rx) = mpsc::channel(8);
5056        forwarding
5057            .register_module_connection_acked(
5058                ConnectionId::new(1),
5059                "acked".to_string(),
5060                2,
5061                Concurrency::ModuleManaged,
5062                FrameSink::new(active_tx),
5063                ModuleHelloAck {
5064                    frame: test_hello_ack(11).into(),
5065                    verified_prefix_owner: None,
5066                },
5067            )
5068            .unwrap();
5069        let (candidate_tx, mut candidate_rx) = mpsc::channel(8);
5070        forwarding
5071            .register_candidate_module_connection_acked(
5072                ConnectionId::new(2),
5073                "acked".to_string(),
5074                2,
5075                Concurrency::ModuleManaged,
5076                FrameSink::new(candidate_tx),
5077                test_hello_ack(12).into(),
5078            )
5079            .unwrap();
5080
5081        let active_first = active_rx.try_recv().unwrap().frame;
5082        assert_eq!(active_first.header.ty, FrameType::HelloAck);
5083        assert_eq!(active_first.header.corr, 11);
5084        let candidate_first = candidate_rx.try_recv().unwrap().frame;
5085        assert_eq!(candidate_first.header.ty, FrameType::HelloAck);
5086        assert_eq!(candidate_first.header.corr, 12);
5087    }
5088
5089    #[test]
5090    fn multi_provider_route_limit_reports_per_client_exhaustion_without_affecting_second_client() {
5091        let forwarding = ForwardingTable::default();
5092        let module_connection = ConnectionId::new(10);
5093        let exhausted_client = ConnectionId::new(20);
5094        let second_client = ConnectionId::new(30);
5095        let (module_tx, _module_rx) = mpsc::channel(1);
5096        let endpoint = forwarding
5097            .register_module_connection(
5098                module_connection,
5099                "route-limit-provider".to_string(),
5100                1,
5101                Concurrency::ModuleManaged,
5102                FrameSink::new(module_tx),
5103            )
5104            .unwrap();
5105
5106        {
5107            let mut inner = forwarding.inner.write().unwrap();
5108            for channel in 1..=u16::MAX {
5109                inner.reserved_client.insert(
5110                    ClientRouteKey {
5111                        connection_id: exhausted_client,
5112                        channel,
5113                    },
5114                    ModuleRouteKey {
5115                        endpoint,
5116                        channel: 1,
5117                    },
5118                );
5119            }
5120        }
5121
5122        let (exhausted_tx, _exhausted_rx) = mpsc::channel(1);
5123        let err = forwarding
5124            .begin_route_bind_relay_for_test(
5125                exhausted_client,
5126                FrameSink::new(exhausted_tx),
5127                1,
5128                "route-limit-provider",
5129            )
5130            .unwrap_err();
5131        assert!(matches!(
5132            err,
5133            ForwardingError::ClientRouteChannelExhausted { connection_id }
5134                if connection_id == exhausted_client
5135        ));
5136
5137        let (second_tx, _second_rx) = mpsc::channel(1);
5138        let pending = forwarding
5139            .begin_route_bind_relay_for_test(
5140                second_client,
5141                FrameSink::new(second_tx),
5142                2,
5143                "route-limit-provider",
5144            )
5145            .unwrap();
5146        assert_eq!(pending.client_channel, 1);
5147    }
5148
5149    #[test]
5150    fn released_module_channels_are_reused_after_wrap_without_slot_leak() {
5151        let forwarding = ForwardingTable::default();
5152        let module_connection = ConnectionId::new(40);
5153        let client = ConnectionId::new(50);
5154        let (module_tx, _module_rx) = mpsc::channel(1);
5155        forwarding
5156            .register_module_connection(
5157                module_connection,
5158                "slot-reuse-provider".to_string(),
5159                1,
5160                Concurrency::ModuleManaged,
5161                FrameSink::new(module_tx),
5162            )
5163            .unwrap();
5164
5165        let (client_tx, _client_rx) = mpsc::channel(1);
5166        let client_sink = FrameSink::new(client_tx);
5167        let mut wrapped_channel = None;
5168        for index in 0..=usize::from(u16::MAX) {
5169            let pending = forwarding
5170                .begin_route_bind_relay_for_test(
5171                    client,
5172                    client_sink.clone(),
5173                    index as u64 + 1,
5174                    "slot-reuse-provider",
5175                )
5176                .unwrap();
5177            if index == usize::from(u16::MAX) {
5178                wrapped_channel = Some(pending.module_channel);
5179            }
5180            forwarding
5181                .abort_pending_relay(
5182                    pending.endpoint,
5183                    pending.corr,
5184                    RouteBindRelayOutcome::ModuleGone("test abort".to_string()),
5185                )
5186                .unwrap();
5187        }
5188
5189        assert_eq!(wrapped_channel, Some(1));
5190    }
5191
5192    #[test]
5193    fn cleanup_connection_prunes_stale_next_client_channel_cursor() {
5194        let forwarding = ForwardingTable::default();
5195        let client = ConnectionId::new(60);
5196        forwarding
5197            .inner
5198            .write()
5199            .unwrap()
5200            .next_client_channel
5201            .insert(client, 41);
5202
5203        let released = forwarding.cleanup_connection(client).unwrap();
5204
5205        assert!(released.is_empty());
5206        assert!(!forwarding
5207            .inner
5208            .read()
5209            .unwrap()
5210            .next_client_channel
5211            .contains_key(&client));
5212    }
5213
5214    #[test]
5215    fn stale_module_cleanup_preserves_fast_reconnect_successor() {
5216        let forwarding = ForwardingTable::default();
5217        let module_id = "fast-reconnect-provider";
5218        let first_connection = ConnectionId::new(70);
5219        let second_connection = ConnectionId::new(80);
5220        let (first_tx, _first_rx) = mpsc::channel(1);
5221        let first_endpoint = forwarding
5222            .register_module_connection(
5223                first_connection,
5224                module_id.to_string(),
5225                1,
5226                Concurrency::ModuleManaged,
5227                FrameSink::new(first_tx),
5228            )
5229            .unwrap();
5230        let (second_tx, _second_rx) = mpsc::channel(1);
5231        let second_endpoint = forwarding
5232            .register_module_connection(
5233                second_connection,
5234                module_id.to_string(),
5235                1,
5236                Concurrency::ModuleManaged,
5237                FrameSink::new(second_tx),
5238            )
5239            .unwrap();
5240        assert_ne!(first_endpoint, second_endpoint);
5241
5242        let released = forwarding.cleanup_connection(first_connection).unwrap();
5243
5244        assert!(released.is_empty());
5245        assert_eq!(
5246            forwarding
5247                .inner
5248                .read()
5249                .unwrap()
5250                .modules_by_id
5251                .get(module_id)
5252                .map(|module| module.endpoint),
5253            Some(second_endpoint)
5254        );
5255        assert!(forwarding.has_live_module_connection(module_id).unwrap());
5256        let control_rpc = forwarding
5257            .begin_module_control_rpc_for(
5258                module_id,
5259                "health.check",
5260                Instant::now() + Duration::from_secs(1),
5261            )
5262            .unwrap();
5263        assert_eq!(control_rpc.endpoint, second_endpoint);
5264    }
5265
5266    fn route_fixture(
5267        module_id: &str,
5268    ) -> (
5269        ForwardingTable,
5270        ConnectionId,
5271        ModuleEndpointId,
5272        ConnectionId,
5273        FrameSink,
5274        mpsc::Receiver<crate::router::OutboundFrame>,
5275    ) {
5276        let forwarding = ForwardingTable::default();
5277        let module_connection = ConnectionId::new(100);
5278        let client_connection = ConnectionId::new(200);
5279        let (module_tx, _module_rx) = mpsc::channel(8);
5280        let endpoint = forwarding
5281            .register_module_connection(
5282                module_connection,
5283                module_id.to_string(),
5284                2,
5285                Concurrency::ModuleManaged,
5286                FrameSink::new(module_tx),
5287            )
5288            .unwrap();
5289        let (client_tx, client_rx) = mpsc::channel(8);
5290        (
5291            forwarding,
5292            module_connection,
5293            endpoint,
5294            client_connection,
5295            FrameSink::new(client_tx),
5296            client_rx,
5297        )
5298    }
5299
5300    #[test]
5301    #[cfg(unix)]
5302    fn daemon_drain_gates_current_and_racing_provider_registrations() {
5303        let (forwarding, _, endpoint, _, sink, _) = route_fixture("provider");
5304        assert_eq!(
5305            forwarding.begin_daemon_drain().unwrap(),
5306            [("provider".to_string(), endpoint)]
5307        );
5308        assert!(forwarding.endpoint_is_draining(endpoint).unwrap());
5309        assert!(matches!(
5310            forwarding.register_module_connection(
5311                ConnectionId::new(300),
5312                "late-provider".into(),
5313                2,
5314                Concurrency::ModuleManaged,
5315                sink,
5316            ),
5317            Err(ForwardingError::ConnectionClosing { .. })
5318        ));
5319    }
5320
5321    #[test]
5322    #[cfg(unix)]
5323    fn daemon_drain_results_are_endpoint_fenced_and_removed_on_cleanup() {
5324        let (forwarding, connection, endpoint, _, _, _) = route_fixture("provider");
5325        assert_eq!(
5326            forwarding
5327                .daemon_drain_result_for_connection(connection)
5328                .unwrap(),
5329            None
5330        );
5331        forwarding
5332            .record_daemon_drain_result(endpoint, true)
5333            .unwrap();
5334        forwarding.begin_daemon_drain().unwrap();
5335        assert_eq!(
5336            forwarding
5337                .daemon_drain_result_for_connection(connection)
5338                .unwrap(),
5339            Some(false)
5340        );
5341        let replacement = ModuleEndpointId {
5342            generation: endpoint.generation + 1,
5343            ..endpoint
5344        };
5345        forwarding
5346            .record_daemon_drain_result(replacement, true)
5347            .unwrap();
5348        assert_eq!(
5349            forwarding
5350                .daemon_drain_result_for_connection(connection)
5351                .unwrap(),
5352            Some(false)
5353        );
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(true)
5362        );
5363        assert_eq!(
5364            forwarding
5365                .daemon_drain_result_for_connection(ConnectionId::new(300))
5366                .unwrap(),
5367            Some(false)
5368        );
5369        forwarding.cleanup_connection(connection).unwrap();
5370        forwarding
5371            .record_daemon_drain_result(endpoint, true)
5372            .unwrap();
5373        assert_eq!(
5374            forwarding
5375                .daemon_drain_result_for_connection(connection)
5376                .unwrap(),
5377            Some(false)
5378        );
5379        assert!(forwarding
5380            .read_inner()
5381            .unwrap()
5382            .daemon_drain_results
5383            .is_empty());
5384    }
5385
5386    #[test]
5387    #[cfg(unix)]
5388    fn late_bind_ack_during_daemon_drain_settles_without_leaking_or_closing_module() {
5389        let (forwarding, module_connection, endpoint, client_connection, sink, mut rx) =
5390            route_fixture("provider");
5391        let mut pending =
5392            begin_test_route(&forwarding, client_connection, sink.clone(), 1, "provider");
5393        assert_eq!(forwarding.reserved_route_count().unwrap(), (1, 1));
5394        forwarding.begin_daemon_drain().unwrap();
5395        let completion = forwarding
5396            .complete_pending_relay(
5397                module_connection,
5398                pending.corr,
5399                RouteBindRelayOutcome::Accepted,
5400            )
5401            .expect("draining admission is not a fatal module error");
5402        assert!(completion.settled);
5403        let abandoned = completion
5404            .abandoned
5405            .expect("late accepted bind needs a route GOODBYE");
5406        assert_eq!(abandoned.channel, pending.module_channel);
5407        assert!(matches!(pending.receiver.try_recv().unwrap(),
5408            RouteBindRelayOutcome::DaemonRejected(error) if error.code == "module_reloading"));
5409        assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
5410        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
5411        assert!(
5412            rx.try_recv().is_err(),
5413            "no route.open may be published during drain"
5414        );
5415        assert_eq!(
5416            forwarding
5417                .module_endpoint_for_connection(module_connection)
5418                .unwrap(),
5419            Some(endpoint)
5420        );
5421        assert!(
5422            !forwarding
5423                .complete_pending_relay(
5424                    module_connection,
5425                    pending.corr,
5426                    RouteBindRelayOutcome::Accepted,
5427                )
5428                .unwrap()
5429                .settled
5430        );
5431    }
5432
5433    fn test_ping(corr: u64) -> Frame {
5434        Frame::build(
5435            FrameType::Ping,
5436            Flags::new(false, Priority::Passive, false),
5437            0,
5438            0,
5439            corr,
5440            Vec::new(),
5441        )
5442        .unwrap()
5443    }
5444
5445    fn begin_test_route(
5446        forwarding: &ForwardingTable,
5447        client_connection: ConnectionId,
5448        client_sink: FrameSink,
5449        corr: u64,
5450        module_id: &str,
5451    ) -> PendingRouteBindRelay {
5452        forwarding
5453            .begin_route_bind_relay_for_test(client_connection, client_sink, corr, module_id)
5454            .unwrap()
5455    }
5456
5457    #[test]
5458    fn module_registration_and_client_reservation_are_mutually_exclusive_in_both_orders() {
5459        for candidate in [false, true] {
5460            for register_first in [false, true] {
5461                let (forwarding, module_connection, _, client_connection, sink, _rx) =
5462                    route_fixture("target");
5463                let register = || {
5464                    if candidate {
5465                        forwarding.register_candidate_module_connection(
5466                            client_connection,
5467                            "source".into(),
5468                            2,
5469                            Concurrency::ModuleManaged,
5470                            sink.clone(),
5471                        )
5472                    } else {
5473                        forwarding.register_module_connection(
5474                            client_connection,
5475                            "source".into(),
5476                            2,
5477                            Concurrency::ModuleManaged,
5478                            sink.clone(),
5479                        )
5480                    }
5481                };
5482                if register_first {
5483                    register().unwrap();
5484                    assert!(
5485                        forwarding
5486                            .begin_route_bind_relay_for_test(
5487                                client_connection,
5488                                sink.clone(),
5489                                1,
5490                                "target",
5491                            )
5492                            .is_err(),
5493                        "a deferred route.open cannot reserve after HELLO"
5494                    );
5495                    assert!(forwarding
5496                        .cleanup_connection(client_connection)
5497                        .unwrap()
5498                        .is_empty());
5499                } else {
5500                    let pending =
5501                        begin_test_route(&forwarding, client_connection, sink.clone(), 1, "target");
5502                    assert!(
5503                        register().is_err(),
5504                        "HELLO cannot register after a route reservation"
5505                    );
5506                    forwarding
5507                        .complete_pending_relay(
5508                            module_connection,
5509                            pending.corr,
5510                            RouteBindRelayOutcome::Accepted,
5511                        )
5512                        .unwrap();
5513                    assert_eq!(
5514                        forwarding
5515                            .cleanup_connection(client_connection)
5516                            .unwrap()
5517                            .len(),
5518                        1
5519                    );
5520                }
5521                assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
5522                assert_eq!(forwarding.active_binding_count().unwrap(), 0);
5523            }
5524        }
5525    }
5526
5527    /// A pending route.open reserves its queue slot with `reserve_owned` and
5528    /// sends its prebuilt response through that slot when the module accepts.
5529    /// A queue already holding many data frames (far more than the old 64-frame
5530    /// queue) must not stop the open from reserving or completing, and the
5531    /// response must be charged to the queue's byte count when it is sent.
5532    #[tokio::test]
5533    async fn pending_route_open_completes_behind_queued_data_frames() {
5534        assert_eq!(
5535            crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION,
5536            8,
5537            "the per-connection pending route.open limit is its own constant"
5538        );
5539        let (forwarding, module_connection, _endpoint, client, _unused_sink, _unused_rx) =
5540            route_fixture("open-behind-data");
5541        let (sink, mut client_rx) = crate::server::connection_egress();
5542        const DATA_FRAMES: usize = 1_000;
5543        let data = |corr: u64| {
5544            Frame::build(
5545                FrameType::StreamData,
5546                Flags::new(false, Priority::Interactive, false),
5547                9,
5548                1,
5549                corr,
5550                vec![b'x'; 200],
5551            )
5552            .unwrap()
5553        };
5554        for corr in 0..DATA_FRAMES as u64 {
5555            sink.try_send(data(corr)).unwrap();
5556        }
5557        let data_bytes = DATA_FRAMES * (subc_protocol::HEADER_LEN + 200);
5558        assert_eq!(sink.backlog().queued_bytes, data_bytes);
5559
5560        let pending = tokio::time::timeout(
5561            Duration::from_secs(5),
5562            forwarding.begin_route_bind_relay_for(
5563                client,
5564                sink.clone(),
5565                subc_protocol::PROTOCOL_VERSION,
5566                4_242,
5567                "open-behind-data",
5568                Principal::Direct,
5569                None,
5570                None,
5571                "fixture".into(),
5572                None,
5573                None,
5574                RouteAuthority::default(),
5575                Instant::now() + Duration::from_secs(60),
5576                false,
5577                None,
5578            ),
5579        )
5580        .await
5581        .expect("reserving the route.open slot must not wait behind data frames")
5582        .unwrap();
5583        forwarding
5584            .complete_pending_relay(
5585                module_connection,
5586                pending.corr,
5587                RouteBindRelayOutcome::Accepted,
5588            )
5589            .unwrap();
5590
5591        let backlog = sink.backlog();
5592        assert_eq!(backlog.queued_frames, DATA_FRAMES + 1);
5593        assert!(
5594            backlog.queued_bytes > data_bytes,
5595            "the route.open response must be counted in queued bytes: {backlog:?}"
5596        );
5597        for corr in 0..DATA_FRAMES as u64 {
5598            assert_eq!(client_rx.recv().await.unwrap().header.corr, corr);
5599        }
5600        let open = client_rx.recv().await.unwrap();
5601        assert_eq!(open.header.corr, 4_242);
5602        assert_eq!(open.header.ty, FrameType::Response);
5603        drop(open);
5604        assert_eq!(sink.backlog().queued_bytes, 0);
5605        assert_eq!(sink.backlog().queued_frames, 0);
5606    }
5607
5608    /// The drain-timeout line reports these numbers, so they must count the
5609    /// requests the drain is waiting on and no others: a route with nothing in
5610    /// flight is not a holdout, and a flagged subscription is excluded from the
5611    /// drain and so from the count.
5612    #[tokio::test]
5613    async fn drain_holdouts_count_held_requests_and_name_the_connection() {
5614        let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
5615            route_fixture("holdouts");
5616        let mut bound = |corr| {
5617            let route = begin_test_route(&forwarding, client, sink.clone(), corr, "holdouts");
5618            forwarding
5619                .complete_pending_relay(
5620                    module_connection,
5621                    route.corr,
5622                    RouteBindRelayOutcome::Accepted,
5623                )
5624                .unwrap();
5625            client_rx.try_recv().unwrap();
5626            match forwarding
5627                .lookup_data_route(client, route.client_channel, route.client_epoch)
5628                .unwrap()
5629            {
5630                DataRoute::Client(DataRouteState::Bound(binding)) => binding,
5631                other => panic!("expected live route, got {other:?}"),
5632            }
5633        };
5634        let holding = bound(61);
5635        let _idle = bound(62);
5636        holding.flow.acquire_tagged(7, false).await.unwrap();
5637        holding.flow.acquire_tagged(2, false).await.unwrap();
5638        holding.flow.acquire_tagged(3, true).await.unwrap();
5639        forwarding
5640            .begin_module_drain("holdouts", RouteCloseReason::Restart)
5641            .unwrap();
5642
5643        let holdouts = forwarding.endpoint_drain_holdouts(endpoint).unwrap();
5644        assert_eq!(
5645            holdouts,
5646            DrainHoldouts {
5647                requests: 2,
5648                routes: 1,
5649                total_routes: 2,
5650                top_connections: vec![(client.get(), 2)],
5651                // The held requests by the module's channel and corr, ascending,
5652                // without the excluded subscription (corr 3).
5653                held: vec![(holding.module_channel, 2), (holding.module_channel, 7)],
5654            }
5655        );
5656    }
5657
5658    #[test]
5659    fn endpoint_routes_keep_goodbye_targets_and_mark_draining_routes() {
5660        let (forwarding, module_connection, endpoint, client, sink, _client_rx) =
5661            route_fixture("census");
5662        let pending = begin_test_route(&forwarding, client, sink, 1, "census");
5663        forwarding
5664            .complete_pending_relay(
5665                module_connection,
5666                pending.corr,
5667                RouteBindRelayOutcome::Accepted,
5668            )
5669            .unwrap();
5670
5671        let routes = forwarding.endpoint_routes(endpoint).unwrap();
5672        assert_eq!(routes.len(), 1);
5673        assert!(matches!(routes[0].principal, Principal::Direct));
5674        assert_eq!(routes[0].goodbye_target.connection_id, client);
5675        assert_eq!(routes[0].goodbye_target.channel, pending.client_channel);
5676        assert_eq!(routes[0].goodbye_target.epoch, pending.client_epoch);
5677        assert!(!routes[0].draining);
5678
5679        forwarding
5680            .begin_module_drain("census", RouteCloseReason::Restart)
5681            .unwrap();
5682        let draining_routes = forwarding.endpoint_routes(endpoint).unwrap();
5683        assert_eq!(draining_routes.len(), 1);
5684        assert!(draining_routes[0].draining);
5685    }
5686
5687    #[test]
5688    fn aborted_reservation_consumes_both_epochs_and_reuse_advances_them() {
5689        let (forwarding, _, endpoint, client, sink, _client_rx) = route_fixture("epoch-abort");
5690        let first = begin_test_route(&forwarding, client, sink.clone(), 1, "epoch-abort");
5691        assert_eq!((first.client_epoch, first.module_epoch), (1, 1));
5692        forwarding
5693            .abort_pending_relay(
5694                first.endpoint,
5695                first.corr,
5696                RouteBindRelayOutcome::ModuleGone("abort".into()),
5697            )
5698            .unwrap();
5699        forwarding.inject_client_slot_epoch(client, first.client_channel, first.client_epoch);
5700        forwarding.inject_module_slot_epoch(endpoint, first.module_channel, first.module_epoch);
5701
5702        let second = begin_test_route(&forwarding, client, sink, 2, "epoch-abort");
5703        assert_eq!(second.client_channel, first.client_channel);
5704        assert_eq!(second.module_channel, first.module_channel);
5705        assert_eq!((second.client_epoch, second.module_epoch), (2, 2));
5706    }
5707
5708    #[test]
5709    fn stale_release_cannot_remove_reused_successor_and_status_is_epoch_fenced() {
5710        let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
5711            route_fixture("epoch-release");
5712        let first = begin_test_route(&forwarding, client, sink.clone(), 10, "epoch-release");
5713        forwarding
5714            .complete_pending_relay(
5715                module_connection,
5716                first.corr,
5717                RouteBindRelayOutcome::Accepted,
5718            )
5719            .unwrap();
5720        assert_eq!(client_rx.try_recv().unwrap().header.corr, 10);
5721        assert!(matches!(
5722            forwarding
5723                .release_client_route(client, first.client_channel, first.client_epoch)
5724                .unwrap(),
5725            RouteRelease::Removed(_)
5726        ));
5727        forwarding.inject_client_slot_epoch(client, first.client_channel, first.client_epoch);
5728        forwarding.inject_module_slot_epoch(endpoint, first.module_channel, first.module_epoch);
5729
5730        let second = begin_test_route(&forwarding, client, sink, 11, "epoch-release");
5731        forwarding
5732            .complete_pending_relay(
5733                module_connection,
5734                second.corr,
5735                RouteBindRelayOutcome::Accepted,
5736            )
5737            .unwrap();
5738        assert_eq!(client_rx.try_recv().unwrap().header.corr, 11);
5739        assert!(matches!(
5740            forwarding
5741                .release_client_route(client, second.client_channel, first.client_epoch)
5742                .unwrap(),
5743            RouteRelease::Stale
5744        ));
5745        assert!(!forwarding
5746            .cache_status(
5747                endpoint,
5748                second.module_channel,
5749                first.module_epoch,
5750                "stale".into(),
5751            )
5752            .unwrap());
5753        assert!(forwarding
5754            .cache_status(
5755                endpoint,
5756                second.module_channel,
5757                second.module_epoch,
5758                "current".into(),
5759            )
5760            .unwrap());
5761        match forwarding
5762            .route_poll_snapshot(client, second.client_channel, second.client_epoch)
5763            .unwrap()
5764        {
5765            RoutePollSnapshot::Bound { status, .. } => {
5766                assert_eq!(status.as_deref(), Some("current"));
5767            }
5768            RoutePollSnapshot::Absent => panic!("successor binding was removed"),
5769        }
5770        let counters = forwarding.counters().snapshot();
5771        assert_eq!(counters["route_released_epoch_fenced"], 1);
5772        assert_eq!(counters["route_release_stale_skipped"], 1);
5773    }
5774
5775    #[test]
5776    fn max_epoch_reservation_retires_only_that_slot() {
5777        let (forwarding, _, endpoint, client, sink, _client_rx) = route_fixture("epoch-max");
5778        forwarding.inject_client_slot_epoch(client, 7, u32::MAX - 1);
5779        forwarding.inject_module_slot_epoch(endpoint, 9, u32::MAX - 1);
5780        let final_use = begin_test_route(&forwarding, client, sink.clone(), 20, "epoch-max");
5781        assert_eq!(
5782            (final_use.client_channel, final_use.client_epoch),
5783            (7, u32::MAX)
5784        );
5785        assert_eq!(
5786            (final_use.module_channel, final_use.module_epoch),
5787            (9, u32::MAX)
5788        );
5789        forwarding
5790            .abort_pending_relay(
5791                endpoint,
5792                final_use.corr,
5793                RouteBindRelayOutcome::ModuleGone("abort".into()),
5794            )
5795            .unwrap();
5796        forwarding.inject_client_slot_epoch(client, 7, u32::MAX);
5797        forwarding.inject_module_slot_epoch(endpoint, 9, u32::MAX);
5798        let next = begin_test_route(&forwarding, client, sink, 21, "epoch-max");
5799        assert_ne!(next.client_channel, 7);
5800        assert_ne!(next.module_channel, 9);
5801        assert_eq!((next.client_epoch, next.module_epoch), (1, 1));
5802    }
5803
5804    #[test]
5805    fn bind_and_module_control_share_monotonic_corr_and_deadline_arbitration() {
5806        let (forwarding, module_connection, endpoint, client, sink, _client_rx) =
5807            route_fixture("corr-shared");
5808        let bind = begin_test_route(&forwarding, client, sink, 30, "corr-shared");
5809        assert_eq!(bind.corr, 1);
5810        forwarding
5811            .abort_pending_relay(
5812                endpoint,
5813                bind.corr,
5814                RouteBindRelayOutcome::ModuleGone("abort".into()),
5815            )
5816            .unwrap();
5817        let rpc = forwarding
5818            .begin_module_control_rpc_for(
5819                "corr-shared",
5820                "health.check",
5821                Instant::now() - Duration::from_millis(1),
5822            )
5823            .unwrap();
5824        assert_eq!(rpc.corr, 2);
5825        assert_eq!(
5826            forwarding
5827                .complete_module_control_rpc(
5828                    module_connection,
5829                    rpc.corr,
5830                    Some("health.check"),
5831                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
5832                        status: subc_protocol::session::HealthStatus::Ok,
5833                        detail: None,
5834                        metrics: None,
5835                    }),
5836                )
5837                .unwrap(),
5838            ModuleControlRpcCompletion::Settled
5839        );
5840        assert!(matches!(
5841            rpc.receiver.blocking_recv().unwrap(),
5842            ModuleControlRpcOutcome::DeadlineElapsed
5843        ));
5844    }
5845
5846    #[tokio::test(start_paused = true)]
5847    async fn health_probe_tombstone_ttl_removes_an_endpoint_that_stops_probing() {
5848        let (forwarding, _, endpoint, _, _, _) = route_fixture("tombstone-ttl");
5849        let probe_started_at = Instant::now();
5850        let rpc = forwarding
5851            .begin_health_probe_rpc_for(
5852                "tombstone-ttl",
5853                "health.check",
5854                probe_started_at,
5855                probe_started_at + Duration::from_secs(5),
5856            )
5857            .unwrap();
5858        assert!(forwarding
5859            .tombstone_health_probe_rpc(endpoint, rpc.corr)
5860            .unwrap());
5861        assert_eq!(forwarding.health_probe_tombstone_count().unwrap(), 1);
5862
5863        tokio::time::advance(HEALTH_PROBE_TOMBSTONE_TTL).await;
5864        tokio::task::yield_now().await;
5865
5866        assert_eq!(forwarding.health_probe_tombstone_count().unwrap(), 0);
5867    }
5868
5869    #[test]
5870    fn correlation_exhaustion_emits_max_once_then_closes_endpoint() {
5871        let (forwarding, _, endpoint, _, _, _) = route_fixture("corr-max");
5872        let mut close = forwarding.register_connection_close(endpoint.connection_id);
5873        forwarding.inject_control_corr(endpoint, u64::MAX);
5874        let final_rpc = forwarding
5875            .begin_module_control_rpc_for(
5876                "corr-max",
5877                "health.check",
5878                Instant::now() + Duration::from_secs(1),
5879            )
5880            .unwrap();
5881        assert_eq!(final_rpc.corr, u64::MAX);
5882        forwarding
5883            .cancel_module_control_rpc(endpoint, final_rpc.corr)
5884            .unwrap();
5885        assert!(matches!(
5886            forwarding.begin_module_control_rpc_for(
5887                "corr-max",
5888                "health.check",
5889                Instant::now() + Duration::from_secs(1),
5890            ),
5891            Err(ForwardingError::RelayCorrelationExhausted)
5892        ));
5893        assert!(close.try_recv().is_ok());
5894    }
5895
5896    #[test]
5897    fn publication_epoch_controls_delivery_failure_escalation() {
5898        fn setup_successor(
5899            commit_successor: Option<bool>,
5900        ) -> (ForwardingTable, ConnectionId, u16, u32) {
5901            let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
5902                route_fixture("escalation");
5903            let first = begin_test_route(&forwarding, client, sink.clone(), 40, "escalation");
5904            forwarding
5905                .complete_pending_relay(
5906                    module_connection,
5907                    first.corr,
5908                    RouteBindRelayOutcome::Accepted,
5909                )
5910                .unwrap();
5911            client_rx.try_recv().unwrap();
5912            assert!(matches!(
5913                forwarding
5914                    .release_client_route(client, first.client_channel, first.client_epoch)
5915                    .unwrap(),
5916                RouteRelease::Removed(_)
5917            ));
5918            if let Some(commit_successor) = commit_successor {
5919                forwarding.inject_client_slot_epoch(
5920                    client,
5921                    first.client_channel,
5922                    first.client_epoch,
5923                );
5924                forwarding.inject_module_slot_epoch(
5925                    endpoint,
5926                    first.module_channel,
5927                    first.module_epoch,
5928                );
5929                let successor = begin_test_route(&forwarding, client, sink, 41, "escalation");
5930                if commit_successor {
5931                    forwarding
5932                        .complete_pending_relay(
5933                            module_connection,
5934                            successor.corr,
5935                            RouteBindRelayOutcome::Accepted,
5936                        )
5937                        .unwrap();
5938                    client_rx.try_recv().unwrap();
5939                } else {
5940                    forwarding
5941                        .abort_pending_relay(
5942                            endpoint,
5943                            successor.corr,
5944                            RouteBindRelayOutcome::ModuleGone("abort".into()),
5945                        )
5946                        .unwrap();
5947                }
5948            }
5949            (forwarding, client, first.client_channel, first.client_epoch)
5950        }
5951
5952        let probe_sink = FrameSink::new(mpsc::channel(1).0);
5953        let (no_successor, client, channel, epoch) = setup_successor(None);
5954        let mut close = no_successor.register_connection_close(client);
5955        assert!(no_successor
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 (aborted, client, channel, epoch) = setup_successor(Some(false));
5970        let mut close = aborted.register_connection_close(client);
5971        assert!(aborted
5972            .escalate_client_delivery_failure(
5973                client,
5974                channel,
5975                epoch,
5976                CloseReason::new("delivery", "failed"),
5977                UndeliveredFrame {
5978                    module_id: None,
5979                    sink: &probe_sink,
5980                },
5981            )
5982            .unwrap());
5983        assert!(close.try_recv().is_ok());
5984
5985        let (published, client, channel, epoch) = setup_successor(Some(true));
5986        let mut close = published.register_connection_close(client);
5987        assert!(!published
5988            .escalate_client_delivery_failure(
5989                client,
5990                channel,
5991                epoch,
5992                CloseReason::new("delivery", "stale failure"),
5993                UndeliveredFrame {
5994                    module_id: None,
5995                    sink: &probe_sink,
5996                },
5997            )
5998            .unwrap());
5999        assert!(close.try_recv().is_err());
6000    }
6001
6002    #[test]
6003    fn route_concentration_separates_client_count_from_routes_per_client() {
6004        // The distinction this asserts is the one a bare connection count cannot
6005        // make: two connections holding one route each and one connection
6006        // holding two are the same total, and have opposite causes.
6007        let (forwarding, module_connection, _, client, sink, _client_rx) =
6008            route_fixture("concentration");
6009        assert_eq!(forwarding.client_route_concentration().unwrap(), (0, 0));
6010
6011        for corr in [70_u64, 71] {
6012            let pending =
6013                begin_test_route(&forwarding, client, sink.clone(), corr, "concentration");
6014            forwarding
6015                .complete_pending_relay(
6016                    module_connection,
6017                    pending.corr,
6018                    RouteBindRelayOutcome::Accepted,
6019                )
6020                .unwrap();
6021        }
6022
6023        // One connection, two routes — not two connections with a route each.
6024        assert_eq!(forwarding.active_binding_count().unwrap(), 2);
6025        assert_eq!(forwarding.client_route_concentration().unwrap(), (1, 2));
6026    }
6027
6028    #[test]
6029    fn cleanup_and_accepted_resolution_have_one_lock_winner() {
6030        let (forwarding, module_connection, _, client, sink, mut client_rx) =
6031            route_fixture("cleanup-race");
6032        let pending = begin_test_route(&forwarding, client, sink, 45, "cleanup-race");
6033        forwarding
6034            .mark_route_bind_relay_enqueued(pending.endpoint, pending.corr)
6035            .unwrap();
6036        let released = forwarding.cleanup_connection(client).unwrap();
6037        assert_eq!(released.len(), 1);
6038        let completion = forwarding
6039            .complete_pending_relay(
6040                module_connection,
6041                pending.corr,
6042                RouteBindRelayOutcome::Accepted,
6043            )
6044            .unwrap();
6045        assert!(!completion.settled);
6046        assert!(client_rx.try_recv().is_err());
6047        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6048
6049        let (forwarding, module_connection, _, client, sink, mut client_rx) =
6050            route_fixture("accepted-race");
6051        let pending = begin_test_route(&forwarding, client, sink, 46, "accepted-race");
6052        forwarding
6053            .complete_pending_relay(
6054                module_connection,
6055                pending.corr,
6056                RouteBindRelayOutcome::Accepted,
6057            )
6058            .unwrap();
6059        assert_eq!(client_rx.try_recv().unwrap().header.corr, 46);
6060        let released = forwarding.cleanup_connection(client).unwrap();
6061        assert_eq!(released.len(), 1);
6062        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6063    }
6064
6065    #[test]
6066    fn drain_marks_block_reservation_commit_and_live_request_admission_until_phase_two() {
6067        let (forwarding, module_connection, _, client, sink, mut client_rx) =
6068            route_fixture("drain-gap");
6069        let live = begin_test_route(&forwarding, client, sink.clone(), 47, "drain-gap");
6070        forwarding
6071            .complete_pending_relay(
6072                module_connection,
6073                live.corr,
6074                RouteBindRelayOutcome::Accepted,
6075            )
6076            .unwrap();
6077        client_rx.try_recv().unwrap();
6078        let binding = match forwarding
6079            .lookup_data_route(client, live.client_channel, live.client_epoch)
6080            .unwrap()
6081        {
6082            DataRoute::Client(DataRouteState::Bound(binding)) => binding,
6083            other => panic!("expected live route, got {other:?}"),
6084        };
6085
6086        let pending = begin_test_route(&forwarding, client, sink.clone(), 48, "drain-gap");
6087        forwarding
6088            .mark_route_bind_relay_enqueued(pending.endpoint, pending.corr)
6089            .unwrap();
6090        let control_rpc = forwarding
6091            .begin_module_control_rpc_for(
6092                "drain-gap",
6093                "health.check",
6094                Instant::now() + Duration::from_secs(1),
6095            )
6096            .unwrap();
6097        let target = forwarding
6098            .begin_module_drain("drain-gap", RouteCloseReason::Reload)
6099            .unwrap()
6100            .unwrap();
6101        assert!(matches!(
6102            control_rpc.receiver.blocking_recv().unwrap(),
6103            ModuleControlRpcOutcome::ModuleGone(_)
6104        ));
6105        assert_eq!(target.abandoned_bindings.len(), 1);
6106        assert!(binding.flow.sem.is_closed());
6107        assert!(
6108            !forwarding
6109                .complete_pending_relay(
6110                    module_connection,
6111                    pending.corr,
6112                    RouteBindRelayOutcome::Accepted,
6113                )
6114                .unwrap()
6115                .settled
6116        );
6117        assert!(matches!(
6118            forwarding.begin_route_bind_relay_for_test(client, sink, 49, "drain-gap"),
6119            Err(ForwardingError::ModuleReloading { .. })
6120        ));
6121        let released = forwarding
6122            .release_module_endpoint_routes(target.endpoint)
6123            .unwrap();
6124        assert_eq!(released.len(), 1);
6125        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6126    }
6127
6128    /// A client can be marked closing while its egress is still open: the daemon
6129    /// asks a connection to close (here through the production path, a module
6130    /// frame that its egress refused) and the connection loop tears down a moment
6131    /// later. A route.bind ack that lands inside that window is answered on the
6132    /// MODULE connection's frame handler, so resolving it must not produce an
6133    /// error -- an error there ends the module connection, and that connection
6134    /// carries every other client's routes to the module.
6135    #[test]
6136    fn accepted_bind_for_a_closing_client_releases_the_route_instead_of_failing_the_module() {
6137        let (forwarding, module_connection, endpoint, client, sink, mut client_rx) =
6138            route_fixture("closing-client");
6139
6140        // A published route on this client: escalate_client_delivery_failure only
6141        // marks a connection closing for a route it has already published.
6142        let live = begin_test_route(&forwarding, client, sink.clone(), 60, "closing-client");
6143        forwarding
6144            .complete_pending_relay(
6145                module_connection,
6146                live.corr,
6147                RouteBindRelayOutcome::Accepted,
6148            )
6149            .unwrap();
6150        client_rx.try_recv().unwrap();
6151
6152        // A second route.open from the same client, relayed and awaiting its ack.
6153        let pending = begin_test_route(&forwarding, client, sink.clone(), 61, "closing-client");
6154        forwarding
6155            .mark_route_bind_relay_enqueued(pending.endpoint, pending.corr)
6156            .unwrap();
6157
6158        // The window: closing, but the sink is still open.
6159        assert!(forwarding
6160            .escalate_client_delivery_failure(
6161                client,
6162                live.client_channel,
6163                live.client_epoch,
6164                CloseReason::new(
6165                    "module_to_client_delivery_failed",
6166                    "client egress refused a module frame",
6167                ),
6168                UndeliveredFrame {
6169                    module_id: None,
6170                    sink: &sink,
6171                },
6172            )
6173            .unwrap());
6174        assert!(!sink.is_closed());
6175
6176        let completion = forwarding
6177            .complete_pending_relay(
6178                module_connection,
6179                pending.corr,
6180                RouteBindRelayOutcome::Accepted,
6181            )
6182            .expect("a closing client must not turn a module's ack into an error");
6183
6184        assert!(completion.settled);
6185        let abandoned = completion
6186            .abandoned
6187            .expect("the module must be told to drop the binding it just created");
6188        assert_eq!(abandoned.connection_id, module_connection);
6189        assert_eq!(abandoned.channel, pending.module_channel);
6190        assert_eq!(abandoned.epoch, pending.module_epoch);
6191        assert!(matches!(abandoned.kind, GoodbyeTargetKind::Module));
6192        assert!(matches!(
6193            pending.receiver.blocking_recv().unwrap(),
6194            RouteBindRelayOutcome::ModuleGone(_)
6195        ));
6196        // No route was published to a client that is on its way out, and the
6197        // reserved handle pair went back.
6198        assert!(client_rx.try_recv().is_err());
6199        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
6200
6201        // The module endpoint is untouched: still live, and still able to take a
6202        // route from another client.
6203        assert!(forwarding
6204            .has_live_module_connection("closing-client")
6205            .unwrap());
6206        let cotenant = ConnectionId::new(201);
6207        let (cotenant_tx, mut cotenant_rx) = mpsc::channel(8);
6208        let cotenant_route = begin_test_route(
6209            &forwarding,
6210            cotenant,
6211            FrameSink::new(cotenant_tx),
6212            62,
6213            "closing-client",
6214        );
6215        assert_eq!(cotenant_route.endpoint, endpoint);
6216        forwarding
6217            .complete_pending_relay(
6218                module_connection,
6219                cotenant_route.corr,
6220                RouteBindRelayOutcome::Accepted,
6221            )
6222            .unwrap();
6223        assert_eq!(cotenant_rx.try_recv().unwrap().header.corr, 62);
6224        assert_eq!(forwarding.active_binding_count().unwrap(), 2);
6225    }
6226
6227    #[test]
6228    fn pending_route_permit_is_released_on_rejection_and_abort() {
6229        let forwarding = ForwardingTable::default();
6230        let module_connection = ConnectionId::new(300);
6231        let client = ConnectionId::new(301);
6232        let (module_tx, _module_rx) = mpsc::channel(1);
6233        let endpoint = forwarding
6234            .register_module_connection(
6235                module_connection,
6236                "permit".into(),
6237                2,
6238                Concurrency::ModuleManaged,
6239                FrameSink::new(module_tx),
6240            )
6241            .unwrap();
6242        let (client_tx, mut client_rx) = mpsc::channel(1);
6243        let sink = FrameSink::new(client_tx);
6244        let rejected = begin_test_route(&forwarding, client, sink.clone(), 50, "permit");
6245        assert!(sink.try_send(test_ping(999)).is_err());
6246        forwarding
6247            .complete_pending_relay(
6248                module_connection,
6249                rejected.corr,
6250                RouteBindRelayOutcome::Rejected(ErrorBody {
6251                    code: "no".into(),
6252                    message: "rejected".into(),
6253                    detail: None,
6254                }),
6255            )
6256            .unwrap();
6257        sink.try_send(test_ping(1000)).unwrap();
6258        assert_eq!(client_rx.try_recv().unwrap().header.corr, 1000);
6259
6260        let aborted = begin_test_route(&forwarding, client, sink.clone(), 51, "permit");
6261        assert!(sink.try_send(test_ping(1001)).is_err());
6262        forwarding
6263            .abort_pending_relay(
6264                endpoint,
6265                aborted.corr,
6266                RouteBindRelayOutcome::ModuleGone("abort".into()),
6267            )
6268            .unwrap();
6269        sink.try_send(test_ping(1002)).unwrap();
6270        assert_eq!(client_rx.try_recv().unwrap().header.corr, 1002);
6271
6272        let receiver_closed = begin_test_route(&forwarding, client, sink, 52, "permit");
6273        forwarding
6274            .mark_route_bind_relay_enqueued(endpoint, receiver_closed.corr)
6275            .unwrap();
6276        drop(client_rx);
6277        let completion = forwarding
6278            .complete_pending_relay(
6279                module_connection,
6280                receiver_closed.corr,
6281                RouteBindRelayOutcome::Accepted,
6282            )
6283            .unwrap();
6284        assert!(completion.abandoned.is_some());
6285        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
6286    }
6287
6288    /// Every connection teardown passes through `cleanup_connection`, and
6289    /// connection ids come from a monotonic counter that never hands an id out
6290    /// twice. If the closing mark survives teardown, the set grows by one entry
6291    /// per connection for the life of the daemon -- the self-watchdog alone
6292    /// reconnects once a minute.
6293    #[test]
6294    fn cleaned_up_connections_do_not_stay_in_the_closing_set() {
6295        let (forwarding, module_connection, _endpoint, _fixture_client, _sink, _rx) =
6296            route_fixture("closing-set-leak");
6297
6298        const CONNECTIONS: u64 = 32;
6299        for index in 0..CONNECTIONS {
6300            let client = ConnectionId::new(1000 + index);
6301            let (client_tx, _client_rx) = mpsc::channel(8);
6302            let route = begin_test_route(
6303                &forwarding,
6304                client,
6305                FrameSink::new(client_tx),
6306                index + 1,
6307                "closing-set-leak",
6308            );
6309            forwarding
6310                .complete_pending_relay(
6311                    module_connection,
6312                    route.corr,
6313                    RouteBindRelayOutcome::Accepted,
6314                )
6315                .unwrap();
6316            forwarding.cleanup_connection(client).unwrap();
6317        }
6318        forwarding.cleanup_connection(module_connection).unwrap();
6319
6320        assert_eq!(forwarding.closing_connection_count().unwrap(), 0);
6321    }
6322
6323    /// The closing mark exists to refuse new work for a connection that is on
6324    /// its way out but whose teardown has not run yet: the daemon asks the
6325    /// connection loop to end, and only when the loop reacts does
6326    /// `cleanup_connection` strip the connection's state. Inside that window an
6327    /// operation for the dying connection must still be refused; only after
6328    /// cleanup completes may the mark go.
6329    #[test]
6330    fn closing_connection_is_refused_new_work_until_cleanup_completes() {
6331        let (forwarding, module_connection, _endpoint, client, sink, mut client_rx) =
6332            route_fixture("closing-gate");
6333
6334        // A published route: escalate_client_delivery_failure only marks a
6335        // connection closing for a route it has already published.
6336        let live = begin_test_route(&forwarding, client, sink.clone(), 80, "closing-gate");
6337        forwarding
6338            .complete_pending_relay(
6339                module_connection,
6340                live.corr,
6341                RouteBindRelayOutcome::Accepted,
6342            )
6343            .unwrap();
6344        client_rx.try_recv().unwrap();
6345
6346        // Mark the connection closing through the production path without
6347        // running teardown, pinning the window open.
6348        assert!(forwarding
6349            .escalate_client_delivery_failure(
6350                client,
6351                live.client_channel,
6352                live.client_epoch,
6353                CloseReason::new(
6354                    "module_to_client_delivery_failed",
6355                    "client egress refused a module frame",
6356                ),
6357                UndeliveredFrame {
6358                    module_id: None,
6359                    sink: &sink,
6360                },
6361            )
6362            .unwrap());
6363        assert_eq!(forwarding.closing_connection_count().unwrap(), 1);
6364
6365        // A late route.open for the closing client is refused ...
6366        assert!(matches!(
6367            forwarding.begin_route_bind_relay_for_test(client, sink, 81, "closing-gate"),
6368            Err(ForwardingError::ConnectionClosing { connection_id })
6369                if connection_id == client
6370        ));
6371        // ... and so is a late attempt to register the connection as a module.
6372        let (late_tx, _late_rx) = mpsc::channel(1);
6373        assert!(matches!(
6374            forwarding.register_module_connection(
6375                client,
6376                "late-module".into(),
6377                2,
6378                Concurrency::ModuleManaged,
6379                FrameSink::new(late_tx),
6380            ),
6381            Err(ForwardingError::ConnectionClosing { connection_id })
6382                if connection_id == client
6383        ));
6384
6385        // Teardown is the point that lifts the mark: it has just removed every
6386        // per-connection entry under the same lock, so the gate has nothing
6387        // left to protect for this id.
6388        forwarding.cleanup_connection(client).unwrap();
6389        assert_eq!(forwarding.closing_connection_count().unwrap(), 0);
6390    }
6391
6392    mod audit_measurements {
6393        use super::*;
6394        include!("forwarding_audit_measurements.rs");
6395    }
6396
6397    mod waiting_requests {
6398        use super::*;
6399        include!("forwarding_waiting_requests_tests.rs");
6400    }
6401}
6402
6403/// Blue/green swap slots: a candidate registered beside the active endpoint,
6404/// promoted by `cutover_candidate`, with the old incumbent drained by endpoint.
6405#[cfg(test)]
6406mod swap_slot_tests {
6407    use std::time::Duration;
6408
6409    use super::*;
6410    use tokio::sync::mpsc;
6411
6412    const MODULE_ID: &str = "swapped";
6413
6414    struct SwapFixture {
6415        forwarding: ForwardingTable,
6416        incumbent_connection: ConnectionId,
6417        incumbent: ModuleEndpointId,
6418        candidate_connection: ConnectionId,
6419        candidate: ModuleEndpointId,
6420        _module_rxs: Vec<mpsc::Receiver<crate::router::OutboundFrame>>,
6421    }
6422
6423    fn swap_fixture() -> SwapFixture {
6424        let forwarding = ForwardingTable::default();
6425        let incumbent_connection = ConnectionId::new(100);
6426        let candidate_connection = ConnectionId::new(110);
6427        let (incumbent_tx, incumbent_rx) = mpsc::channel(8);
6428        let incumbent = forwarding
6429            .register_module_connection(
6430                incumbent_connection,
6431                MODULE_ID.to_string(),
6432                2,
6433                Concurrency::ModuleManaged,
6434                FrameSink::new(incumbent_tx),
6435            )
6436            .unwrap();
6437        let (candidate_tx, candidate_rx) = mpsc::channel(8);
6438        let candidate = forwarding
6439            .register_candidate_module_connection(
6440                candidate_connection,
6441                MODULE_ID.to_string(),
6442                2,
6443                Concurrency::ModuleManaged,
6444                FrameSink::new(candidate_tx),
6445            )
6446            .unwrap();
6447        SwapFixture {
6448            forwarding,
6449            incumbent_connection,
6450            incumbent,
6451            candidate_connection,
6452            candidate,
6453            _module_rxs: vec![incumbent_rx, candidate_rx],
6454        }
6455    }
6456
6457    fn client(
6458        raw: u64,
6459    ) -> (
6460        ConnectionId,
6461        FrameSink,
6462        mpsc::Receiver<crate::router::OutboundFrame>,
6463    ) {
6464        let (tx, rx) = mpsc::channel(8);
6465        (ConnectionId::new(raw), FrameSink::new(tx), rx)
6466    }
6467
6468    fn committed_endpoints(forwarding: &ForwardingTable) -> Vec<ModuleEndpointId> {
6469        forwarding
6470            .read_inner()
6471            .unwrap()
6472            .client_to_module
6473            .values()
6474            .map(|route| route.module_endpoint)
6475            .collect()
6476    }
6477
6478    #[test]
6479    fn candidate_is_unroutable_until_cutover_and_by_id_lookups_resolve_the_active_slot() {
6480        let fixture = swap_fixture();
6481        let forwarding = &fixture.forwarding;
6482        assert_ne!(fixture.incumbent, fixture.candidate);
6483
6484        // Every by-id consumer still resolves the incumbent.
6485        assert!(forwarding.has_live_module_connection(MODULE_ID).unwrap());
6486        assert!(!forwarding.module_is_draining(MODULE_ID).unwrap());
6487        let (client_connection, client_sink, _client_rx) = client(200);
6488        let pending = forwarding
6489            .begin_route_bind_relay_for_test(client_connection, client_sink, 1, MODULE_ID)
6490            .unwrap();
6491        assert_eq!(pending.endpoint, fixture.incumbent);
6492        let rpc = forwarding
6493            .begin_module_control_rpc_for(
6494                MODULE_ID,
6495                "health.check",
6496                Instant::now() + Duration::from_secs(1),
6497            )
6498            .unwrap();
6499        assert_eq!(rpc.endpoint, fixture.incumbent);
6500        let census = forwarding.route_census(Some(MODULE_ID)).unwrap();
6501        assert_eq!(census.len(), 1, "the census lists one endpoint per id");
6502
6503        // Connection-keyed lookups see the candidate, so its own frames resolve.
6504        assert_eq!(
6505            forwarding
6506                .module_endpoint_for_connection(fixture.candidate_connection)
6507                .unwrap(),
6508            Some(fixture.candidate)
6509        );
6510        assert_eq!(
6511            forwarding
6512                .module_id_for_connection(fixture.candidate_connection)
6513                .unwrap()
6514                .as_deref(),
6515            Some(MODULE_ID)
6516        );
6517
6518        // One candidate per id.
6519        let (other_tx, _other_rx) = mpsc::channel(1);
6520        assert_eq!(
6521            forwarding.register_candidate_module_connection(
6522                ConnectionId::new(120),
6523                MODULE_ID.to_string(),
6524                2,
6525                Concurrency::ModuleManaged,
6526                FrameSink::new(other_tx),
6527            ),
6528            Err(ForwardingError::CandidateSlotOccupied {
6529                module_id: MODULE_ID.to_string()
6530            })
6531        );
6532    }
6533
6534    /// The cutover linearization point. A relay reserved on the incumbent before
6535    /// cutover must never become a route on the incumbent, and every relay
6536    /// reserved after it must land on the promoted candidate.
6537    #[test]
6538    fn relay_reserved_before_cutover_never_commits_and_later_relays_land_on_the_candidate() {
6539        let fixture = swap_fixture();
6540        let forwarding = &fixture.forwarding;
6541        let (early_client, early_sink, _early_rx) = client(200);
6542        let mut early = forwarding
6543            .begin_route_bind_relay_for_test(early_client, early_sink, 1, MODULE_ID)
6544            .unwrap();
6545        assert_eq!(early.endpoint, fixture.incumbent);
6546        assert_eq!(
6547            forwarding
6548                .mark_route_bind_relay_enqueued(early.endpoint, early.corr)
6549                .unwrap(),
6550            RouteBindRelayMark::Marked
6551        );
6552
6553        let cutover = forwarding.cutover_candidate(MODULE_ID).unwrap().unwrap();
6554        assert_eq!(
6555            cutover,
6556            ForwardingCutover {
6557                promoted: fixture.candidate,
6558                incumbent: Some(fixture.incumbent),
6559            }
6560        );
6561
6562        // A route.open reserved after cutover goes to the promoted candidate.
6563        let (late_client, late_sink, _late_rx) = client(201);
6564        let late = forwarding
6565            .begin_route_bind_relay_for_test(late_client, late_sink, 2, MODULE_ID)
6566            .unwrap();
6567        assert_eq!(
6568            late.endpoint, fixture.candidate,
6569            "a route.open after cutover was reserved on the incumbent"
6570        );
6571
6572        // The incumbent acks the early relay after cutover.
6573        let completion = forwarding
6574            .complete_pending_relay(
6575                fixture.incumbent_connection,
6576                early.corr,
6577                RouteBindRelayOutcome::Accepted,
6578            )
6579            .expect("a superseded endpoint's ack is not an error on its connection");
6580        assert!(completion.settled);
6581        assert!(
6582            !committed_endpoints(forwarding).contains(&fixture.incumbent),
6583            "a relay reserved before cutover committed a route on the incumbent"
6584        );
6585        let goodbye = completion
6586            .abandoned
6587            .expect("the incumbent is told to drop the binding it just created");
6588        assert_eq!(goodbye.connection_id, fixture.incumbent_connection);
6589        assert_eq!(goodbye.channel, early.module_channel);
6590        assert_eq!(goodbye.epoch, early.module_epoch);
6591        assert_eq!(goodbye.kind, GoodbyeTargetKind::Module);
6592        match early.receiver.try_recv() {
6593            Ok(RouteBindRelayOutcome::DaemonRejected(body)) => {
6594                assert_eq!(body.code, "module_reloading")
6595            }
6596            other => panic!("expected a retryable module_reloading answer, got {other:?}"),
6597        }
6598        assert!(matches!(
6599            forwarding
6600                .lookup_data_route(early_client, early.client_channel, early.client_epoch)
6601                .unwrap(),
6602            DataRoute::Client(DataRouteState::Absent)
6603        ));
6604
6605        // The late relay commits on the candidate; only its pair stays reserved
6606        // until then.
6607        assert_eq!(forwarding.reserved_route_count().unwrap(), (1, 1));
6608        forwarding
6609            .complete_pending_relay(
6610                fixture.candidate_connection,
6611                late.corr,
6612                RouteBindRelayOutcome::Accepted,
6613            )
6614            .unwrap();
6615        assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
6616        assert_eq!(committed_endpoints(forwarding), vec![fixture.candidate]);
6617    }
6618
6619    #[test]
6620    fn endpoint_drain_after_cutover_drains_the_incumbent_not_the_promoted_candidate() {
6621        let fixture = swap_fixture();
6622        let forwarding = &fixture.forwarding;
6623        // One bound route and one in-flight relay on the incumbent.
6624        let (bound_client, bound_sink, _bound_rx) = client(200);
6625        let bound = forwarding
6626            .begin_route_bind_relay_for_test(bound_client, bound_sink, 1, MODULE_ID)
6627            .unwrap();
6628        forwarding
6629            .complete_pending_relay(
6630                fixture.incumbent_connection,
6631                bound.corr,
6632                RouteBindRelayOutcome::Accepted,
6633            )
6634            .unwrap();
6635        let (pending_client, pending_sink, _pending_rx) = client(201);
6636        let mut in_flight = forwarding
6637            .begin_route_bind_relay_for_test(pending_client, pending_sink, 2, MODULE_ID)
6638            .unwrap();
6639        forwarding
6640            .mark_route_bind_relay_enqueued(in_flight.endpoint, in_flight.corr)
6641            .unwrap();
6642
6643        let incumbent = forwarding
6644            .cutover_candidate(MODULE_ID)
6645            .unwrap()
6646            .unwrap()
6647            .incumbent
6648            .unwrap();
6649        let target = forwarding
6650            .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
6651            .unwrap()
6652            .expect("the superseded incumbent is still registered");
6653
6654        assert_eq!(target.endpoint, fixture.incumbent);
6655        assert!(forwarding.endpoint_is_draining(fixture.incumbent).unwrap());
6656        assert!(!forwarding.endpoint_is_draining(fixture.candidate).unwrap());
6657        assert!(!forwarding.module_is_draining(MODULE_ID).unwrap());
6658        assert_eq!(target.abandoned_bindings.len(), 1);
6659        assert_eq!(
6660            target.abandoned_bindings[0].channel,
6661            in_flight.module_channel
6662        );
6663        assert!(matches!(
6664            in_flight.receiver.try_recv(),
6665            Ok(RouteBindRelayOutcome::DaemonRejected(body)) if body.code == "module_reloading"
6666        ));
6667        assert_eq!(
6668            forwarding.endpoint_routes(fixture.incumbent).unwrap().len(),
6669            1,
6670            "the incumbent's bound route stays until its drain finishes"
6671        );
6672
6673        let (next_client, next_sink, _next_rx) = client(202);
6674        let next = forwarding
6675            .begin_route_bind_relay_for_test(next_client, next_sink, 3, MODULE_ID)
6676            .expect("the promoted candidate keeps accepting routes");
6677        assert_eq!(next.endpoint, fixture.candidate);
6678    }
6679
6680    /// An endpoint replaced WITHOUT a promotion (a successor registered over it
6681    /// as an ordinary active HELLO) is stale, not superseded, and its ack still
6682    /// fails the acking connection exactly as it did before swap slots existed:
6683    /// `StaleModuleEndpoint`, the reservation indexes already stripped, and the
6684    /// waiting client's sender dropped unanswered.
6685    #[test]
6686    fn stale_endpoint_ack_without_a_promotion_still_fails_as_before() {
6687        let forwarding = ForwardingTable::default();
6688        let first_connection = ConnectionId::new(70);
6689        let (first_tx, _first_rx) = mpsc::channel(8);
6690        forwarding
6691            .register_module_connection(
6692                first_connection,
6693                MODULE_ID.to_string(),
6694                2,
6695                Concurrency::ModuleManaged,
6696                FrameSink::new(first_tx),
6697            )
6698            .unwrap();
6699        let (client_connection, client_sink, _client_rx) = client(200);
6700        let mut pending = forwarding
6701            .begin_route_bind_relay_for_test(client_connection, client_sink, 1, MODULE_ID)
6702            .unwrap();
6703        let (second_tx, _second_rx) = mpsc::channel(8);
6704        forwarding
6705            .register_module_connection(
6706                ConnectionId::new(80),
6707                MODULE_ID.to_string(),
6708                2,
6709                Concurrency::ModuleManaged,
6710                FrameSink::new(second_tx),
6711            )
6712            .unwrap();
6713
6714        assert_eq!(
6715            forwarding
6716                .complete_pending_relay(
6717                    first_connection,
6718                    pending.corr,
6719                    RouteBindRelayOutcome::Accepted
6720                )
6721                .unwrap_err(),
6722            ForwardingError::StaleModuleEndpoint
6723        );
6724        assert!(committed_endpoints(&forwarding).is_empty());
6725        assert_eq!(forwarding.reserved_route_count().unwrap(), (0, 0));
6726        assert!(matches!(
6727            pending.receiver.try_recv(),
6728            Err(oneshot::error::TryRecvError::Closed)
6729        ));
6730    }
6731
6732    #[test]
6733    fn cleanup_releases_candidate_and_superseded_slots_without_touching_the_active_one() {
6734        // A candidate whose connection drops leaves the incumbent routable.
6735        let fixture = swap_fixture();
6736        let forwarding = &fixture.forwarding;
6737        assert!(forwarding
6738            .cleanup_connection(fixture.candidate_connection)
6739            .unwrap()
6740            .is_empty());
6741        assert_eq!(forwarding.cutover_candidate(MODULE_ID).unwrap(), None);
6742        let (client_connection, client_sink, _client_rx) = client(200);
6743        assert_eq!(
6744            forwarding
6745                .begin_route_bind_relay_for_test(client_connection, client_sink, 1, MODULE_ID)
6746                .unwrap()
6747                .endpoint,
6748            fixture.incumbent
6749        );
6750
6751        // After a cutover, the incumbent's teardown releases its own routes and
6752        // leaves the promoted candidate in place.
6753        let fixture = swap_fixture();
6754        let forwarding = &fixture.forwarding;
6755        let (bound_client, bound_sink, _bound_rx) = client(200);
6756        let bound = forwarding
6757            .begin_route_bind_relay_for_test(bound_client, bound_sink, 1, MODULE_ID)
6758            .unwrap();
6759        forwarding
6760            .complete_pending_relay(
6761                fixture.incumbent_connection,
6762                bound.corr,
6763                RouteBindRelayOutcome::Accepted,
6764            )
6765            .unwrap();
6766        forwarding.cutover_candidate(MODULE_ID).unwrap().unwrap();
6767        let released = forwarding
6768            .cleanup_connection(fixture.incumbent_connection)
6769            .unwrap();
6770        assert_eq!(released.len(), 1);
6771        assert_eq!(released[0].connection_id, bound_client);
6772        assert!(forwarding
6773            .read_inner()
6774            .unwrap()
6775            .superseded_endpoints
6776            .is_empty());
6777        assert!(forwarding.has_live_module_connection(MODULE_ID).unwrap());
6778        let (next_client, next_sink, _next_rx) = client(201);
6779        assert_eq!(
6780            forwarding
6781                .begin_route_bind_relay_for_test(next_client, next_sink, 2, MODULE_ID)
6782                .unwrap()
6783                .endpoint,
6784            fixture.candidate
6785        );
6786    }
6787}