Skip to main content

subc_daemon/control/
route_open.rs

1use super::*;
2
3/// How long subc waits for a module to ack a relayed route.bind before returning
4/// `module_timeout`. The ack waits on the module's own configure, which for AFT
5/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
6/// and DB-open work — on a cold page cache or a large repo that legitimately
7/// exceeds a couple of seconds. The default is generous because rejecting a VALID
8/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
9/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
10pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
11
12/// How many CONSECUTIVE full-budget relay timeouts against one target module
13/// open that module's bind-relay breaker.
14///
15/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
16/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
17/// so three consecutive full-budget timeouts take ~36s to observe: every client
18/// whose open contributed to opening the breaker had already given up on its
19/// own. That is what makes opening the breaker unable to turn a call that would
20/// have succeeded into a refusal — it can only make an already-failing module
21/// fail faster.
22///
23/// Two would be reachable inside one default deadline. One would convict a
24/// module on a single cold-cache bind, which is exactly the valid-but-slow case
25/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
26pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
27
28/// How long a module's bind-relay breaker stays open before exactly one
29/// `route.open` is let through as a probe.
30///
31/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
32/// re-pays a full-budget stall almost continuously, and the breaker stops being
33/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
34/// deadline: a client that starts retrying after the module recovers has to get
35/// a probe opportunity inside its own deadline, or the breaker converts a
36/// recovered module into a failed call — the failure it exists to prevent,
37/// pointed the other way.
38///
39/// 20s sits between those with room on both sides, and it caps what a wedged
40/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
41/// rather than one per `route.open` per connection. The stall that motivated
42/// this, with its measurements, is written up in
43/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
44/// waited the whole budget out.
45pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
46
47/// Refusal labels passed to `observe_route_open_refusal` that mean the target
48/// module is not serving right now, and so open or extend an outage in the
49/// route outage tracker. Every one of them is only reachable after the target
50/// was found in the registry, which is what keeps an arbitrary client-chosen
51/// id from ever creating tracker state.
52///
53/// Deliberately absent: `not_registered` and `removed` (the id may be
54/// anything a client sent, and a removed module is gone on purpose),
55/// `protocol_none` (such a module never serves routes, so nothing is out),
56/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
57/// capability and admission-facts refusals (they refuse the caller, not a
58/// module outage), and `relay_reservation_failed` (its code ranges over
59/// capacity limits as well as a vanished connection). Capacity, breaker,
60/// relay-timeout and module-rejection refusals do not pass through that
61/// function at all; the breaker logs its own transitions.
62///
63/// The two not-serving refusals that bypass that function record themselves
64/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
65/// `required_capability_unprovided` is not tracked: the module itself is up,
66/// and the outage belongs to the missing provider.
67const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
68    "reloading",
69    "supervisor_not_live",
70    "registration_not_active",
71    "no_forwarding_connection",
72    "relay_send_failed",
73];
74
75pub(super) struct RouteOpenRequest {
76    pub(super) target: RouteTarget,
77    pub(super) identity: BindIdentity,
78    pub(super) consumer_identity: Option<ConsumerIdentity>,
79    pub(super) consumer_capabilities: Option<Vec<String>>,
80    pub(super) role_versions: Option<BTreeMap<String, String>>,
81    pub(super) busy_refusals: Option<bool>,
82    pub(super) admission_facts: Option<serde_json::Value>,
83    pub(super) scope: Option<ScopeSelector>,
84    pub(super) accepts_close_reasons: Option<Vec<String>>,
85}
86
87#[derive(Clone, Copy)]
88enum RouteOpenPhase {
89    Admission,
90    ProjectRoot,
91    EgressReservation,
92    BindSend,
93    BindAckWait,
94}
95
96/// Store elapsed time for each route-open phase, including attempts that end
97/// in an early refusal or backend error. Admission also includes rechecks and
98/// commit bookkeeping performed between the other timed phases.
99pub(super) struct RouteOpenTimings {
100    pub(super) module_id: String,
101    pub(super) principal: String,
102    pub(super) admission: Duration,
103    pub(super) project_root: Duration,
104    pub(super) egress_reservation: Duration,
105    pub(super) bind_send: Duration,
106    pub(super) bind_ack_wait: Duration,
107    phase: Option<RouteOpenPhase>,
108    phase_started_at: Instant,
109}
110
111impl RouteOpenTimings {
112    pub(super) fn new() -> Self {
113        Self {
114            module_id: String::new(),
115            // Refusals before attestation must not claim a verified principal.
116            principal: "unresolved".to_string(),
117            admission: Duration::ZERO,
118            project_root: Duration::ZERO,
119            egress_reservation: Duration::ZERO,
120            bind_send: Duration::ZERO,
121            bind_ack_wait: Duration::ZERO,
122            phase: Some(RouteOpenPhase::Admission),
123            phase_started_at: Instant::now(),
124        }
125    }
126
127    pub(super) fn finish(&mut self) {
128        let elapsed = self.phase_started_at.elapsed();
129        match self.phase.take() {
130            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
131            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
132            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
133            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
134            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
135            None => {}
136        }
137    }
138
139    fn enter(&mut self, phase: RouteOpenPhase) {
140        self.finish();
141        self.phase = Some(phase);
142        self.phase_started_at = Instant::now();
143    }
144}
145
146struct RouteBindReservationGuard {
147    forwarding: Arc<ForwardingTable>,
148    endpoint: ModuleEndpointId,
149    relay_corr: u64,
150    armed: bool,
151}
152
153impl RouteBindReservationGuard {
154    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
155        Self {
156            forwarding,
157            endpoint,
158            relay_corr,
159            armed: true,
160        }
161    }
162
163    fn release_and_disarm(&mut self) {
164        if !self.armed {
165            return;
166        }
167        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
168            self.endpoint,
169            self.relay_corr,
170            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
171        ) {
172            send_goodbye_target_best_effort(
173                &self.forwarding.counters(),
174                &target,
175                "canceled route.bind",
176            );
177        }
178        self.armed = false;
179    }
180
181    fn disarm(&mut self) {
182        self.armed = false;
183    }
184}
185
186impl Drop for RouteBindReservationGuard {
187    fn drop(&mut self) {
188        self.release_and_disarm();
189    }
190}
191
192/// Per-target-module circuit breaker around the `route.bind` relay.
193///
194/// The connection reader is serial per connection, so a module whose `on_bind`
195/// sits on the ack blocks every LATER frame on the connections that call it,
196/// including calls to unrelated modules. This does not make any module's bind
197/// fast; it stops the daemon paying the full budget again and again for a
198/// condition it has already observed.
199///
200/// State is keyed by TARGET MODULE and shared by every connection: a wedged
201/// module wedges everyone, so what one connection learned should protect the
202/// rest.
203///
204/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
205/// relay to that module has actually timed out, and is removed again when a
206/// relay is accepted or the module reconnects, so it cannot grow with traffic
207/// or with modules that behave.
208///
209/// # Why a `std` mutex here is not the head-of-line defect again
210///
211/// Acquisition never awaits. The critical section is a hash lookup plus a few
212/// integer updates, with no I/O and no `.await` inside it, so a reader task
213/// cannot be descheduled behind it the way it can behind
214/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
215/// primitive, held for the same kind of work, as the refusal counter this very
216/// path already increments.
217///
218/// It is also NOT on the data-plane splice path: only `route.open` and module
219/// registration touch it, so bound-route frames gain no state check and no
220/// contention.
221#[derive(Debug, Clone, Default)]
222pub(crate) struct RouteBindBreakers {
223    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
224}
225
226#[derive(Debug, Clone, Default)]
227pub(crate) struct RouteBindConcurrency {
228    state: Arc<Mutex<RouteBindConcurrencyState>>,
229}
230
231#[derive(Debug, Default)]
232struct RouteBindConcurrencyState {
233    modules: HashMap<String, usize>,
234    upgrade_producers: Option<tokio::sync::watch::Sender<usize>>,
235}
236
237pub(super) struct RouteBindConcurrencyGuard {
238    concurrency: RouteBindConcurrency,
239    module_id: String,
240}
241
242impl RouteBindConcurrency {
243    /// Admit without waiting. Waiting here would move the bind stall from the
244    /// module reply to a semaphore and restore reader head-of-line blocking.
245    pub(super) fn try_admit(
246        &self,
247        module_id: &str,
248        limit: usize,
249    ) -> Result<RouteBindConcurrencyGuard, usize> {
250        let mut state = self
251            .state
252            .lock()
253            .expect("route.bind concurrency mutex poisoned");
254        let in_flight = state.modules.entry(module_id.to_string()).or_default();
255        if *in_flight >= limit {
256            return Err(*in_flight);
257        }
258        *in_flight += 1;
259        if let Some(producers) = &state.upgrade_producers {
260            producers.send_modify(|count| *count += 1);
261        }
262        Ok(RouteBindConcurrencyGuard {
263            concurrency: self.clone(),
264            module_id: module_id.to_string(),
265        })
266    }
267
268    #[cfg(any(target_os = "linux", target_os = "macos"))]
269    pub(super) fn track_upgrade_producers(&self) -> tokio::sync::watch::Receiver<usize> {
270        let mut state = self
271            .state
272            .lock()
273            .expect("route.bind concurrency mutex poisoned");
274        let (sender, receiver) = tokio::sync::watch::channel(state.modules.values().sum());
275        state.upgrade_producers = Some(sender);
276        receiver
277    }
278
279    #[cfg(any(target_os = "linux", target_os = "macos"))]
280    pub(crate) fn clear_upgrade_producers(&self) {
281        self.state
282            .lock()
283            .expect("route.bind concurrency mutex poisoned")
284            .upgrade_producers = None;
285    }
286}
287
288impl Drop for RouteBindConcurrencyGuard {
289    fn drop(&mut self) {
290        let mut state = self
291            .concurrency
292            .state
293            .lock()
294            .expect("route.bind concurrency mutex poisoned");
295        let remove = {
296            let in_flight = state
297                .modules
298                .get_mut(&self.module_id)
299                .expect("admitted route.bind has a concurrency entry");
300            *in_flight -= 1;
301            *in_flight == 0
302        };
303        if remove {
304            state.modules.remove(&self.module_id);
305        }
306        if let Some(producers) = &state.upgrade_producers {
307            producers.send_modify(|count| *count -= 1);
308        }
309    }
310}
311
312#[derive(Debug, Default)]
313struct ModuleBreakerState {
314    /// Relay timeouts observed with no accepted relay in between.
315    consecutive_timeouts: u32,
316    /// `Some` while the breaker is open: the instant the cooldown expires and
317    /// the next arrival may probe. `None` means closed.
318    cooldown_until: Option<Instant>,
319    /// A half-open probe has been admitted and has not settled yet. This is
320    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
321    /// that read the cooldown, so concurrent opens arriving at the moment the
322    /// cooldown expires cannot all decide that they are the probe.
323    probe_in_flight: Option<Arc<()>>,
324}
325
326/// What the breaker decided for one `route.open`, before any relay work.
327pub(super) enum RouteBindAdmission<'a> {
328    Admitted {
329        guard: RouteBindBreakerGuard<'a>,
330        /// This open is the single half-open probe, so the transition is worth
331        /// one log line.
332        probe: bool,
333    },
334    Refused {
335        consecutive_timeouts: u32,
336        /// What is left of the cooldown. Zero when the refusal is because the
337        /// one probe is already in flight rather than because the cooldown has
338        /// not elapsed.
339        retry_in: Duration,
340        probe_in_flight: bool,
341    },
342}
343
344/// An outstanding admission, which must be told how its relay settled.
345///
346/// `Drop` settles it as inconclusive, so an early return between admission and
347/// the relay -- or the whole handler being cancelled when the client
348/// disconnects -- releases a half-open probe slot instead of leaving the
349/// breaker wedged half-open with no further probes.
350pub(super) struct RouteBindBreakerGuard<'a> {
351    breakers: RouteBindBreakers,
352    module_id: &'a str,
353    probe_token: Option<Arc<()>>,
354    settled: bool,
355}
356
357impl RouteBindBreakerGuard<'_> {
358    /// The module answered within the budget and took the bind. THE ONLY
359    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
360    /// breaker, which is a transition worth logging.
361    fn record_accepted(&mut self) -> bool {
362        self.settled = true;
363        self.breakers.record_accepted(self.module_id)
364    }
365
366    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
367    /// COUNTS TOWARD OPENING.
368    pub(super) fn record_timeout(
369        &mut self,
370        threshold: u32,
371        cooldown: Duration,
372    ) -> Option<BreakerOpened> {
373        self.settled = true;
374        self.breakers.record_timeout(
375            self.module_id,
376            self.probe_token.as_ref(),
377            threshold,
378            cooldown,
379        )
380    }
381
382    /// Everything else: the module REJECTED the bind, its connection went away
383    /// mid-relay, or the waiter was cancelled.
384    ///
385    /// None of these is evidence that a module is slow, and each already has
386    /// its own refusal with its own code. A module that rejects a bind in
387    /// microseconds is healthy and must never be convicted for it; a module
388    /// that died has said nothing about the module that replaces it. So these
389    /// neither increment nor reset the count -- they only release a probe slot.
390    pub(super) fn record_inconclusive(&mut self) {
391        self.settled = true;
392        self.breakers
393            .record_inconclusive(self.module_id, self.probe_token.as_ref());
394    }
395}
396
397impl Drop for RouteBindBreakerGuard<'_> {
398    fn drop(&mut self) {
399        if !self.settled {
400            self.breakers
401                .record_inconclusive(self.module_id, self.probe_token.as_ref());
402        }
403    }
404}
405
406/// The breaker moved to open, reported so the caller can log it outside the
407/// lock. Opening is rare and load-bearing; the refusals that follow are
408/// frequent and are counted rather than logged.
409pub(super) struct BreakerOpened {
410    consecutive_timeouts: u32,
411    /// True when a failed probe re-opened an already-open breaker, which reads
412    /// very differently in a log from a first opening.
413    pub(super) reopened_after_probe: bool,
414}
415
416impl RouteBindBreakers {
417    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
418        self.modules
419            .lock()
420            .expect("route.bind breaker mutex poisoned")
421    }
422
423    /// Decide whether this `route.open` may attempt its relay. Takes the map
424    /// lock and nothing else, and never awaits.
425    pub(super) fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
426        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
427            probe: probe_token.is_some(),
428            guard: RouteBindBreakerGuard {
429                breakers: self.clone(),
430                module_id,
431                probe_token,
432                settled: false,
433            },
434        };
435
436        let mut modules = self.lock();
437        let Some(state) = modules.get_mut(module_id) else {
438            return admitted(None);
439        };
440        let Some(cooldown_until) = state.cooldown_until else {
441            return admitted(None);
442        };
443        if state.probe_in_flight.is_some() {
444            return RouteBindAdmission::Refused {
445                consecutive_timeouts: state.consecutive_timeouts,
446                retry_in: Duration::ZERO,
447                probe_in_flight: true,
448            };
449        }
450        let now = Instant::now();
451        if now < cooldown_until {
452            return RouteBindAdmission::Refused {
453                consecutive_timeouts: state.consecutive_timeouts,
454                retry_in: cooldown_until - now,
455                probe_in_flight: false,
456            };
457        }
458        let token = Arc::new(());
459        state.probe_in_flight = Some(Arc::clone(&token));
460        admitted(Some(token))
461    }
462
463    fn record_accepted(&self, module_id: &str) -> bool {
464        self.lock()
465            .remove(module_id)
466            .is_some_and(|state| state.cooldown_until.is_some())
467    }
468
469    pub(super) fn record_timeout(
470        &self,
471        module_id: &str,
472        probe_token: Option<&Arc<()>>,
473        threshold: u32,
474        cooldown: Duration,
475    ) -> Option<BreakerOpened> {
476        let mut modules = self.lock();
477        let state = modules.entry(module_id.to_string()).or_default();
478        let was_open = state.cooldown_until.is_some();
479        let was_probe = Self::owns_probe(state, probe_token);
480        if was_probe {
481            state.probe_in_flight = None;
482        }
483        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
484        if state.consecutive_timeouts < threshold {
485            return None;
486        }
487        state.cooldown_until = Some(Instant::now() + cooldown);
488        Some(BreakerOpened {
489            consecutive_timeouts: state.consecutive_timeouts,
490            reopened_after_probe: was_open && was_probe,
491        })
492    }
493
494    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
495        // A relay can finish after the breaker was reset or after it opened
496        // again and started a new probe. Only the guard whose token matches the
497        // active probe may release it, so a late relay never frees a newer probe.
498        state
499            .probe_in_flight
500            .as_ref()
501            .zip(token)
502            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
503    }
504
505    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
506        if let Some(state) = self.lock().get_mut(module_id) {
507            if Self::owns_probe(state, probe_token) {
508                state.probe_in_flight = None;
509            }
510        }
511    }
512
513    /// Discard what was learned about a module, because the process it was
514    /// learned about is gone. Returns the discarded count when it was non-zero.
515    ///
516    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
517    /// `module_id` is a configuration identity that outlives any particular
518    /// child; what the breaker observed was the process behind the module
519    /// connection of the moment. When a new connection registers under that id
520    /// the verdict's subject no longer exists, so the verdict is stale by
521    /// construction rather than merely likely to be wrong. Keeping it would
522    /// apply a dead process's record to a live one, which is the same defect
523    /// class this breaker exists to stop the daemon committing.
524    ///
525    /// A half-open probe in flight is discarded with the rest: it was a
526    /// question about the old process.
527    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
528        self.lock()
529            .remove(module_id)
530            .map(|state| state.consecutive_timeouts)
531            .filter(|discarded| *discarded > 0)
532    }
533
534    /// Open breakers, for the `server.describe` counters object. `None` when
535    /// none is open, so the key stays absent rather than present-and-empty.
536    ///
537    /// This is the operator's answer to "is this module refusing instantly or
538    /// is it fine?", which look identical from a client that retries and then
539    /// succeeds.
540    pub(super) fn open_snapshot(&self) -> Option<serde_json::Value> {
541        let now = Instant::now();
542        let modules = self.lock();
543        let open = modules
544            .iter()
545            .filter_map(|(module_id, state)| {
546                let cooldown_until = state.cooldown_until?;
547                Some((
548                    module_id.clone(),
549                    serde_json::json!({
550                        "consecutive_timeouts": state.consecutive_timeouts,
551                        "cooldown_remaining_ms":
552                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
553                        "probe_in_flight": state.probe_in_flight.is_some(),
554                    }),
555                ))
556            })
557            .collect::<serde_json::Map<String, serde_json::Value>>();
558        (!open.is_empty()).then_some(serde_json::Value::Object(open))
559    }
560}
561
562impl ControlHandler {
563    fn deliver_route_open_fence_refusal(&self, ctx: &RouteCtx, refusal: Frame) -> Vec<Frame> {
564        match self
565            .forwarding
566            .upgrade_refusals
567            .track_fence_refusal(refusal)
568        {
569            Ok(tracked) => {
570                tracked.send(&ctx.egress);
571                Vec::new()
572            }
573            Err(refusal) => vec![refusal],
574        }
575    }
576
577    /// Override the route.bind relay timeout. Used by tests that assert the
578    /// timeout path so they don't block on the production-safe default.
579    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
580        self.route_bind_relay_timeout = timeout;
581        self
582    }
583
584    /// Install per-module route.bind relay budget overrides. A module id
585    /// listed here wins over the daemon-wide default set via
586    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
587    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
588    /// the same `Duration` the bind path will use.
589    pub fn with_route_bind_relay_timeouts(
590        mut self,
591        timeouts: impl IntoIterator<Item = (String, Duration)>,
592    ) -> Self {
593        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
594        self
595    }
596
597    /// Resolve the route.bind relay budget for a specific target module id.
598    /// Per-module overrides win; the daemon-wide value (set via
599    /// `with_route_bind_relay_timeout` or the built-in default) is the
600    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
601    /// the same resolution `handle_route_open` will use.
602    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
603        self.route_bind_relay_timeouts
604            .get(module_id)
605            .copied()
606            .unwrap_or(self.route_bind_relay_timeout)
607    }
608
609    /// Override the per-module bind-relay breaker policy.
610    ///
611    /// Used by tests, which cannot spend three production budgets opening a
612    /// breaker or twenty seconds waiting for its cooldown. The production
613    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
614    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
615    /// reasoning for the numbers.
616    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
617        self.route_bind_breaker_threshold = threshold.max(1);
618        self.route_bind_breaker_cooldown = cooldown;
619        self
620    }
621}
622
623impl ControlHandler {
624    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
625    /// announce it is parked, once to be released. Build the barrier for two
626    /// parties, the test being the other one.
627    #[cfg(test)]
628    pub(crate) fn with_route_bind_relay_sent_hold(
629        mut self,
630        hold: Arc<tokio::sync::Barrier>,
631    ) -> Self {
632        self.route_bind_relay_sent_hold = Some(hold);
633        self
634    }
635}
636
637impl ControlHandler {
638    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
639        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
640            return None;
641        }
642        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
643            parse_client_control_request(&frame.body)
644        else {
645            return None;
646        };
647        Some(target_module_id(&target).to_string())
648    }
649
650    pub(crate) fn route_open_capacity_refusal(
651        &self,
652        ctx: &RouteCtx,
653        frame: &Frame,
654        target_module_id: &str,
655        in_flight: usize,
656        limit: usize,
657    ) -> Result<Frame, RouterError> {
658        // Sent before the request reaches `handle_route_open`, so the caller
659        // fields come from the raw frame here.
660        let caller = self.route_open_caller_from_frame(ctx, frame);
661        self.route_open_admission_refusal_frame(
662            ctx,
663            &caller,
664            frame,
665            target_module_id,
666            "open_admission_full",
667            (in_flight, limit),
668            format!(
669                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
670            ),
671        )
672    }
673
674    pub(super) fn route_open_target_capacity_refusal(
675        &self,
676        ctx: &RouteCtx,
677        caller: &RouteOpenCaller,
678        frame: &Frame,
679        target_module_id: &str,
680        in_flight: usize,
681    ) -> Result<Frame, RouterError> {
682        self.route_open_admission_refusal_frame(
683            ctx,
684            caller,
685            frame,
686            target_module_id,
687            "target_binds_full",
688            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
689            format!(
690                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
691            ),
692        )
693    }
694
695    /// Admission pressure clears as existing binds settle, so its refusal must
696    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
697    /// `module_reloading`, `module_warming`, `target_unavailable`, or
698    /// `module_timeout`. `target_unavailable` is honest for an attempt that
699    /// cannot currently reach its target; `module_timeout` would falsely claim
700    /// that a wait expired. A new, cleaner code would be terminal to deployed
701    /// clients, so it requires a client-tolerance rollout before daemon emission.
702    #[allow(clippy::too_many_arguments)]
703    fn route_open_admission_refusal_frame(
704        &self,
705        ctx: &RouteCtx,
706        caller: &RouteOpenCaller,
707        frame: &Frame,
708        target_module_id: &str,
709        reason: &'static str,
710        (in_flight, limit): (usize, usize),
711        message: impl Into<String>,
712    ) -> Result<Frame, RouterError> {
713        let code = error_codes::TARGET_UNAVAILABLE;
714        self.counters.increment_route_open_refused(code);
715        info!(
716            target: "control",
717            code,
718            reason,
719            module_id = ?target_module_id,
720            connection_id = ctx.connection_id.get(),
721            principal = %caller.principal,
722            scope = %caller.scope,
723            harness = %caller.harness,
724            in_flight,
725            limit,
726            "route.open refused"
727        );
728        control_error_frame(frame, code, message.into())
729    }
730}
731
732impl ControlHandler {
733    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
734    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
735    /// own commit failed after the module had already accepted). Without this, a
736    /// module that accepts late keeps a binding subc has torn down, so a later
737    /// frame on that module channel could misdeliver if the channel is reused.
738    ///
739    /// Never closes the shared module connection on failure: a dropped notification
740    /// only wastes a bounded amount of warm module-side state, which the module's
741    /// own idle reaper reclaims. Only call this once the route.bind relay was
742    /// actually enqueued to the module — if the relay send itself failed, the
743    /// module never created a binding and there is nothing to tear down.
744    fn send_abandoned_route_bind_goodbye(
745        &self,
746        module_sink: &crate::FrameSink,
747        negotiated_ver: u8,
748        module_channel: u16,
749        module_epoch: u32,
750    ) {
751        let frame = match Frame::build_with_version(
752            negotiated_ver,
753            FrameType::Goodbye,
754            control_flags(),
755            module_channel,
756            module_epoch,
757            0,
758            Vec::new(),
759        ) {
760            Ok(frame) => frame,
761            Err(err) => {
762                warn!(
763                    route_channel = module_channel,
764                    error = %err,
765                    "failed to build GOODBYE for abandoned route.bind"
766                );
767                return;
768            }
769        };
770        crate::forwarding::send_module_route_goodbye(
771            &self.counters,
772            module_sink,
773            frame,
774            None,
775            "abandoned route.bind",
776        );
777    }
778}
779
780impl ControlHandler {
781    /// The caller fields for a refusal that only has the raw request frame,
782    /// such as the connection-level admission refusal sent before the request
783    /// reaches [`Self::handle_route_open`].
784    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
785        let Ok(ClientControlRequest::RouteOpen {
786            identity,
787            consumer_identity,
788            scope,
789            ..
790        }) = parse_client_control_request(&frame.body)
791        else {
792            return RouteOpenCaller::unknown();
793        };
794        let principal = self
795            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
796            .map(|attested| attested.principal);
797        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
798    }
799
800    pub(super) fn route_open_principal(
801        &self,
802        connection_id: ConnectionId,
803        frame: &Frame,
804        consumer_identity: Option<ConsumerIdentity>,
805    ) -> Result<Result<Principal, Frame>, RouterError> {
806        let attested = self
807            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
808            .map(|attested| attested.principal);
809        self.route_open_principal_attested(frame, consumer_identity, attested)
810    }
811
812    /// [`Self::route_open_principal`] with `attested` already taken by
813    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
814    /// claim or launch nonce once.
815    fn route_open_principal_attested(
816        &self,
817        frame: &Frame,
818        consumer_identity: Option<ConsumerIdentity>,
819        attested: Option<Principal>,
820    ) -> Result<Result<Principal, Frame>, RouterError> {
821        if let Some(principal) = attested {
822            return Ok(Ok(principal));
823        }
824        Ok(Err(control_error_frame(
825            frame,
826            "bad_consumer_identity",
827            consumer_identity.map_or_else(
828                || "connection claim is no longer authorized for routes".to_string(),
829                |identity| format!(
830                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
831                    identity.module_id
832                ),
833            ),
834        )?))
835    }
836
837    /// Ordinary `route.open` refusals go through here; admission and breaker
838    /// refusals log separately with their capacity or breaker state. The daemon can
839    /// attest which code it sent: without the event, a client's "the daemon
840    /// refused me" and the daemon's own view could only be reconciled by
841    /// argument. Malformed input (`invalid_project_root`) does not come here;
842    /// rejecting a request that was never a valid open is not a refusal of one.
843    #[allow(clippy::too_many_arguments)]
844    pub(super) fn route_open_refusal_frame(
845        &self,
846        ctx: &RouteCtx,
847        caller: &RouteOpenCaller,
848        frame: &Frame,
849        module_id: &str,
850        reason: &'static str,
851        code: &'static str,
852        message: impl Into<String>,
853    ) -> Result<Frame, RouterError> {
854        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
855        let detail = if reason == "daemon_upgrade" {
856            Some(serde_json::json!({"reason": "daemon_upgrade"}))
857        } else if matches!(
858            reason,
859            "registration_not_active"
860                | "supervisor_not_live"
861                | "no_forwarding_connection"
862                | "reloading"
863        ) {
864            // A planned restart, reload or swap is already replacing the
865            // process; it does not need a slot in the crash-restart budget.
866            let expected_back = (reason == "reloading").then_some(true);
867            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
868        } else {
869            None
870        };
871        control_error_body_frame(
872            frame,
873            ErrorBody {
874                code: code.to_string(),
875                message: message.into(),
876                detail,
877            },
878        )
879    }
880
881    fn route_open_recovery_detail(
882        &self,
883        module_id: &str,
884        corr: u64,
885        detail: Option<serde_json::Value>,
886        expected_back: Option<bool>,
887    ) -> Result<Option<serde_json::Value>, RouterError> {
888        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
889            return Ok(detail);
890        };
891        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
892        detail["state"] = serde_json::json!(status.state.to_string());
893        if let Some(expected_back) = expected_back {
894            detail["expected_back"] = serde_json::json!(expected_back);
895        } else if let Some(module) = self.supervisor.get(module_id) {
896            match module.will_recover_after_connection_loss() {
897                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
898                Err(err) => warn!(
899                    %module_id,
900                    error = %err,
901                    "failed to read route.open recovery verdict; omitting expected_back"
902                ),
903            }
904        }
905        Ok(Some(detail))
906    }
907
908    /// Answer a waiting `route.open` whose relayed bind was refused.
909    ///
910    /// `daemon_authored` is provenance, not a code match: the daemon
911    /// synthesized the refusal itself (a drain, a late reply, a scope that
912    /// ended mid-bind) or the module refused the bind with its own body. A
913    /// daemon refusal carries the daemon-origin bit; a module's own
914    /// rejection is relayed with the bit clear, so a module that refuses
915    /// with `module_reloading` still cannot mint a daemon refusal.
916    #[allow(clippy::too_many_arguments)]
917    fn route_bind_rejection(
918        &self,
919        ctx: &RouteCtx,
920        caller: &RouteOpenCaller,
921        frame: &Frame,
922        target_module_id: &str,
923        body: ErrorBody,
924        daemon_authored: bool,
925    ) -> Result<Vec<Frame>, RouterError> {
926        // The daemon's own commit re-check refused the bind because the
927        // scope ended or changed after admission. The module accepted;
928        // counting it as a module rejection would blame the module. This
929        // branch only runs for daemon-synthesized bodies: a module that
930        // refuses with a scope code is answered as a module rejection below.
931        if daemon_authored {
932            let scope_code = match body.code.as_str() {
933                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
934                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
935                _ => None,
936            };
937            if let Some(code) = scope_code {
938                self.observe_route_open_refusal(
939                    ctx,
940                    caller,
941                    target_module_id,
942                    "scope_changed_before_commit",
943                    code,
944                );
945                return Ok(vec![control_error_body_frame(frame, body)?]);
946            }
947        }
948        self.counters
949            .increment_route_open_refused("module_rejected");
950        info!(
951            target: "control",
952            code = "module_rejected",
953            module_code = ?body.code,
954            module_id = ?target_module_id,
955            connection_id = ctx.connection_id.get(),
956            principal = %caller.principal,
957            scope = %caller.scope,
958            harness = %caller.harness,
959            "route.open refused"
960        );
961        let refusal = if daemon_authored {
962            control_error_body_frame(frame, body)?
963        } else {
964            control_relayed_error_body_frame(frame, body)?
965        };
966        Ok(vec![refusal])
967    }
968
969    /// Refuse a `route.open` because the target module's bind-relay breaker is
970    /// open, without attempting the relay.
971    ///
972    /// The wire code is `module_timeout`, which is the truth (the module has
973    /// not been answering binds) and which both SDKs already classify as
974    /// retryable with capped backoff. Reusing it is what keeps this change out
975    /// of both SDKs; the daemon-side distinction lives in the counter key
976    /// instead.
977    ///
978    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
979    /// While a breaker is open this fires on every open to that module, and the
980    /// stall written up in `docs/designs/route-open-head-of-line.md` already
981    /// produced 261 lines about a single module inside 3000 lines of daemon
982    /// log. The rare transitions are logged at warn/info instead and the volume
983    /// is carried by the counter, so the evidence survives without the flood.
984    /// The debug line keeps a per-refusal record reachable for whoever turns
985    /// the level up.
986    #[allow(clippy::too_many_arguments)]
987    fn route_open_breaker_refusal_frame(
988        &self,
989        ctx: &RouteCtx,
990        caller: &RouteOpenCaller,
991        frame: &Frame,
992        module_id: &str,
993        consecutive_timeouts: u32,
994        retry_in: Duration,
995        probe_in_flight: bool,
996    ) -> Result<Frame, RouterError> {
997        self.counters
998            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
999        debug!(
1000            target: "control",
1001            code = "module_timeout",
1002            module_id = ?module_id,
1003            connection_id = ctx.connection_id.get(),
1004            principal = %caller.principal,
1005            scope = %caller.scope,
1006            harness = %caller.harness,
1007            consecutive_timeouts,
1008            retry_in_ms = retry_in.as_millis() as u64,
1009            probe_in_flight,
1010            "route.open refused by open bind-relay breaker"
1011        );
1012        // Say what a caller can act on. An open bind-relay breaker means the
1013        // module timed out accepting several new routes in a row. The module
1014        // is still running and its established routes keep working; only new
1015        // route.open requests are refused until the cooldown ends and one
1016        // test route (the probe) gets through. A message that only counts
1017        // failed relays reads as "the module is down" to a worker that sees it.
1018        let detail = if probe_in_flight {
1019            "one test route is already being tried; retry once it settles".to_string()
1020        } else {
1021            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
1022        };
1023        control_error_frame(
1024            frame,
1025            "module_timeout",
1026            format!(
1027                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
1028                 timed out in a row); {detail}; its established routes are unaffected"
1029            ),
1030        )
1031    }
1032
1033    /// `reason` names the check that refused, because one wire code has
1034    /// several senders: after a module registers, `target_unavailable` can
1035    /// come from a missing role, an inactive registration, a supervisor that
1036    /// has not marked the process live, a missing forwarding connection, or a
1037    /// failed relay, and a log that records only the code cannot say which of
1038    /// them fired. It is a static, daemon-chosen label per branch, so it is
1039    /// safe to print plainly and stays a closed set.
1040    fn observe_route_open_refusal(
1041        &self,
1042        ctx: &RouteCtx,
1043        caller: &RouteOpenCaller,
1044        module_id: &str,
1045        reason: &'static str,
1046        code: &'static str,
1047    ) {
1048        self.counters.increment_route_open_refused(code);
1049        self.route_refusal_log
1050            .record(module_id, code, reason, caller, ctx.connection_id.get());
1051        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
1052            self.route_outages.record_not_serving(module_id, reason);
1053        }
1054    }
1055
1056    /// Record an ACCEPTED route.open.
1057    ///
1058    /// Refusals have been logged and counted since the attestation work; accepts
1059    /// were invisible, so the daemon knew every principal it stamped and wrote
1060    /// none of them down. The party that attests the identity was the only party
1061    /// not recording it, which left a credential vault unable to name the sender
1062    /// of a call that reached it (claustrum #43) and left the launch-nonce
1063    /// concurrency question unanswerable from the outside.
1064    ///
1065    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
1066    /// `code`/`module_id`/`connection_id` returns both directions of the same
1067    /// decision rather than two shapes a reader has to join by hand.
1068    ///
1069    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
1070    /// and the difference carries information rather than being an
1071    /// inconsistency. This line is only reachable after a successful bind to a
1072    /// REGISTERED module, so the value has already passed HELLO validation
1073    /// including the path-hazard refusal and cannot contain control bytes. A
1074    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
1075    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
1076    ///
1077    /// Bare is also what every other daemon line already emits (`module
1078    /// registered`, `configured module supervised`). Shipping `?module_id` here
1079    /// made this instrument the only one in the file whose ids did not answer
1080    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
1081    /// line whose whole purpose is being grepped beside its sibling.
1082    ///
1083    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
1084    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
1085    /// forwards every field type through it and a bare `&str` and a `?`-escaped
1086    /// one are recorded identically. A test written against that harness passes
1087    /// either way -- I wrote one, measured it, and deleted it rather than ship a
1088    /// green assertion that cannot fail. The same limit applies to the escaping
1089    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
1090    /// it reads as a guard on the Debug escaping and cannot detect its removal.
1091    /// Fencing either needs the real formatter, not the capture layer.
1092    ///
1093    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
1094    /// unix-socket options and subc is loopback TCP, so there is no peer identity
1095    /// to record. The ephemeral port would decay within minutes and answer only a
1096    /// live question. The identity question is instead answered by counting
1097    /// distinct live connections presenting one module's `consumer_identity` --
1098    /// "is anyone else holding this secret" rather than "is this the right
1099    /// process".
1100    fn observe_route_open_accept(
1101        &self,
1102        ctx: &RouteCtx,
1103        module_id: &str,
1104        principal: &str,
1105        scope: &str,
1106    ) {
1107        self.route_outages.record_accepted(module_id);
1108        self.counters.increment_route_open_accepted(principal);
1109        debug!(
1110            target: "control",
1111            principal,
1112            module_id,
1113            connection_id = ctx.connection_id.get(),
1114            scope = %scope,
1115            "route.open accepted"
1116        );
1117    }
1118
1119    fn supervised_absent_route_open_refusal_frame(
1120        &self,
1121        ctx: &RouteCtx,
1122        caller: &RouteOpenCaller,
1123        frame: &Frame,
1124        module_id: &str,
1125        code: &'static str,
1126        status: &crate::supervise::ModuleStatus,
1127    ) -> Result<Frame, RouterError> {
1128        self.counters.increment_route_open_refused(code);
1129        info!(
1130            target: "control",
1131            code,
1132            reason = "supervised_not_registered",
1133            module_id = ?module_id,
1134            connection_id = ctx.connection_id.get(),
1135            principal = %caller.principal,
1136            scope = %caller.scope,
1137            harness = %caller.harness,
1138            state = %status.state,
1139            enabled = status.enabled,
1140            live = status.live,
1141            "route.open refused"
1142        );
1143        // A supervised module whose process has not registered is not
1144        // serving, whatever the reason; the supervisor knows this id, so it is
1145        // safe to track.
1146        self.route_outages
1147            .record_not_serving(module_id, "supervised_not_registered");
1148        let message = if let Some(pid) = status.waiting_for_previous_pid {
1149            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
1150                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
1151            })
1152        } else {
1153            format!(
1154                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
1155                status.state, status.enabled, status.live
1156            )
1157        };
1158        // `module_warming` here means the process is starting, running or
1159        // being restarted and has not registered yet. Nothing has to be
1160        // restarted for it to serve, so the crash budget does not decide it.
1161        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
1162        control_error_body_frame(
1163            frame,
1164            ErrorBody {
1165                code: code.to_string(),
1166                message,
1167                detail: self.route_open_recovery_detail(
1168                    module_id,
1169                    frame.header.corr,
1170                    None,
1171                    expected_back,
1172                )?,
1173            },
1174        )
1175    }
1176
1177    pub(super) async fn handle_route_open(
1178        &self,
1179        ctx: &RouteCtx,
1180        frame: Frame,
1181        request: RouteOpenRequest,
1182        timings: &mut RouteOpenTimings,
1183    ) -> Result<Vec<Frame>, RouterError> {
1184        let RouteOpenRequest {
1185            target,
1186            mut identity,
1187            consumer_identity,
1188            consumer_capabilities,
1189            role_versions,
1190            busy_refusals,
1191            admission_facts,
1192            scope,
1193            accepts_close_reasons,
1194        } = request;
1195        let target_module_id = target_module_id(&target).to_string();
1196        timings.module_id.clone_from(&target_module_id);
1197        if self
1198            .registry
1199            .get_module_by_connection(ctx.connection_id)
1200            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
1201            .is_some()
1202        {
1203            return Ok(vec![control_error_frame(
1204                &frame,
1205                "invalid_request",
1206                "module connections cannot open client routes",
1207            )?]);
1208        }
1209        debug!(
1210            connection_id = ctx.connection_id.get(),
1211            corr = frame.header.corr,
1212            module_id = %target_module_id,
1213            "handling route.open"
1214        );
1215
1216        // The caller's attested principal, requested scope and harness, for
1217        // every `route.open refused` line below. The connection's claim
1218        // binding or launch nonce is checked here, once, and the answer is
1219        // reused where the principal is enforced further down, so the order
1220        // of refusals is unchanged.
1221        let attested =
1222            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
1223        let mut caller = RouteOpenCaller::new(
1224            attested.as_ref().map(|attested| &attested.principal),
1225            scope.as_ref(),
1226            &identity,
1227        );
1228
1229        // A malformed declaration is refused first, before anything about the
1230        // target is looked up: the same body would be refused against any
1231        // module, so the caller learns nothing by retrying or waiting. An empty
1232        // map declares nothing and travels as no field at all, so a provider
1233        // only ever sees a missing field or a non-empty one.
1234        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
1235        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
1236            self.observe_route_open_refusal(
1237                ctx,
1238                &caller,
1239                &target_module_id,
1240                "invalid_role_versions",
1241                error_codes::INVALID_REQUEST,
1242            );
1243            return Ok(vec![control_error_body_frame(
1244                &frame,
1245                ErrorBody {
1246                    code: error_codes::INVALID_REQUEST.to_string(),
1247                    message: error.to_string(),
1248                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
1249                },
1250            )?]);
1251        }
1252
1253        if self.forwarding.upgrade_admission.phase().fenced()
1254            || self.supervisor.adoption_blocks(&target_module_id)
1255        {
1256            let refusal = self.route_open_refusal_frame(
1257                ctx,
1258                &caller,
1259                &frame,
1260                &target_module_id,
1261                "daemon_upgrade",
1262                "module_reloading",
1263                "module is awaiting daemon upgrade recovery",
1264            )?;
1265            return Ok(self.deliver_route_open_fence_refusal(ctx, refusal));
1266        }
1267        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
1268            if status.waiting_for_previous_pid.is_some() {
1269                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
1270                    ctx,
1271                    &caller,
1272                    &frame,
1273                    &target_module_id,
1274                    "module_warming",
1275                    &status,
1276                )?]);
1277            }
1278        }
1279
1280        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
1281        // opposite. Below, a caller learns whether a module is unregistered,
1282        // supervised-but-down (with state/enabled/live), or registered without the
1283        // requested role. Elsewhere that is an enumeration leak: a probe learning
1284        // the shape of a fleet it cannot otherwise see.
1285        //
1286        // It is not one here, and the reason is the ACCESS MODEL rather than
1287        // anything about these errors. Reaching route.open requires the
1288        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
1289        // connection file, so any caller who completes it already runs as this
1290        // user -- and can read subc.jsonc for the module list and `ck module
1291        // status` for live state. The reply discloses nothing the caller cannot
1292        // read more easily from disk, while the precision is load-bearing:
1293        // `unknown_module` is retryable and a missing role is not.
1294        //
1295        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
1296        // remote transport, a sandboxed caller, a shared-host mode -- THAT
1297        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
1298        let admission_registry = self
1299            .registry
1300            .route_admission_snapshot()
1301            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
1302        let Some(registration) =
1303            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
1304        else {
1305            if let Some((status, warming)) =
1306                self.supervisor_status(&target_module_id, frame.header.corr)?
1307            {
1308                // BEFORE the two availability codes below, because for a module
1309                // that speaks no subc wire both of them are false comfort: they
1310                // say "not right now" and are retried, and this module will
1311                // never register no matter how long the caller waits. The
1312                // absence here is the declaration being honoured, not a module
1313                // that is late.
1314                if status.protocol == ModuleProtocol::None {
1315                    return Ok(vec![self.route_open_refusal_frame(
1316                        ctx,
1317                        &caller,
1318                        &frame,
1319                        &target_module_id,
1320                        "protocol_none",
1321                        error_codes::MODULE_NO_PROTOCOL,
1322                        format!(
1323                            "module_id '{target_module_id}' is declared protocol: none; \
1324                             it speaks no subc wire and serves no routes"
1325                        ),
1326                    )?]);
1327                }
1328                let code = if warming {
1329                    "module_warming"
1330                } else {
1331                    "target_unavailable"
1332                };
1333                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
1334                    ctx,
1335                    &caller,
1336                    &frame,
1337                    &target_module_id,
1338                    code,
1339                    &status,
1340                )?]);
1341            }
1342            if let Some(removed_ago_ms) =
1343                self.supervisor.removal_tombstone_age_ms(&target_module_id)
1344            {
1345                return Ok(vec![self.route_open_refusal_frame(
1346                    ctx,
1347                    &caller,
1348                    &frame,
1349                    &target_module_id,
1350                    "removed",
1351                    error_codes::MODULE_REMOVED,
1352                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
1353                )?]);
1354            }
1355            return Ok(vec![self.route_open_refusal_frame(
1356                ctx,
1357                &caller,
1358                &frame,
1359                &target_module_id,
1360                "not_registered",
1361                error_codes::UNKNOWN_MODULE,
1362                format!("module_id '{target_module_id}' is not registered"),
1363            )?]);
1364        };
1365
1366        // Best-effort only: registry readiness and forwarding reservation use
1367        // different locks, so a module can flip readiness between this read and
1368        // the relay. Modules must still tolerate an `on_bind` while not ready.
1369        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
1370            .is_err()
1371        {
1372            self.counters
1373                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
1374            info!(
1375                target: "control",
1376                code = error_codes::MODULE_WARMING,
1377                module_id = ?target_module_id,
1378                connection_id = ctx.connection_id.get(),
1379                principal = %caller.principal,
1380                scope = %caller.scope,
1381                harness = %caller.harness,
1382                reason = "declared_not_ready",
1383                "route.open refused"
1384            );
1385            // The module is registered but says it cannot take work, which is
1386            // an outage from the caller's side even though its process is up.
1387            self.route_outages
1388                .record_not_serving(&target_module_id, "declared_not_ready");
1389            // The registered process can declare itself ready without a
1390            // restart, so an exhausted crash budget does not prevent serving.
1391            return Ok(vec![control_error_body_frame(
1392                &frame,
1393                ErrorBody {
1394                    code: error_codes::MODULE_WARMING.to_string(),
1395                    message: format!(
1396                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
1397                    ),
1398                    detail: self.route_open_recovery_detail(
1399                        &target_module_id,
1400                        frame.header.corr,
1401                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
1402                        Some(true),
1403                    )?,
1404                },
1405            )?]);
1406        }
1407
1408        // Effective readiness, second half: a module that declares a capability
1409        // `need: required` is not routable while that capability has no
1410        // registered provider. It is enforced HERE, as a retryable routing
1411        // refusal, and deliberately not as spawn ordering or a boot block. The
1412        // module is still started and registered and can make its own calls;
1413        // spawn ordering is a promise that cannot be kept once a provider
1414        // crashes at runtime, and refusing to boot would stop the whole
1415        // machine, including the tools needed to fix its configuration.
1416        //
1417        // "Provided" is the evaluator's verdict, which counts a provider as
1418        // soon as it has REGISTERED, not once it is ready. Two modules that
1419        // require each other's capabilities are therefore both routable once
1420        // both register; counting readiness instead would deadlock them.
1421        //
1422        // Only new opens are refused. Routes already bound when a provider
1423        // goes away stay bound: nothing here tears them down, and the module
1424        // answers them as it can. Like the readiness read above this is
1425        // best-effort against a provider registering or leaving concurrently.
1426        if let Some(capability) = self.first_unprovided_required_capability_for(
1427            &registration.module_id,
1428            registration.capabilities.as_ref(),
1429        ) {
1430            self.counters
1431                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
1432            info!(
1433                target: "control",
1434                code = error_codes::MODULE_WARMING,
1435                module_id = ?target_module_id,
1436                connection_id = ctx.connection_id.get(),
1437                principal = %caller.principal,
1438                scope = %caller.scope,
1439                harness = %caller.harness,
1440                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
1441                capability = %capability,
1442                "route.open refused"
1443            );
1444            return Ok(vec![control_error_body_frame(
1445                &frame,
1446                ErrorBody {
1447                    code: error_codes::MODULE_WARMING.to_string(),
1448                    message: format!(
1449                        "module_id '{target_module_id}' requires capability '{capability}', \
1450                         which no registered module provides; retry"
1451                    ),
1452                    detail: Some(serde_json::json!({
1453                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
1454                        "capability": capability,
1455                    })),
1456                },
1457            )?]);
1458        }
1459
1460        if !target_has_required_role(&target, &registration.roles) {
1461            return Ok(vec![self.route_open_refusal_frame(
1462                ctx,
1463                &caller,
1464                &frame,
1465                &target_module_id,
1466                "role_not_provided",
1467                "target_unavailable",
1468                format!("module_id '{target_module_id}' does not provide the requested target"),
1469            )?]);
1470        }
1471
1472        if registration.state != ChannelState::Active {
1473            return Ok(vec![self.route_open_refusal_frame(
1474                ctx,
1475                &caller,
1476                &frame,
1477                &target_module_id,
1478                "registration_not_active",
1479                "target_unavailable",
1480                format!("module_id '{target_module_id}' is not active"),
1481            )?]);
1482        }
1483
1484        if self
1485            .forwarding
1486            .module_is_draining(&target_module_id)
1487            .map_err(RouterError::Forwarding)?
1488        {
1489            return Ok(vec![self.route_open_refusal_frame(
1490                ctx,
1491                &caller,
1492                &frame,
1493                &target_module_id,
1494                "reloading",
1495                "module_reloading",
1496                format!("module_id '{target_module_id}' is reloading"),
1497            )?]);
1498        }
1499
1500        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
1501            process_liveness.process_live(&target_module_id) == Some(false)
1502        }) {
1503            // The supervisor reports Draining for both phases; only the short,
1504            // refusing phase makes an otherwise live endpoint unroutable.
1505            if !self
1506                .forwarding
1507                .module_is_accepting_drain(&target_module_id)
1508                .map_err(RouterError::Forwarding)?
1509            {
1510                // A module the supervisor is restarting or reloading can still hold
1511                // a registration: the old process before its connection closes, or
1512                // a new one that registered while the supervisor was draining. The
1513                // forwarding table does not see that as draining, but the consumer
1514                // should still be told to retry soon, exactly as for the drain
1515                // above, rather than that the target is unavailable.
1516                if process_liveness.process_replacing(&target_module_id) {
1517                    return Ok(vec![self.route_open_refusal_frame(
1518                        ctx,
1519                        &caller,
1520                        &frame,
1521                        &target_module_id,
1522                        "reloading",
1523                        "module_reloading",
1524                        format!("module_id '{target_module_id}' is reloading"),
1525                    )?]);
1526                }
1527                return Ok(vec![self.route_open_refusal_frame(
1528                    ctx,
1529                    &caller,
1530                    &frame,
1531                    &target_module_id,
1532                    "supervisor_not_live",
1533                    "target_unavailable",
1534                    format!("module_id '{target_module_id}' is not live"),
1535                )?]);
1536            }
1537        }
1538
1539        if !self
1540            .forwarding
1541            .has_live_module_connection(&target_module_id)
1542            .map_err(RouterError::Forwarding)?
1543        {
1544            return Ok(vec![self.route_open_refusal_frame(
1545                ctx,
1546                &caller,
1547                &frame,
1548                &target_module_id,
1549                "no_forwarding_connection",
1550                "target_unavailable",
1551                format!("module_id '{target_module_id}' has no live forwarding connection"),
1552            )?]);
1553        }
1554
1555        if let Some(error) =
1556            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
1557        {
1558            self.observe_route_open_refusal(
1559                ctx,
1560                &caller,
1561                &target_module_id,
1562                "op_not_allowed",
1563                "op_not_allowed",
1564            );
1565            return Ok(vec![error]);
1566        }
1567
1568        let principal = match (&attested, consumer_identity.is_some()) {
1569            // A claim-bound connection whose launch ended attests nothing,
1570            // and it must never fall back to opening as `direct`.
1571            (None, false) => {
1572                self.observe_route_open_refusal(
1573                    ctx,
1574                    &caller,
1575                    &target_module_id,
1576                    "registration_channel_closed",
1577                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1578                );
1579                return Ok(vec![control_error_frame(
1580                    &frame,
1581                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1582                    "the claim binding's launch has ended",
1583                )?]);
1584            }
1585            _ => match self.route_open_principal_attested(
1586                &frame,
1587                consumer_identity,
1588                attested.as_ref().map(|attested| attested.principal.clone()),
1589            )? {
1590                Ok(principal) => principal,
1591                Err(error) => {
1592                    self.observe_route_open_refusal(
1593                        ctx,
1594                        &caller,
1595                        &target_module_id,
1596                        "bad_consumer_identity",
1597                        "bad_consumer_identity",
1598                    );
1599                    return Ok(vec![error]);
1600                }
1601            },
1602        };
1603        let attested = attested.expect("an attested principal was resolved above");
1604        timings.principal = principal_label(&principal);
1605
1606        // The opener's spawn authority, read once here and carried with the
1607        // relay; nothing below reads its record again.
1608        let Ok(mut caller_capture) = attested.capture() else {
1609            self.observe_route_open_refusal(
1610                ctx,
1611                &caller,
1612                &target_module_id,
1613                "registration_channel_closed",
1614                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1615            );
1616            return Ok(vec![control_error_frame(
1617                &frame,
1618                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1619                "the opener's launch has ended",
1620            )?]);
1621        };
1622        // The caller-side checks below read the opener's own spawn: its
1623        // module from its record and its manifest from its own registration,
1624        // never another launch's active registration under the same id.
1625        let caller_module_id = match &attested.spawn {
1626            Some((record, _)) => Some(record.module_id().to_owned()),
1627            None => match &principal {
1628                Principal::Reserved { module_id } => Some(module_id.clone()),
1629                _ => None,
1630            },
1631        };
1632
1633        // Only Callosum can attest a production phone build. Consume the raw
1634        // claim here; opted-in targets receive only the honoured peer fact.
1635        let build_class = identity.build_class.take().filter(|build_class| {
1636            if caller_module_id.as_deref() == Some("callosum") {
1637                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
1638            } else {
1639                if self
1640                    .build_class_warned
1641                    .lock()
1642                    .unwrap_or_else(|p| p.into_inner())
1643                    .insert(ctx.connection_id)
1644                {
1645                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
1646                        "ignoring build_class from a non-Callosum opener");
1647                }
1648                false
1649            }
1650        });
1651
1652        // This is attested, control-plane policy for supervised module origins.
1653        // Keep it before route reservation and out of the opaque forwarding hot
1654        // path: data frames must never acquire a per-frame capability check.
1655        let opening_registration = self.caller_registration(&attested, &admission_registry);
1656        if let Some(opening_registration) = &opening_registration {
1657            let opening_module_id = opening_registration.module_id.as_str();
1658            if let Some(capability) = denied_capability(
1659                opening_registration.capabilities.as_ref(),
1660                registration.capabilities.as_ref(),
1661            ) {
1662                warn!(
1663                    opening_module_id,
1664                    target_module_id,
1665                    capability,
1666                    "refusing route.open because an attested capability deny edge matches"
1667                );
1668                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
1669                    &frame,
1670                    &target_module_id,
1671                    "capability_deny_edge",
1672                    "capability_forbidden",
1673                    format!(
1674                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
1675                    ),
1676                )?]);
1677            }
1678        }
1679
1680        if admission_facts.is_some() {
1681            let carrier_matches = caller_module_id.is_some()
1682                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
1683            if !carrier_matches {
1684                return Ok(vec![self.route_open_refusal_frame(
1685                    ctx,
1686                    &caller,
1687                    &frame,
1688                    &target_module_id,
1689                    "admission_facts_carrier_not_permitted",
1690                    "admission_facts_not_permitted",
1691                    "admission facts may only be carried by the configured reserved module",
1692                )?]);
1693            }
1694
1695            let target_allowed = self
1696                .admission_facts_targets
1697                .as_ref()
1698                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
1699            if !target_allowed {
1700                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
1701                    &frame,
1702                    &target_module_id,
1703                    "admission_facts_target_not_listed",
1704                    "admission_facts_target_not_allowed",
1705                    format!(
1706                        "admission facts are not permitted for target module_id '{target_module_id}'"
1707                    ),
1708                )?]);
1709            }
1710
1711            // Keep the value opaque to subc. The downstream admission validator owns
1712            // schema and semantic checks; this daemon only enforces carrier authority
1713            // and the configured destination allowlist.
1714        }
1715
1716        // Scope admission, on the attested principal above and never on the
1717        // request body. The tag read here travels with the pending bind and is
1718        // compared with the published one at commit, so a sync between here
1719        // and the module's ack refuses the open instead of binding a stamp
1720        // that is no longer true.
1721        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
1722            None => (None, None, false),
1723            Some(selector) => {
1724                let owner_configured = match &selector.owner {
1725                    // A reserved owner counts as configured from before its
1726                    // process is spawned (see `SupervisorHandle::is_configured`).
1727                    // So an owner that has not synced its scopes yet is refused
1728                    // as retryable (`scope_not_synced`), not as one that will
1729                    // never sync.
1730                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
1731                    _ => false,
1732                };
1733                let mut scopes = self
1734                    .scopes
1735                    .write()
1736                    .unwrap_or_else(|poisoned| poisoned.into_inner());
1737                let admitted = crate::scopes::admission::admit_route(
1738                    &scopes,
1739                    &admission_registry,
1740                    &principal,
1741                    &target_module_id,
1742                    Some(selector),
1743                    owner_configured,
1744                    crate::scopes::admission::AdmissionMode::Open,
1745                )
1746                .map(|route| {
1747                    let admission = route.scope.expect("scoped admission");
1748                    let bound = scopes.reserve_bind(
1749                        &admission,
1750                        &principal,
1751                        ctx.connection_id,
1752                        selector.hold_presence,
1753                    );
1754                    (admission, bound)
1755                });
1756                match admitted {
1757                    Ok((admission, bound)) => {
1758                        (Some(bound), Some(admission.stamp), admission.stamp_required)
1759                    }
1760                    Err(refusal) => {
1761                        return Ok(vec![self.route_open_refusal_frame(
1762                            ctx,
1763                            &caller,
1764                            &frame,
1765                            &target_module_id,
1766                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
1767                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
1768                            refusal.message,
1769                        )?]);
1770                    }
1771                }
1772            }
1773        };
1774        // From here on a refusal names the scope by the stamp admission
1775        // issued, exactly as the `route.open accepted` line does.
1776        if let Some(stamp) = &scope_stamp {
1777            caller.scope = route_open_scope_label(stamp);
1778        }
1779        // Decided from the admitted stamp, before any field of it is stripped
1780        // for a target that lacks the capability to read it.
1781        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
1782            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
1783        }
1784
1785        // Allow resolvable missing-tail paths so a vanished directory does not
1786        // prevent reopening an existing session for cleanup. Binding does not
1787        // authorize creation of durable provider state.
1788        //
1789        // Resolve real paths rather than lexical cleanup: canonicalize the
1790        // longest existing ancestor and append the missing tail, retaining the
1791        // path's real existing ancestry even when a leaf is missing.
1792        timings.enter(RouteOpenPhase::ProjectRoot);
1793        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
1794            Ok(project) => project,
1795            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
1796        };
1797        timings.enter(RouteOpenPhase::Admission);
1798        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
1799            Ok(root) => root,
1800            Err(err) => {
1801                return Ok(vec![control_error_frame(
1802                    &frame,
1803                    "invalid_project_root",
1804                    err.to_string(),
1805                )?])
1806            }
1807        };
1808        // Compute compatibility project fields before stripping optional stamp
1809        // members. Preserve the canonical opener root and its project ID,
1810        // including absence. For rootless openers, use stamp workdir or `/`, and
1811        // opener ID, else stamp ID, else no ID. Emit these identity fields only
1812        // to targets without bind-no-project/v1.
1813        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
1814
1815        // Last gate before any relay work, and deliberately after the cheap
1816        // registry and availability checks above: those name a more precise
1817        // condition (unknown, removed, reloading) and a caller is better served
1818        // by the precise code than by this one.
1819        //
1820        // Everything below this point costs an egress permit, a reserved handle
1821        // pair and, if the module does not answer, the whole relay budget. The
1822        // reader no longer waits for that budget, so cap each target explicitly;
1823        // serial dispatch used to provide the accidental cap of one relay per
1824        // connection. Admission is a mutex-protected count and never waits.
1825        let _concurrency_guard = match self
1826            .route_bind_concurrency
1827            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
1828        {
1829            Ok(guard) => guard,
1830            Err(in_flight) => {
1831                return Ok(vec![self.route_open_target_capacity_refusal(
1832                    ctx,
1833                    &caller,
1834                    &frame,
1835                    &target_module_id,
1836                    in_flight,
1837                )?]);
1838            }
1839        };
1840
1841        // A module that has already burned the whole budget `threshold` times
1842        // in a row does not get to charge it again until a probe says it recovered.
1843        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
1844            RouteBindAdmission::Admitted { guard, probe } => {
1845                if probe {
1846                    info!(
1847                        module_id = %target_module_id,
1848                        connection_id = ctx.connection_id.get(),
1849                        "route.bind breaker half-open: admitting one probe"
1850                    );
1851                }
1852                guard
1853            }
1854            RouteBindAdmission::Refused {
1855                consecutive_timeouts,
1856                retry_in,
1857                probe_in_flight,
1858            } => {
1859                return Ok(vec![self.route_open_breaker_refusal_frame(
1860                    ctx,
1861                    &caller,
1862                    &frame,
1863                    &target_module_id,
1864                    consecutive_timeouts,
1865                    retry_in,
1866                    probe_in_flight,
1867                )?]);
1868            }
1869        };
1870
1871        let operator_app = self
1872            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
1873            .await;
1874        // Resolve the per-module budget here so the wait matches the operator's
1875        // intent for this specific target. A per-module override in
1876        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
1877        // daemons) wins over the daemon-wide default.
1878        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
1879        let relay_deadline = Instant::now() + route_bind_relay_timeout;
1880        let production_peer_build =
1881            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
1882        timings.enter(RouteOpenPhase::EgressReservation);
1883        let pending = match self
1884            .forwarding
1885            .begin_route_bind_relay_for(
1886                ctx.connection_id,
1887                ctx.egress.clone(),
1888                response_version(&frame),
1889                frame.header.corr,
1890                &target_module_id,
1891                principal.clone(),
1892                bound_scope,
1893                project_root,
1894                identity.harness.clone(),
1895                build_class,
1896                operator_app.clone(),
1897                crate::forwarding::RouteAuthority {
1898                    incarnation: self.supervisor.daemon_incarnation(),
1899                    caller: caller_capture
1900                        .as_ref()
1901                        .map(|caller| caller.authority.pair()),
1902                    capability_fence: route_bind_settlement::fence(
1903                        &opening_registration,
1904                        registration,
1905                    ),
1906                },
1907                relay_deadline,
1908                busy_refusals == Some(true),
1909                accepts_close_reasons,
1910            )
1911            .await
1912        {
1913            Ok(pending) => pending,
1914            Err(err) => {
1915                return Ok(vec![self.route_open_refusal_frame(
1916                    ctx,
1917                    &caller,
1918                    &frame,
1919                    &target_module_id,
1920                    "relay_reservation_failed",
1921                    forwarding_error_code(&err),
1922                    err.to_string(),
1923                )?])
1924            }
1925        };
1926        timings.enter(RouteOpenPhase::Admission);
1927        let crate::forwarding::PendingRouteBindRelay {
1928            endpoint,
1929            module_sink,
1930            negotiated_ver,
1931            client_channel,
1932            client_epoch,
1933            module_channel,
1934            module_epoch,
1935            corr: relay_corr,
1936            receiver,
1937        } = pending;
1938        let mut reservation =
1939            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
1940
1941        // Reserving egress can wait while a module reconnects or a swap cuts
1942        // over. Check the relay's captured connection, not the earlier by-id
1943        // lookup: the original module's flow/run capabilities cannot authorize
1944        // its replacement. The captured sink stays bound to that connection.
1945        let relay_registration = self
1946            .registry
1947            .route_registration_by_connection(endpoint.connection_id)
1948            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
1949        let relay_capabilities = relay_registration
1950            .as_ref()
1951            .and_then(|registration| registration.capabilities.as_ref());
1952        if let Some(selector) = &scope {
1953            // Egress reservation may wait across a scope update. Recheck the
1954            // proof against the current record before sending the captured bind.
1955            if let Err(refusal) = self
1956                .scopes
1957                .read()
1958                .unwrap_or_else(|poisoned| poisoned.into_inner())
1959                .check_bind_proof(&principal, selector)
1960            {
1961                reservation.release_and_disarm();
1962                return Ok(vec![self.route_open_refusal_frame(
1963                    ctx,
1964                    &caller,
1965                    &frame,
1966                    &target_module_id,
1967                    refusal.code,
1968                    refusal.code,
1969                    refusal.message,
1970                )?]);
1971            }
1972        }
1973        if let Some(stamp) = scope_stamp.as_ref() {
1974            if let Err(refusal) = crate::scopes::check_target_required_stamp(
1975                stamp_required,
1976                &target_module_id,
1977                relay_capabilities,
1978            )
1979            .and_then(|()| {
1980                crate::scopes::check_target_flow_support(
1981                    stamp,
1982                    &target_module_id,
1983                    relay_capabilities,
1984                )
1985            })
1986            .and_then(|()| {
1987                crate::scopes::check_target_agent_run_support(
1988                    stamp,
1989                    &target_module_id,
1990                    relay_capabilities,
1991                )
1992            }) {
1993                reservation.release_and_disarm();
1994                return Ok(vec![self.route_open_refusal_frame(
1995                    ctx,
1996                    &caller,
1997                    &frame,
1998                    &target_module_id,
1999                    refusal.code,
2000                    refusal.code,
2001                    refusal.message,
2002                )?]);
2003            }
2004        }
2005
2006        // Use the admitted scope before compatibility removes fields from the bind.
2007        let caller_attestation = self.caller_for_target(
2008            caller_capture.as_ref(),
2009            relay_capabilities,
2010            &target_module_id,
2011            &principal,
2012            scope_stamp
2013                .as_ref()
2014                .and_then(|stamp| stamp.project_id.as_deref()),
2015        );
2016        // Older readers may reject unknown fields. Select optional fields from
2017        // the captured endpoint's declaration, including on unscoped binds.
2018        if scope_stamp
2019            .as_ref()
2020            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
2021            && !crate::scopes::target_supports_federated(relay_capabilities)
2022        {
2023            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
2024            scope_stamp = None;
2025        }
2026        if !relay_capabilities.is_some_and(|caps| {
2027            caps.provides
2028                .iter()
2029                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
2030        }) {
2031            if let Some(stamp) = scope_stamp.as_mut() {
2032                stamp.workdir = None;
2033                stamp.project_id = None;
2034            }
2035        }
2036        // A worker run has no agent_id; on_behalf_of_agent is its only agent
2037        // attribution. The run gate above has already required the target to
2038        // declare `worker-runs/v1`, which promises to read both
2039        // `on_behalf_of_agent` and `call_mode`.
2040        let worker_run = scope_stamp
2041            .as_ref()
2042            .is_some_and(crate::scopes::is_worker_run)
2043            && relay_capabilities.is_some_and(|caps| {
2044                caps.provides
2045                    .iter()
2046                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
2047            });
2048        if !worker_run
2049            && !relay_capabilities.is_some_and(|caps| {
2050                caps.provides
2051                    .iter()
2052                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
2053            })
2054        {
2055            if let Some(stamp) = scope_stamp.as_mut() {
2056                stamp.attributes.on_behalf_of_agent = None;
2057            }
2058        }
2059        if !relay_capabilities.is_some_and(|caps| {
2060            caps.provides
2061                .iter()
2062                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
2063        }) {
2064            if let Some(stamp) = scope_stamp.as_mut() {
2065                stamp.attributes.flow_version = None;
2066                stamp.attributes.flow_code_hash = None;
2067                stamp.attributes.flow_install_id = None;
2068            }
2069        }
2070        let call_mode = if worker_run
2071            || relay_capabilities
2072                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
2073        {
2074            Some(derive_call_mode(scope_stamp.as_ref()))
2075        } else {
2076            if let Some(stamp) = scope_stamp.as_mut() {
2077                stamp.expires_at_ms = None;
2078            }
2079            None
2080        };
2081
2082        debug!(
2083            connection_id = ctx.connection_id.get(),
2084            client_channel,
2085            client_epoch,
2086            module_channel,
2087            module_epoch,
2088            "reserved route handle pair"
2089        );
2090        // Rendered BEFORE the move into the relay, because the accept arm below
2091        // is where it is logged and the principal is gone by then.
2092        let route_principal_label = principal_label(&principal);
2093        let relay = ModuleControlRequest::RouteBind {
2094            route_channel: module_channel,
2095            epoch: module_epoch,
2096            target,
2097            identity,
2098            principal: Some(principal),
2099            consumer_capabilities,
2100            role_versions,
2101            admission_facts,
2102            scope: scope_stamp,
2103            call_mode,
2104        };
2105        let peer = RouteBindPeer::new()
2106            .with_observed_peer(
2107                relay_capabilities
2108                    .is_some_and(|caps| {
2109                        caps.provides
2110                            .iter()
2111                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
2112                    })
2113                    .then(|| {
2114                        self.observed_peers
2115                            .lock()
2116                            .unwrap_or_else(|p| p.into_inner())
2117                            .get(&ctx.connection_id)
2118                            .cloned()
2119                            .unwrap_or_else(ObservedPeer::unobserved)
2120                    }),
2121            )
2122            .with_operator_app(
2123                self.connection_operator_app(operator_app.as_ref())
2124                    .filter(|_| {
2125                        relay_capabilities.is_some_and(|caps| {
2126                            caps.provides
2127                                .iter()
2128                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
2129                        })
2130                    }),
2131            )
2132            .with_caller(caller_attestation)
2133            .with_peer_build(
2134                (production_peer_build
2135                    && relay_capabilities.is_some_and(|caps| {
2136                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
2137                    }))
2138                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
2139            );
2140        let relay_body = crate::bind_compat::encode_bind(
2141            &relay,
2142            &peer,
2143            &legacy_bind_project,
2144            relay_capabilities,
2145        )
2146        .map_err(|err| {
2147            RouterError::backend(
2148                0,
2149                frame.header.corr,
2150                format!("failed to encode route.bind request: {err}"),
2151            )
2152        })?;
2153        let relay_frame = Frame::build_with_version(
2154            negotiated_ver,
2155            FrameType::Request,
2156            control_flags(),
2157            0,
2158            0,
2159            relay_corr,
2160            relay_body,
2161        )
2162        .map_err(RouterError::FrameBuild)?;
2163
2164        timings.enter(RouteOpenPhase::BindSend);
2165        // Enqueueing the bind spends the same absolute budget as its ack.
2166        let sent = timeout_at(
2167            relay_deadline,
2168            module_sink.send_upgrade_fenced(
2169                relay_frame,
2170                RouterError::DaemonUpgrade {
2171                    channel: 0,
2172                    epoch: 0,
2173                    corr: frame.header.corr,
2174                },
2175            ),
2176        )
2177        .await;
2178        timings.enter(RouteOpenPhase::Admission);
2179        let Ok(sent) = sent else {
2180            // Never enqueued: the module's queue, not its bind handler, was
2181            // slow, so the ack-timeout breaker is not charged.
2182            reservation.release_and_disarm();
2183            breaker.record_inconclusive();
2184            return Ok(vec![self.unsent_bind_timeout_refusal(
2185                ctx,
2186                &caller,
2187                &frame,
2188                &target_module_id,
2189            )?]);
2190        };
2191        if let Err(err) = sent {
2192            reservation.release_and_disarm();
2193            if matches!(err, RouterError::DaemonUpgrade { .. }) {
2194                breaker.record_inconclusive();
2195                let refusal = self.route_open_refusal_frame(
2196                    ctx,
2197                    &caller,
2198                    &frame,
2199                    &target_module_id,
2200                    "daemon_upgrade",
2201                    "module_reloading",
2202                    "daemon upgrade has fenced route admission",
2203                )?;
2204                return Ok(self.deliver_route_open_fence_refusal(ctx, refusal));
2205            }
2206            return Ok(vec![self.route_open_refusal_frame(
2207                ctx,
2208                &caller,
2209                &frame,
2210                &target_module_id,
2211                "relay_send_failed",
2212                "target_unavailable",
2213                err.to_string(),
2214            )?]);
2215        }
2216
2217        #[cfg(test)]
2218        if let Some(hold) = &self.route_bind_relay_sent_hold {
2219            // First wait: tell the test the bind is queued. Second wait: stay
2220            // here until the test has driven whatever it wants to happen
2221            // between queueing the bind and marking it enqueued.
2222            hold.wait().await;
2223            hold.wait().await;
2224        }
2225
2226        // A missing relay is not by itself an abandoned bind: the module may
2227        // already have acked it and the route may be committed. Only a relay
2228        // dropped without any module reply needs this GOODBYE; one a reply
2229        // settled has already had its GOODBYE decided by the reply path.
2230        if self
2231            .forwarding
2232            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
2233            .map_err(RouterError::Forwarding)?
2234            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
2235        {
2236            self.send_abandoned_route_bind_goodbye(
2237                &module_sink,
2238                negotiated_ver,
2239                module_channel,
2240                module_epoch,
2241            );
2242        }
2243
2244        timings.enter(RouteOpenPhase::BindAckWait);
2245        let outcome = timeout_at(relay_deadline, receiver).await;
2246        timings.enter(RouteOpenPhase::Admission);
2247        match outcome {
2248            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
2249                reservation.disarm();
2250                if breaker.record_accepted() {
2251                    info!(
2252                        module_id = %target_module_id,
2253                        "route.bind breaker closed: the probe was accepted"
2254                    );
2255                }
2256                self.observe_route_open_accept(
2257                    ctx,
2258                    &target_module_id,
2259                    &route_principal_label,
2260                    &caller.scope,
2261                );
2262                Ok(Vec::new())
2263            }
2264            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
2265                reservation.release_and_disarm();
2266                // A module that says no in microseconds is healthy. Rejection
2267                // is a different condition with its own refusal and must not
2268                // move the breaker.
2269                breaker.record_inconclusive();
2270                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
2271            }
2272            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
2273                reservation.release_and_disarm();
2274                breaker.record_inconclusive();
2275                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
2276            }
2277            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
2278                reservation.release_and_disarm();
2279                breaker.record_inconclusive();
2280                // Fires when the module's connection closes while a relayed
2281                // bind is pending -- typically a caller racing a module restart
2282                // whose bind was relayed BEFORE the drain mark went up. Logged
2283                // because the caller sees only its own error and the fleet has
2284                // already spent one diagnosis round unable to tell this arm
2285                // from a relay timeout without daemon-side evidence.
2286                tracing::warn!(
2287                    module_id = %target_module_id,
2288                    "route.bind relay abandoned: {message}"
2289                );
2290                Ok(vec![self.route_open_refusal_frame(
2291                    ctx,
2292                    &caller,
2293                    &frame,
2294                    &target_module_id,
2295                    "relay_abandoned",
2296                    "target_unavailable",
2297                    message,
2298                )?])
2299            }
2300            Ok(Err(_)) => {
2301                reservation.release_and_disarm();
2302                breaker.record_inconclusive();
2303                Ok(vec![self.route_open_refusal_frame(
2304                    ctx,
2305                    &caller,
2306                    &frame,
2307                    &target_module_id,
2308                    "relay_waiter_canceled",
2309                    "target_unavailable",
2310                    "route.bind relay waiter was canceled before the module responded",
2311                )?])
2312            }
2313            Err(_) => {
2314                reservation.release_and_disarm();
2315                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
2316                // answer at all is the one condition a fast refusal can
2317                // usefully stand in for; every other arm already answered.
2318                if let Some(opened) = breaker.record_timeout(
2319                    self.route_bind_breaker_threshold,
2320                    self.route_bind_breaker_cooldown,
2321                ) {
2322                    warn!(
2323                        module_id = %target_module_id,
2324                        consecutive_timeouts = opened.consecutive_timeouts,
2325                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
2326                        reopened_after_probe = opened.reopened_after_probe,
2327                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
2328                    );
2329                }
2330                // The generous budget just burned to no answer: the module is
2331                // registered and its connection is up, but its bind handler sat
2332                // on the ack for the full budget (warm-on-bind, cold configure,
2333                // or a wedged handler). Every earlier unavailability shape
2334                // fast-refuses BEFORE the relay, so this arm firing means the
2335                // slowness is module-side -- log it so the per-module timeline
2336                // is reconstructable without client audit rows.
2337                tracing::warn!(
2338                    module_id = %target_module_id,
2339                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
2340                    "route.bind relay timed out: module did not ack within budget"
2341                );
2342                Ok(vec![self.route_open_refusal_frame(
2343                    ctx,
2344                    &caller,
2345                    &frame,
2346                    &target_module_id,
2347                    "relay_timed_out",
2348                    "module_timeout",
2349                    format!(
2350                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
2351                        route_bind_relay_timeout
2352                    ),
2353                )?])
2354            }
2355        }
2356    }
2357}
2358
2359fn target_module_id(target: &RouteTarget) -> &str {
2360    match target {
2361        RouteTarget::ToolProvider { module_id }
2362        | RouteTarget::ManagementSurface { module_id }
2363        | RouteTarget::InternalService { module_id, .. } => module_id,
2364    }
2365}
2366
2367fn target_has_required_role(
2368    target: &RouteTarget,
2369    roles: &[crate::registry::AdmissionRole],
2370) -> bool {
2371    use crate::registry::AdmissionRole;
2372    roles.iter().any(|role| match (target, role) {
2373        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
2374        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
2375        (
2376            RouteTarget::InternalService { service_id, .. },
2377            AdmissionRole::InternalService(provided),
2378        ) => service_id == provided,
2379        _ => false,
2380    })
2381}
2382
2383pub(super) fn is_routable_role(role: &ProviderRole) -> bool {
2384    matches!(
2385        role,
2386        ProviderRole::ToolProvider { .. }
2387            | ProviderRole::ManagementSurface { .. }
2388            | ProviderRole::InternalService { .. }
2389    )
2390}
2391
2392/// The caller of one `route.open`, as its `route.open refused` line names it.
2393///
2394/// A connection id alone cannot name a caller after the fact: ids restart at
2395/// every daemon restart, so the same number belongs to different modules
2396/// before and after one. These three fields are what the refused line needs
2397/// to be attributable on its own, and they are rendered with the same helpers
2398/// as the `route.open accepted` line so both directions grep alike.
2399pub(super) struct RouteOpenCaller {
2400    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
2401    /// when the request presented a consumer identity whose launch nonce did
2402    /// not verify. The claimed module id is never printed as a principal.
2403    pub(super) principal: String,
2404    /// `none` for an unscoped open; the admitted stamp's label once scope
2405    /// admission issued one; before that, the requested selector's label.
2406    pub(super) scope: String,
2407    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
2408    /// because it is a string the caller chose.
2409    pub(super) harness: String,
2410}
2411
2412impl RouteOpenCaller {
2413    fn new(
2414        principal: Option<&Principal>,
2415        scope: Option<&ScopeSelector>,
2416        identity: &BindIdentity,
2417    ) -> Self {
2418        Self {
2419            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
2420            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
2421            harness: bounded_log_text(&identity.harness),
2422        }
2423    }
2424
2425    /// For a refusal that has no parsed request at hand: names whatever the
2426    /// frame still says, and `unknown` where it says nothing parseable.
2427    pub(super) fn unknown() -> Self {
2428        Self {
2429            principal: "unknown".to_string(),
2430            scope: "unknown".to_string(),
2431            harness: "unknown".to_string(),
2432        }
2433    }
2434}
2435
2436/// Longest client-chosen text (a scope ref, a harness) a route.open log line
2437/// prints before cutting it.
2438const MAX_LOGGED_TEXT_CHARS: usize = 64;
2439
2440/// `value` Debug-quoted, so control characters land escaped and cannot forge
2441/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
2442/// `…` inside the quotes so one request cannot flood the line.
2443fn bounded_log_text(value: &str) -> String {
2444    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
2445    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
2446        bounded.push('…');
2447    }
2448    format!("{bounded:?}")
2449}
2450
2451/// The `scope=` field of the `route.open accepted` line, from the stamp that
2452/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
2453/// so a ref holding control characters cannot forge a log line, and cut to 64
2454/// characters with a trailing `…` to bound the line. The bind proof and the
2455/// scope's attributes never appear.
2456fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
2457    use subc_protocol::scope::ScopeKind;
2458    let kind = match stamp.kind {
2459        ScopeKind::Head => "head",
2460        ScopeKind::Worker => "worker",
2461        ScopeKind::Ephemeral => "ephemeral",
2462        ScopeKind::Federated => "federated",
2463        _ => "unknown",
2464    };
2465    format!(
2466        "{kind}/{}/{}@{}",
2467        principal_label(&stamp.owner),
2468        bounded_log_text(&stamp.scope_ref),
2469        stamp.scope_epoch
2470    )
2471}
2472
2473/// The `scope=` field of a `route.open refused` line for an open refused
2474/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
2475/// The kind is not known yet, so the literal `requested` stands in its place.
2476/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
2477/// owner it has not been checked against the configured modules: a quoted
2478/// owner means the value was never validated. The bind proof never appears.
2479fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
2480    let epoch = selector
2481        .scope_epoch
2482        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
2483    format!(
2484        "requested/{}/{}@{epoch}",
2485        bounded_log_text(&principal_label(&selector.owner)),
2486        bounded_log_text(&selector.scope_ref),
2487    )
2488}
2489
2490pub(super) fn principal_label(principal: &Principal) -> String {
2491    match principal {
2492        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
2493        Principal::Direct => "direct".to_string(),
2494        other => format!("{other:?}"),
2495    }
2496}