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