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            // A module the supervisor is restarting or reloading can still hold
1504            // a registration: the old process before its connection closes, or
1505            // a new one that registered while the supervisor was draining. The
1506            // forwarding table does not see that as draining, but the consumer
1507            // should still be told to retry soon, exactly as for the drain
1508            // above, rather than that the target is unavailable.
1509            if process_liveness.process_replacing(&target_module_id) {
1510                return Ok(vec![self.route_open_refusal_frame(
1511                    ctx,
1512                    &caller,
1513                    &frame,
1514                    &target_module_id,
1515                    "reloading",
1516                    "module_reloading",
1517                    format!("module_id '{target_module_id}' is reloading"),
1518                )?]);
1519            }
1520            return Ok(vec![self.route_open_refusal_frame(
1521                ctx,
1522                &caller,
1523                &frame,
1524                &target_module_id,
1525                "supervisor_not_live",
1526                "target_unavailable",
1527                format!("module_id '{target_module_id}' is not live"),
1528            )?]);
1529        }
1530
1531        if !self
1532            .forwarding
1533            .has_live_module_connection(&target_module_id)
1534            .map_err(RouterError::Forwarding)?
1535        {
1536            return Ok(vec![self.route_open_refusal_frame(
1537                ctx,
1538                &caller,
1539                &frame,
1540                &target_module_id,
1541                "no_forwarding_connection",
1542                "target_unavailable",
1543                format!("module_id '{target_module_id}' has no live forwarding connection"),
1544            )?]);
1545        }
1546
1547        if let Some(error) =
1548            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
1549        {
1550            self.observe_route_open_refusal(
1551                ctx,
1552                &caller,
1553                &target_module_id,
1554                "op_not_allowed",
1555                "op_not_allowed",
1556            );
1557            return Ok(vec![error]);
1558        }
1559
1560        let principal = match (&attested, consumer_identity.is_some()) {
1561            // A claim-bound connection whose launch ended attests nothing,
1562            // and it must never fall back to opening as `direct`.
1563            (None, false) => {
1564                self.observe_route_open_refusal(
1565                    ctx,
1566                    &caller,
1567                    &target_module_id,
1568                    "registration_channel_closed",
1569                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1570                );
1571                return Ok(vec![control_error_frame(
1572                    &frame,
1573                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1574                    "the claim binding's launch has ended",
1575                )?]);
1576            }
1577            _ => match self.route_open_principal_attested(
1578                &frame,
1579                consumer_identity,
1580                attested.as_ref().map(|attested| attested.principal.clone()),
1581            )? {
1582                Ok(principal) => principal,
1583                Err(error) => {
1584                    self.observe_route_open_refusal(
1585                        ctx,
1586                        &caller,
1587                        &target_module_id,
1588                        "bad_consumer_identity",
1589                        "bad_consumer_identity",
1590                    );
1591                    return Ok(vec![error]);
1592                }
1593            },
1594        };
1595        let attested = attested.expect("an attested principal was resolved above");
1596        timings.principal = principal_label(&principal);
1597
1598        // The opener's spawn authority, read once here and carried with the
1599        // relay; nothing below reads its record again.
1600        let Ok(mut caller_capture) = attested.capture() else {
1601            self.observe_route_open_refusal(
1602                ctx,
1603                &caller,
1604                &target_module_id,
1605                "registration_channel_closed",
1606                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1607            );
1608            return Ok(vec![control_error_frame(
1609                &frame,
1610                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
1611                "the opener's launch has ended",
1612            )?]);
1613        };
1614        // The caller-side checks below read the opener's own spawn: its
1615        // module from its record and its manifest from its own registration,
1616        // never another launch's active registration under the same id.
1617        let caller_module_id = match &attested.spawn {
1618            Some((record, _)) => Some(record.module_id().to_owned()),
1619            None => match &principal {
1620                Principal::Reserved { module_id } => Some(module_id.clone()),
1621                _ => None,
1622            },
1623        };
1624
1625        // Only Callosum can attest a production phone build. Consume the raw
1626        // claim here; opted-in targets receive only the honoured peer fact.
1627        let build_class = identity.build_class.take().filter(|build_class| {
1628            if caller_module_id.as_deref() == Some("callosum") {
1629                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
1630            } else {
1631                if self
1632                    .build_class_warned
1633                    .lock()
1634                    .unwrap_or_else(|p| p.into_inner())
1635                    .insert(ctx.connection_id)
1636                {
1637                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
1638                        "ignoring build_class from a non-Callosum opener");
1639                }
1640                false
1641            }
1642        });
1643
1644        // This is attested, control-plane policy for supervised module origins.
1645        // Keep it before route reservation and out of the opaque forwarding hot
1646        // path: data frames must never acquire a per-frame capability check.
1647        let opening_registration = self.caller_registration(&attested, &admission_registry);
1648        if let Some(opening_registration) = &opening_registration {
1649            let opening_module_id = opening_registration.module_id.as_str();
1650            if let Some(capability) = denied_capability(
1651                opening_registration.capabilities.as_ref(),
1652                registration.capabilities.as_ref(),
1653            ) {
1654                warn!(
1655                    opening_module_id,
1656                    target_module_id,
1657                    capability,
1658                    "refusing route.open because an attested capability deny edge matches"
1659                );
1660                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
1661                    &frame,
1662                    &target_module_id,
1663                    "capability_deny_edge",
1664                    "capability_forbidden",
1665                    format!(
1666                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
1667                    ),
1668                )?]);
1669            }
1670        }
1671
1672        if admission_facts.is_some() {
1673            let carrier_matches = caller_module_id.is_some()
1674                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
1675            if !carrier_matches {
1676                return Ok(vec![self.route_open_refusal_frame(
1677                    ctx,
1678                    &caller,
1679                    &frame,
1680                    &target_module_id,
1681                    "admission_facts_carrier_not_permitted",
1682                    "admission_facts_not_permitted",
1683                    "admission facts may only be carried by the configured reserved module",
1684                )?]);
1685            }
1686
1687            let target_allowed = self
1688                .admission_facts_targets
1689                .as_ref()
1690                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
1691            if !target_allowed {
1692                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
1693                    &frame,
1694                    &target_module_id,
1695                    "admission_facts_target_not_listed",
1696                    "admission_facts_target_not_allowed",
1697                    format!(
1698                        "admission facts are not permitted for target module_id '{target_module_id}'"
1699                    ),
1700                )?]);
1701            }
1702
1703            // Keep the value opaque to subc. The downstream admission validator owns
1704            // schema and semantic checks; this daemon only enforces carrier authority
1705            // and the configured destination allowlist.
1706        }
1707
1708        // Scope admission, on the attested principal above and never on the
1709        // request body. The tag read here travels with the pending bind and is
1710        // compared with the published one at commit, so a sync between here
1711        // and the module's ack refuses the open instead of binding a stamp
1712        // that is no longer true.
1713        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
1714            None => (None, None, false),
1715            Some(selector) => {
1716                let owner_configured = match &selector.owner {
1717                    // A reserved owner counts as configured from before its
1718                    // process is spawned (see `SupervisorHandle::is_configured`).
1719                    // So an owner that has not synced its scopes yet is refused
1720                    // as retryable (`scope_not_synced`), not as one that will
1721                    // never sync.
1722                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
1723                    _ => false,
1724                };
1725                let mut scopes = self
1726                    .scopes
1727                    .write()
1728                    .unwrap_or_else(|poisoned| poisoned.into_inner());
1729                let admitted = crate::scopes::admission::admit_route(
1730                    &scopes,
1731                    &admission_registry,
1732                    &principal,
1733                    &target_module_id,
1734                    Some(selector),
1735                    owner_configured,
1736                    crate::scopes::admission::AdmissionMode::Open,
1737                )
1738                .map(|route| {
1739                    let admission = route.scope.expect("scoped admission");
1740                    let bound = scopes.reserve_bind(
1741                        &admission,
1742                        &principal,
1743                        ctx.connection_id,
1744                        selector.hold_presence,
1745                    );
1746                    (admission, bound)
1747                });
1748                match admitted {
1749                    Ok((admission, bound)) => {
1750                        (Some(bound), Some(admission.stamp), admission.stamp_required)
1751                    }
1752                    Err(refusal) => {
1753                        return Ok(vec![self.route_open_refusal_frame(
1754                            ctx,
1755                            &caller,
1756                            &frame,
1757                            &target_module_id,
1758                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
1759                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
1760                            refusal.message,
1761                        )?]);
1762                    }
1763                }
1764            }
1765        };
1766        // From here on a refusal names the scope by the stamp admission
1767        // issued, exactly as the `route.open accepted` line does.
1768        if let Some(stamp) = &scope_stamp {
1769            caller.scope = route_open_scope_label(stamp);
1770        }
1771        // Decided from the admitted stamp, before any field of it is stripped
1772        // for a target that lacks the capability to read it.
1773        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
1774            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
1775        }
1776
1777        // Allow resolvable missing-tail paths so a vanished directory does not
1778        // prevent reopening an existing session for cleanup. Binding does not
1779        // authorize creation of durable provider state.
1780        //
1781        // Resolve real paths rather than lexical cleanup: canonicalize the
1782        // longest existing ancestor and append the missing tail, retaining the
1783        // path's real existing ancestry even when a leaf is missing.
1784        timings.enter(RouteOpenPhase::ProjectRoot);
1785        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
1786            Ok(project) => project,
1787            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
1788        };
1789        timings.enter(RouteOpenPhase::Admission);
1790        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
1791            Ok(root) => root,
1792            Err(err) => {
1793                return Ok(vec![control_error_frame(
1794                    &frame,
1795                    "invalid_project_root",
1796                    err.to_string(),
1797                )?])
1798            }
1799        };
1800        // Compute compatibility project fields before stripping optional stamp
1801        // members. Preserve the canonical opener root and its project ID,
1802        // including absence. For rootless openers, use stamp workdir or `/`, and
1803        // opener ID, else stamp ID, else no ID. Emit these identity fields only
1804        // to targets without bind-no-project/v1.
1805        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
1806
1807        // Last gate before any relay work, and deliberately after the cheap
1808        // registry and availability checks above: those name a more precise
1809        // condition (unknown, removed, reloading) and a caller is better served
1810        // by the precise code than by this one.
1811        //
1812        // Everything below this point costs an egress permit, a reserved handle
1813        // pair and, if the module does not answer, the whole relay budget. The
1814        // reader no longer waits for that budget, so cap each target explicitly;
1815        // serial dispatch used to provide the accidental cap of one relay per
1816        // connection. Admission is a mutex-protected count and never waits.
1817        let _concurrency_guard = match self
1818            .route_bind_concurrency
1819            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
1820        {
1821            Ok(guard) => guard,
1822            Err(in_flight) => {
1823                return Ok(vec![self.route_open_target_capacity_refusal(
1824                    ctx,
1825                    &caller,
1826                    &frame,
1827                    &target_module_id,
1828                    in_flight,
1829                )?]);
1830            }
1831        };
1832
1833        // A module that has already burned the whole budget `threshold` times
1834        // in a row does not get to charge it again until a probe says it recovered.
1835        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
1836            RouteBindAdmission::Admitted { guard, probe } => {
1837                if probe {
1838                    info!(
1839                        module_id = %target_module_id,
1840                        connection_id = ctx.connection_id.get(),
1841                        "route.bind breaker half-open: admitting one probe"
1842                    );
1843                }
1844                guard
1845            }
1846            RouteBindAdmission::Refused {
1847                consecutive_timeouts,
1848                retry_in,
1849                probe_in_flight,
1850            } => {
1851                return Ok(vec![self.route_open_breaker_refusal_frame(
1852                    ctx,
1853                    &caller,
1854                    &frame,
1855                    &target_module_id,
1856                    consecutive_timeouts,
1857                    retry_in,
1858                    probe_in_flight,
1859                )?]);
1860            }
1861        };
1862
1863        let operator_app = self
1864            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
1865            .await;
1866        // Resolve the per-module budget here so the wait matches the operator's
1867        // intent for this specific target. A per-module override in
1868        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
1869        // daemons) wins over the daemon-wide default.
1870        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
1871        let relay_deadline = Instant::now() + route_bind_relay_timeout;
1872        let production_peer_build =
1873            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
1874        timings.enter(RouteOpenPhase::EgressReservation);
1875        let pending = match self
1876            .forwarding
1877            .begin_route_bind_relay_for(
1878                ctx.connection_id,
1879                ctx.egress.clone(),
1880                response_version(&frame),
1881                frame.header.corr,
1882                &target_module_id,
1883                principal.clone(),
1884                bound_scope,
1885                project_root,
1886                identity.harness.clone(),
1887                build_class,
1888                operator_app.clone(),
1889                crate::forwarding::RouteAuthority {
1890                    incarnation: self.supervisor.daemon_incarnation(),
1891                    caller: caller_capture
1892                        .as_ref()
1893                        .map(|caller| caller.authority.pair()),
1894                    capability_fence: route_bind_settlement::fence(
1895                        &opening_registration,
1896                        registration,
1897                    ),
1898                },
1899                relay_deadline,
1900                busy_refusals == Some(true),
1901                accepts_close_reasons,
1902            )
1903            .await
1904        {
1905            Ok(pending) => pending,
1906            Err(err) => {
1907                return Ok(vec![self.route_open_refusal_frame(
1908                    ctx,
1909                    &caller,
1910                    &frame,
1911                    &target_module_id,
1912                    "relay_reservation_failed",
1913                    forwarding_error_code(&err),
1914                    err.to_string(),
1915                )?])
1916            }
1917        };
1918        timings.enter(RouteOpenPhase::Admission);
1919        let crate::forwarding::PendingRouteBindRelay {
1920            endpoint,
1921            module_sink,
1922            negotiated_ver,
1923            client_channel,
1924            client_epoch,
1925            module_channel,
1926            module_epoch,
1927            corr: relay_corr,
1928            receiver,
1929        } = pending;
1930        let mut reservation =
1931            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
1932
1933        // Reserving egress can wait while a module reconnects or a swap cuts
1934        // over. Check the relay's captured connection, not the earlier by-id
1935        // lookup: the original module's flow/run capabilities cannot authorize
1936        // its replacement. The captured sink stays bound to that connection.
1937        let relay_registration = self
1938            .registry
1939            .route_registration_by_connection(endpoint.connection_id)
1940            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
1941        let relay_capabilities = relay_registration
1942            .as_ref()
1943            .and_then(|registration| registration.capabilities.as_ref());
1944        if let Some(selector) = &scope {
1945            // Egress reservation may wait across a scope update. Recheck the
1946            // proof against the current record before sending the captured bind.
1947            if let Err(refusal) = self
1948                .scopes
1949                .read()
1950                .unwrap_or_else(|poisoned| poisoned.into_inner())
1951                .check_bind_proof(&principal, selector)
1952            {
1953                reservation.release_and_disarm();
1954                return Ok(vec![self.route_open_refusal_frame(
1955                    ctx,
1956                    &caller,
1957                    &frame,
1958                    &target_module_id,
1959                    refusal.code,
1960                    refusal.code,
1961                    refusal.message,
1962                )?]);
1963            }
1964        }
1965        if let Some(stamp) = scope_stamp.as_ref() {
1966            if let Err(refusal) = crate::scopes::check_target_required_stamp(
1967                stamp_required,
1968                &target_module_id,
1969                relay_capabilities,
1970            )
1971            .and_then(|()| {
1972                crate::scopes::check_target_flow_support(
1973                    stamp,
1974                    &target_module_id,
1975                    relay_capabilities,
1976                )
1977            })
1978            .and_then(|()| {
1979                crate::scopes::check_target_agent_run_support(
1980                    stamp,
1981                    &target_module_id,
1982                    relay_capabilities,
1983                )
1984            }) {
1985                reservation.release_and_disarm();
1986                return Ok(vec![self.route_open_refusal_frame(
1987                    ctx,
1988                    &caller,
1989                    &frame,
1990                    &target_module_id,
1991                    refusal.code,
1992                    refusal.code,
1993                    refusal.message,
1994                )?]);
1995            }
1996        }
1997
1998        // Use the admitted scope before compatibility removes fields from the bind.
1999        let caller_attestation = self.caller_for_target(
2000            caller_capture.as_ref(),
2001            relay_capabilities,
2002            &target_module_id,
2003            &principal,
2004            scope_stamp
2005                .as_ref()
2006                .and_then(|stamp| stamp.project_id.as_deref()),
2007        );
2008        // Older readers may reject unknown fields. Select optional fields from
2009        // the captured endpoint's declaration, including on unscoped binds.
2010        if scope_stamp
2011            .as_ref()
2012            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
2013            && !crate::scopes::target_supports_federated(relay_capabilities)
2014        {
2015            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
2016            scope_stamp = None;
2017        }
2018        if !relay_capabilities.is_some_and(|caps| {
2019            caps.provides
2020                .iter()
2021                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
2022        }) {
2023            if let Some(stamp) = scope_stamp.as_mut() {
2024                stamp.workdir = None;
2025                stamp.project_id = None;
2026            }
2027        }
2028        // A worker run has no agent_id; on_behalf_of_agent is its only agent
2029        // attribution. The run gate above has already required the target to
2030        // declare `worker-runs/v1`, which promises to read both
2031        // `on_behalf_of_agent` and `call_mode`.
2032        let worker_run = scope_stamp
2033            .as_ref()
2034            .is_some_and(crate::scopes::is_worker_run)
2035            && relay_capabilities.is_some_and(|caps| {
2036                caps.provides
2037                    .iter()
2038                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
2039            });
2040        if !worker_run
2041            && !relay_capabilities.is_some_and(|caps| {
2042                caps.provides
2043                    .iter()
2044                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
2045            })
2046        {
2047            if let Some(stamp) = scope_stamp.as_mut() {
2048                stamp.attributes.on_behalf_of_agent = None;
2049            }
2050        }
2051        if !relay_capabilities.is_some_and(|caps| {
2052            caps.provides
2053                .iter()
2054                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
2055        }) {
2056            if let Some(stamp) = scope_stamp.as_mut() {
2057                stamp.attributes.flow_version = None;
2058                stamp.attributes.flow_code_hash = None;
2059                stamp.attributes.flow_install_id = None;
2060            }
2061        }
2062        let call_mode = if worker_run
2063            || relay_capabilities
2064                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
2065        {
2066            Some(derive_call_mode(scope_stamp.as_ref()))
2067        } else {
2068            if let Some(stamp) = scope_stamp.as_mut() {
2069                stamp.expires_at_ms = None;
2070            }
2071            None
2072        };
2073
2074        debug!(
2075            connection_id = ctx.connection_id.get(),
2076            client_channel,
2077            client_epoch,
2078            module_channel,
2079            module_epoch,
2080            "reserved route handle pair"
2081        );
2082        // Rendered BEFORE the move into the relay, because the accept arm below
2083        // is where it is logged and the principal is gone by then.
2084        let route_principal_label = principal_label(&principal);
2085        let relay = ModuleControlRequest::RouteBind {
2086            route_channel: module_channel,
2087            epoch: module_epoch,
2088            target,
2089            identity,
2090            principal: Some(principal),
2091            consumer_capabilities,
2092            role_versions,
2093            admission_facts,
2094            scope: scope_stamp,
2095            call_mode,
2096        };
2097        let peer = RouteBindPeer::new()
2098            .with_observed_peer(
2099                relay_capabilities
2100                    .is_some_and(|caps| {
2101                        caps.provides
2102                            .iter()
2103                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
2104                    })
2105                    .then(|| {
2106                        self.observed_peers
2107                            .lock()
2108                            .unwrap_or_else(|p| p.into_inner())
2109                            .get(&ctx.connection_id)
2110                            .cloned()
2111                            .unwrap_or_else(ObservedPeer::unobserved)
2112                    }),
2113            )
2114            .with_operator_app(
2115                self.connection_operator_app(operator_app.as_ref())
2116                    .filter(|_| {
2117                        relay_capabilities.is_some_and(|caps| {
2118                            caps.provides
2119                                .iter()
2120                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
2121                        })
2122                    }),
2123            )
2124            .with_caller(caller_attestation)
2125            .with_peer_build(
2126                (production_peer_build
2127                    && relay_capabilities.is_some_and(|caps| {
2128                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
2129                    }))
2130                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
2131            );
2132        let relay_body = crate::bind_compat::encode_bind(
2133            &relay,
2134            &peer,
2135            &legacy_bind_project,
2136            relay_capabilities,
2137        )
2138        .map_err(|err| {
2139            RouterError::backend(
2140                0,
2141                frame.header.corr,
2142                format!("failed to encode route.bind request: {err}"),
2143            )
2144        })?;
2145        let relay_frame = Frame::build_with_version(
2146            negotiated_ver,
2147            FrameType::Request,
2148            control_flags(),
2149            0,
2150            0,
2151            relay_corr,
2152            relay_body,
2153        )
2154        .map_err(RouterError::FrameBuild)?;
2155
2156        timings.enter(RouteOpenPhase::BindSend);
2157        // Enqueueing the bind spends the same absolute budget as its ack.
2158        let sent = timeout_at(
2159            relay_deadline,
2160            module_sink.send_upgrade_fenced(
2161                relay_frame,
2162                RouterError::DaemonUpgrade {
2163                    channel: 0,
2164                    epoch: 0,
2165                    corr: frame.header.corr,
2166                },
2167            ),
2168        )
2169        .await;
2170        timings.enter(RouteOpenPhase::Admission);
2171        let Ok(sent) = sent else {
2172            // Never enqueued: the module's queue, not its bind handler, was
2173            // slow, so the ack-timeout breaker is not charged.
2174            reservation.release_and_disarm();
2175            breaker.record_inconclusive();
2176            return Ok(vec![self.unsent_bind_timeout_refusal(
2177                ctx,
2178                &caller,
2179                &frame,
2180                &target_module_id,
2181            )?]);
2182        };
2183        if let Err(err) = sent {
2184            reservation.release_and_disarm();
2185            if matches!(err, RouterError::DaemonUpgrade { .. }) {
2186                breaker.record_inconclusive();
2187                let refusal = self.route_open_refusal_frame(
2188                    ctx,
2189                    &caller,
2190                    &frame,
2191                    &target_module_id,
2192                    "daemon_upgrade",
2193                    "module_reloading",
2194                    "daemon upgrade has fenced route admission",
2195                )?;
2196                return Ok(self.deliver_route_open_fence_refusal(ctx, refusal));
2197            }
2198            return Ok(vec![self.route_open_refusal_frame(
2199                ctx,
2200                &caller,
2201                &frame,
2202                &target_module_id,
2203                "relay_send_failed",
2204                "target_unavailable",
2205                err.to_string(),
2206            )?]);
2207        }
2208
2209        #[cfg(test)]
2210        if let Some(hold) = &self.route_bind_relay_sent_hold {
2211            // First wait: tell the test the bind is queued. Second wait: stay
2212            // here until the test has driven whatever it wants to happen
2213            // between queueing the bind and marking it enqueued.
2214            hold.wait().await;
2215            hold.wait().await;
2216        }
2217
2218        // A missing relay is not by itself an abandoned bind: the module may
2219        // already have acked it and the route may be committed. Only a relay
2220        // dropped without any module reply needs this GOODBYE; one a reply
2221        // settled has already had its GOODBYE decided by the reply path.
2222        if self
2223            .forwarding
2224            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
2225            .map_err(RouterError::Forwarding)?
2226            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
2227        {
2228            self.send_abandoned_route_bind_goodbye(
2229                &module_sink,
2230                negotiated_ver,
2231                module_channel,
2232                module_epoch,
2233            );
2234        }
2235
2236        timings.enter(RouteOpenPhase::BindAckWait);
2237        let outcome = timeout_at(relay_deadline, receiver).await;
2238        timings.enter(RouteOpenPhase::Admission);
2239        match outcome {
2240            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
2241                reservation.disarm();
2242                if breaker.record_accepted() {
2243                    info!(
2244                        module_id = %target_module_id,
2245                        "route.bind breaker closed: the probe was accepted"
2246                    );
2247                }
2248                self.observe_route_open_accept(
2249                    ctx,
2250                    &target_module_id,
2251                    &route_principal_label,
2252                    &caller.scope,
2253                );
2254                Ok(Vec::new())
2255            }
2256            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
2257                reservation.release_and_disarm();
2258                // A module that says no in microseconds is healthy. Rejection
2259                // is a different condition with its own refusal and must not
2260                // move the breaker.
2261                breaker.record_inconclusive();
2262                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
2263            }
2264            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
2265                reservation.release_and_disarm();
2266                breaker.record_inconclusive();
2267                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
2268            }
2269            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
2270                reservation.release_and_disarm();
2271                breaker.record_inconclusive();
2272                // Fires when the module's connection closes while a relayed
2273                // bind is pending -- typically a caller racing a module restart
2274                // whose bind was relayed BEFORE the drain mark went up. Logged
2275                // because the caller sees only its own error and the fleet has
2276                // already spent one diagnosis round unable to tell this arm
2277                // from a relay timeout without daemon-side evidence.
2278                tracing::warn!(
2279                    module_id = %target_module_id,
2280                    "route.bind relay abandoned: {message}"
2281                );
2282                Ok(vec![self.route_open_refusal_frame(
2283                    ctx,
2284                    &caller,
2285                    &frame,
2286                    &target_module_id,
2287                    "relay_abandoned",
2288                    "target_unavailable",
2289                    message,
2290                )?])
2291            }
2292            Ok(Err(_)) => {
2293                reservation.release_and_disarm();
2294                breaker.record_inconclusive();
2295                Ok(vec![self.route_open_refusal_frame(
2296                    ctx,
2297                    &caller,
2298                    &frame,
2299                    &target_module_id,
2300                    "relay_waiter_canceled",
2301                    "target_unavailable",
2302                    "route.bind relay waiter was canceled before the module responded",
2303                )?])
2304            }
2305            Err(_) => {
2306                reservation.release_and_disarm();
2307                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
2308                // answer at all is the one condition a fast refusal can
2309                // usefully stand in for; every other arm already answered.
2310                if let Some(opened) = breaker.record_timeout(
2311                    self.route_bind_breaker_threshold,
2312                    self.route_bind_breaker_cooldown,
2313                ) {
2314                    warn!(
2315                        module_id = %target_module_id,
2316                        consecutive_timeouts = opened.consecutive_timeouts,
2317                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
2318                        reopened_after_probe = opened.reopened_after_probe,
2319                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
2320                    );
2321                }
2322                // The generous budget just burned to no answer: the module is
2323                // registered and its connection is up, but its bind handler sat
2324                // on the ack for the full budget (warm-on-bind, cold configure,
2325                // or a wedged handler). Every earlier unavailability shape
2326                // fast-refuses BEFORE the relay, so this arm firing means the
2327                // slowness is module-side -- log it so the per-module timeline
2328                // is reconstructable without client audit rows.
2329                tracing::warn!(
2330                    module_id = %target_module_id,
2331                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
2332                    "route.bind relay timed out: module did not ack within budget"
2333                );
2334                Ok(vec![self.route_open_refusal_frame(
2335                    ctx,
2336                    &caller,
2337                    &frame,
2338                    &target_module_id,
2339                    "relay_timed_out",
2340                    "module_timeout",
2341                    format!(
2342                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
2343                        route_bind_relay_timeout
2344                    ),
2345                )?])
2346            }
2347        }
2348    }
2349}
2350
2351fn target_module_id(target: &RouteTarget) -> &str {
2352    match target {
2353        RouteTarget::ToolProvider { module_id }
2354        | RouteTarget::ManagementSurface { module_id }
2355        | RouteTarget::InternalService { module_id, .. } => module_id,
2356    }
2357}
2358
2359fn target_has_required_role(
2360    target: &RouteTarget,
2361    roles: &[crate::registry::AdmissionRole],
2362) -> bool {
2363    use crate::registry::AdmissionRole;
2364    roles.iter().any(|role| match (target, role) {
2365        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
2366        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
2367        (
2368            RouteTarget::InternalService { service_id, .. },
2369            AdmissionRole::InternalService(provided),
2370        ) => service_id == provided,
2371        _ => false,
2372    })
2373}
2374
2375pub(super) fn is_routable_role(role: &ProviderRole) -> bool {
2376    matches!(
2377        role,
2378        ProviderRole::ToolProvider { .. }
2379            | ProviderRole::ManagementSurface { .. }
2380            | ProviderRole::InternalService { .. }
2381    )
2382}
2383
2384/// The caller of one `route.open`, as its `route.open refused` line names it.
2385///
2386/// A connection id alone cannot name a caller after the fact: ids restart at
2387/// every daemon restart, so the same number belongs to different modules
2388/// before and after one. These three fields are what the refused line needs
2389/// to be attributable on its own, and they are rendered with the same helpers
2390/// as the `route.open accepted` line so both directions grep alike.
2391pub(super) struct RouteOpenCaller {
2392    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
2393    /// when the request presented a consumer identity whose launch nonce did
2394    /// not verify. The claimed module id is never printed as a principal.
2395    pub(super) principal: String,
2396    /// `none` for an unscoped open; the admitted stamp's label once scope
2397    /// admission issued one; before that, the requested selector's label.
2398    pub(super) scope: String,
2399    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
2400    /// because it is a string the caller chose.
2401    pub(super) harness: String,
2402}
2403
2404impl RouteOpenCaller {
2405    fn new(
2406        principal: Option<&Principal>,
2407        scope: Option<&ScopeSelector>,
2408        identity: &BindIdentity,
2409    ) -> Self {
2410        Self {
2411            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
2412            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
2413            harness: bounded_log_text(&identity.harness),
2414        }
2415    }
2416
2417    /// For a refusal that has no parsed request at hand: names whatever the
2418    /// frame still says, and `unknown` where it says nothing parseable.
2419    pub(super) fn unknown() -> Self {
2420        Self {
2421            principal: "unknown".to_string(),
2422            scope: "unknown".to_string(),
2423            harness: "unknown".to_string(),
2424        }
2425    }
2426}
2427
2428/// Longest client-chosen text (a scope ref, a harness) a route.open log line
2429/// prints before cutting it.
2430const MAX_LOGGED_TEXT_CHARS: usize = 64;
2431
2432/// `value` Debug-quoted, so control characters land escaped and cannot forge
2433/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
2434/// `…` inside the quotes so one request cannot flood the line.
2435fn bounded_log_text(value: &str) -> String {
2436    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
2437    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
2438        bounded.push('…');
2439    }
2440    format!("{bounded:?}")
2441}
2442
2443/// The `scope=` field of the `route.open accepted` line, from the stamp that
2444/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
2445/// so a ref holding control characters cannot forge a log line, and cut to 64
2446/// characters with a trailing `…` to bound the line. The bind proof and the
2447/// scope's attributes never appear.
2448fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
2449    use subc_protocol::scope::ScopeKind;
2450    let kind = match stamp.kind {
2451        ScopeKind::Head => "head",
2452        ScopeKind::Worker => "worker",
2453        ScopeKind::Ephemeral => "ephemeral",
2454        ScopeKind::Federated => "federated",
2455        _ => "unknown",
2456    };
2457    format!(
2458        "{kind}/{}/{}@{}",
2459        principal_label(&stamp.owner),
2460        bounded_log_text(&stamp.scope_ref),
2461        stamp.scope_epoch
2462    )
2463}
2464
2465/// The `scope=` field of a `route.open refused` line for an open refused
2466/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
2467/// The kind is not known yet, so the literal `requested` stands in its place.
2468/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
2469/// owner it has not been checked against the configured modules: a quoted
2470/// owner means the value was never validated. The bind proof never appears.
2471fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
2472    let epoch = selector
2473        .scope_epoch
2474        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
2475    format!(
2476        "requested/{}/{}@{epoch}",
2477        bounded_log_text(&principal_label(&selector.owner)),
2478        bounded_log_text(&selector.scope_ref),
2479    )
2480}
2481
2482pub(super) fn principal_label(principal: &Principal) -> String {
2483    match principal {
2484        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
2485        Principal::Direct => "direct".to_string(),
2486        other => format!("{other:?}"),
2487    }
2488}