Skip to main content

subc_client_rs/
consumer.rs

1use std::{
2    collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
3    error::Error,
4    fmt,
5    future::Future,
6    io,
7    path::{Path, PathBuf},
8    pin::Pin,
9    sync::{
10        atomic::{AtomicBool, AtomicU64, Ordering},
11        Arc, Mutex, MutexGuard, OnceLock,
12    },
13    task::{Context, Poll},
14    time::{Duration, SystemTime, UNIX_EPOCH},
15};
16
17use sha2::{Digest as _, Sha256};
18pub use subc_control::SupervisorEntry;
19use subc_control::{
20    CatalogEntry, ClientControlRequest, ClientControlResponse, ConsumerIdentity, PollKind,
21    RouteOpenReplyExt, RouteOpenRequestExt, ROUTE_CLOSE_REASONS_CAPABILITY,
22};
23/// The spawn snapshot types, re-exported so a caller of
24/// [`SubcConsumer::spawn_snapshot`] needs no direct `subc-control` dependency.
25pub use subc_control::{LiveSpawn, SpawnCursor, SpawnEvent, SpawnEventKind, SpawnSnapshot};
26pub use subc_control::{RouteOpenTarget, RouteOpenTargetKind};
27/// The scope a route is opened under, re-exported so a caller of
28/// [`SubcConsumer::open_route_scoped`] can name the type from this crate.
29pub use subc_protocol::scope::ScopeSelector;
30use subc_protocol::{
31    error_codes, manifest::is_valid_capability_identifier, AdmissionClass, BindIdentity, ErrorBody,
32    Flags, Frame, FrameBuildError, FrameType, Priority, RouteTarget, FLAG_SUBSCRIPTION,
33    SUBC_MODULE_ID_ENV,
34};
35
36use crate::{
37    ActivityCursor, ActivityQueryRequest, ActivityQueryResponse, ActivitySubscribeRequest,
38    ActivitySubscription, RouteHandle,
39};
40use subc_transport::{
41    authenticate_client, connection_file, read_frame, write_frame, AuthError, ConnectionFileError,
42    FrameIoError,
43};
44use tokio::{
45    io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufWriter},
46    net::TcpStream,
47    sync::{mpsc, oneshot, watch, Notify, OwnedSemaphorePermit, Semaphore},
48    task::JoinHandle,
49    time::{sleep, sleep_until, timeout_at, Instant},
50};
51use tokio_util::sync::CancellationToken;
52
53const DEFAULT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(2);
54// Describe is a daemon-local control read. A daemon that cannot answer within
55// two seconds is overloaded or hung; leave the rest of the route's budget for
56// opening without the optional close-reason declaration.
57const CAPABILITY_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
58pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(30);
59// Sized against a real module restart, not a single bind: the daemon drains the
60// module's routes (up to 30s), waits for the old process to stop (up to its stop
61// budget, 25s by default), then boots the new one. A measured prefrontal-core
62// restart kept route.open refused for 62.5s end to end, which a 30s budget gave
63// up on halfway through. 90s covers that window with room for a slow boot. The
64// retries still end at the call's own deadline (`CallOptions::timeout`) when
65// that comes first, so a caller that wants to ride out a restart raises both.
66pub const DEFAULT_ROUTE_RETRY_DEADLINE: Duration = Duration::from_secs(90);
67/// The most route.open requests a consumer keeps outstanding on its connection.
68/// Mirrors the daemon's `MAX_PENDING_ROUTE_OPENS_PER_CONNECTION`
69/// (`crates/subc-daemon/src/server.rs`): the daemon refuses every open beyond
70/// that many with a retryable `target_unavailable`, so sending more at once only
71/// manufactures refusals. Extra opens wait here, first come first served, and the
72/// wait counts against the same deadline as retrying refusals.
73pub const MAX_ROUTE_OPENS_IN_FLIGHT: usize = 8;
74const DEFAULT_RESTORED_DEBOUNCE: Duration = Duration::from_millis(250);
75pub const DEFAULT_LIVENESS_PROBE_WINDOW: Duration = Duration::from_secs(2);
76const EGRESS_BUFFER: usize = 128;
77const DEFAULT_ROUTE_WINDOW: usize = 1024;
78const DEFAULT_SUBSCRIPTION_EVENT_BUFFER: usize = 128;
79const DEFAULT_PUSH_EVENT_BUFFER: usize = 128;
80const REVERSE_REQUEST_UNHANDLED: &str = "reverse_request_unhandled";
81/// The spawn stream's event buffer. A subscription from an old cursor receives the
82/// daemon's whole retained ring at once (4096 events in the current daemon); a smaller
83/// buffer would drop the stream on its own replay. Twice that leaves room for live
84/// events arriving while the replay is being read.
85const SPAWN_EVENT_BUFFER: usize = 8192;
86// Hold the daemon's 1024-entry activity replay plus live entries without ending
87// a healthy subscriber merely because its initial replay arrives in a burst.
88const ACTIVITY_EVENT_BUFFER: usize = 2048;
89
90#[cfg(test)]
91#[path = "activity_consumer_tests.rs"]
92mod activity_consumer_tests;
93
94mod cancellation;
95mod slots;
96use slots::*;
97mod reservation;
98pub use reservation::{CorrelationId, PendingReply, RequestBody, RequestReservation};
99mod catalog;
100mod config_ops;
101mod supervisor_ops;
102use catalog::decode_route_open_response;
103pub use catalog::CatalogSubscription;
104pub use config_ops::{
105    ConfigApplyResponse, ConfigEdit, ConfigEditAction, ConfigFileError, ConfigFileErrorLayer,
106    ConfigModule, ConfigModulesResponse, ConfigPlanRefusal, ConfigPlanView, ConfigSchemaResponse,
107    ConfigSettingsLayer, ConfigShowResponse, ConfigStatus, ConfigSubscription, ConfigThrough,
108    ConfigWatchEvent, Digest,
109};
110
111#[cfg(test)]
112mod reader_skew_tests;
113
114#[cfg(test)]
115mod connection_ops_tests;
116pub use cancellation::{CancelHandle, CancelOutcome};
117use cancellation::{CancelRegistration, UnaryCancel};
118pub use supervisor_ops::{
119    HealthProbeResponse, ServerDescription, StderrTailResponse, SupervisorAck,
120    SupervisorHealthResponse, SupervisorProvenanceResponse,
121};
122
123/// `supervisor.spawn_subscribe` refused a cursor from another daemon incarnation.
124pub const SPAWN_CURSOR_INCARNATION_MISMATCH: &str = "spawn_cursor_incarnation_mismatch";
125/// `supervisor.spawn_subscribe` refused a cursor older than the daemon's retained ring.
126pub const SPAWN_CURSOR_TOO_OLD: &str = "spawn_cursor_too_old";
127/// The daemon dropped a spawn subscriber that fell too far behind.
128pub const SPAWN_SUBSCRIBER_LAGGED: &str = "spawn_subscriber_lagged";
129
130type ReverseRequestFuture =
131    Pin<Box<dyn Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static>>;
132type ReverseRequestHandler =
133    Arc<dyn Fn(Vec<u8>, ReverseRequestContext) -> ReverseRequestFuture + Send + Sync + 'static>;
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct ReverseRequestContext {
137    pub corr: u64,
138    pub method: String,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct ReverseRequestError {
143    message: String,
144}
145
146impl ReverseRequestError {
147    pub fn new(message: impl Into<String>) -> Self {
148        Self {
149            message: message.into(),
150        }
151    }
152}
153
154impl fmt::Display for ReverseRequestError {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        f.write_str(&self.message)
157    }
158}
159
160impl Error for ReverseRequestError {}
161
162#[derive(Default)]
163struct ReverseRequestRegistryState {
164    handlers: HashMap<String, ReverseRequestHandler>,
165    declared_families: Option<BTreeSet<String>>,
166    consumer_capabilities: BTreeSet<String>,
167}
168
169/// Handler registry prepared before route.open. It carries the reverse-request
170/// method families and any extra capability strings added through route options'
171/// `with_consumer_capability` builder.
172#[derive(Clone, Default)]
173pub struct ReverseRequestRegistry {
174    inner: Arc<Mutex<ReverseRequestRegistryState>>,
175}
176
177impl fmt::Debug for ReverseRequestRegistry {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        f.debug_struct("ReverseRequestRegistry")
180            .field("capabilities", &self.capabilities())
181            .field("consumer_capabilities", &self.consumer_capabilities())
182            .finish()
183    }
184}
185
186impl PartialEq for ReverseRequestRegistry {
187    fn eq(&self, other: &Self) -> bool {
188        self.capabilities() == other.capabilities()
189            && self.consumer_capabilities() == other.consumer_capabilities()
190    }
191}
192
193impl Eq for ReverseRequestRegistry {}
194
195impl ReverseRequestRegistry {
196    pub fn new() -> Self {
197        Self::default()
198    }
199
200    pub fn on_request<F, Fut>(
201        &self,
202        method_family: impl Into<String>,
203        handler: F,
204    ) -> Result<(), ReverseRequestRegistrationError>
205    where
206        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
207        Fut: Future<Output = Vec<u8>> + Send + 'static,
208    {
209        self.on_request_fallible(method_family, move |body, ctx| {
210            let future = handler(body, ctx);
211            async move { Ok(future.await) }
212        })
213    }
214
215    pub fn on_request_fallible<F, Fut>(
216        &self,
217        method_family: impl Into<String>,
218        handler: F,
219    ) -> Result<(), ReverseRequestRegistrationError>
220    where
221        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
222        Fut: Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static,
223    {
224        let method_family = method_family.into();
225        if !is_valid_method_family(&method_family) {
226            return Err(ReverseRequestRegistrationError::InvalidFamily(
227                method_family,
228            ));
229        }
230        let mut state = self
231            .inner
232            .lock()
233            .unwrap_or_else(|poisoned| poisoned.into_inner());
234        if state
235            .declared_families
236            .as_ref()
237            .is_some_and(|families| !families.contains(&method_family))
238        {
239            return Err(ReverseRequestRegistrationError::NotDeclared(method_family));
240        }
241        state.handlers.insert(
242            method_family,
243            Arc::new(move |body, ctx| Box::pin(handler(body, ctx))),
244        );
245        Ok(())
246    }
247
248    fn capabilities(&self) -> Vec<String> {
249        let state = self
250            .inner
251            .lock()
252            .unwrap_or_else(|poisoned| poisoned.into_inner());
253        let mut capabilities = state.handlers.keys().cloned().collect::<Vec<_>>();
254        capabilities.sort();
255        capabilities
256    }
257
258    fn declare_consumer_capability(
259        &self,
260        capability: String,
261    ) -> Result<(), ConsumerCapabilityError> {
262        if capability.is_empty()
263            || capability.len() > 64
264            || !capability.bytes().all(|byte| (0x21..=0x7e).contains(&byte))
265        {
266            return Err(ConsumerCapabilityError { capability });
267        }
268
269        self.inner
270            .lock()
271            .unwrap_or_else(|poisoned| poisoned.into_inner())
272            .consumer_capabilities
273            .insert(capability);
274        Ok(())
275    }
276
277    fn consumer_capabilities(&self) -> Vec<String> {
278        self.inner
279            .lock()
280            .unwrap_or_else(|poisoned| poisoned.into_inner())
281            .consumer_capabilities
282            .iter()
283            .cloned()
284            .collect()
285    }
286
287    fn handler(&self, method_family: &str) -> Option<ReverseRequestHandler> {
288        self.inner
289            .lock()
290            .unwrap_or_else(|poisoned| poisoned.into_inner())
291            .handlers
292            .get(method_family)
293            .cloned()
294    }
295
296    pub(crate) fn seal(&self) {
297        let mut state = self
298            .inner
299            .lock()
300            .unwrap_or_else(|poisoned| poisoned.into_inner());
301        if state.declared_families.is_none() {
302            state.declared_families = Some(state.handlers.keys().cloned().collect());
303        }
304    }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub enum ReverseRequestRegistrationError {
309    InvalidFamily(String),
310    NotDeclared(String),
311    NotConsumerRoute,
312}
313
314impl fmt::Display for ReverseRequestRegistrationError {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        match self {
317            Self::InvalidFamily(family) => {
318                write!(f, "invalid reverse-request method family {family:?}")
319            }
320            Self::NotDeclared(family) => write!(
321                f,
322                "reverse-request capability {family:?} was not registered before route.open"
323            ),
324            Self::NotConsumerRoute => {
325                f.write_str("route handle does not belong to a consumer route")
326            }
327        }
328    }
329}
330
331impl Error for ReverseRequestRegistrationError {}
332
333fn is_valid_method_family(value: &str) -> bool {
334    let mut segments = value.split(['.', '_', '-']);
335    segments.next().is_some_and(|segment| {
336        segment
337            .as_bytes()
338            .first()
339            .is_some_and(u8::is_ascii_lowercase)
340            && segment
341                .bytes()
342                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
343    }) && segments.all(|segment| {
344        !segment.is_empty()
345            && segment
346                .bytes()
347                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
348    })
349}
350
351/// Reverse-request handlers live in a process-global map keyed by an id the
352/// `RouteHandle` carries, rather than inside the handle itself.
353///
354/// WHY, so nobody "simplifies" this into the handle later: `RouteHandle` is
355/// `Copy`, deliberately and publicly. Every route-scoped call in this SDK takes
356/// it by value, and the fleet's Rust consumers pass it around freely on that
357/// assumption. An `Arc<ReverseRequestRegistry>` field would make it non-`Copy`
358/// and break every one of those call sites across twelve repositories, for a
359/// lane most of them do not use.
360///
361/// The cost is real and bounded: entries are removed on every teardown path
362/// (`remove_route`, `remove_route_by_handle`, `drain_routes`,
363/// `uninstall_route_handle`, `install_ingress_handle`), so a consumer that opens
364/// and closes routes for its lifetime does not grow. A consumer DROPPED without
365/// closing leaks its remaining entries until process exit, which is the one gap
366/// and is acceptable because nothing else about a dropped consumer is reclaimed
367/// either.
368///
369/// If `RouteHandle` ever stops being `Copy` for another reason, move this into
370/// the handle and delete the map — the indirection exists only to preserve that
371/// property.
372static NEXT_REVERSE_REQUEST_REGISTRY_ID: AtomicU64 = AtomicU64::new(1);
373static REVERSE_REQUEST_REGISTRIES: OnceLock<Mutex<HashMap<u64, ReverseRequestRegistry>>> =
374    OnceLock::new();
375
376fn reverse_request_registries() -> &'static Mutex<HashMap<u64, ReverseRequestRegistry>> {
377    REVERSE_REQUEST_REGISTRIES.get_or_init(|| Mutex::new(HashMap::new()))
378}
379
380pub(crate) fn install_reverse_request_registry(registry: ReverseRequestRegistry) -> u64 {
381    let id = crate::checked_increment(&NEXT_REVERSE_REQUEST_REGISTRY_ID)
382        .expect("reverse-request route registry id exhausted");
383    reverse_request_registries()
384        .lock()
385        .unwrap_or_else(|poisoned| poisoned.into_inner())
386        .insert(id, registry);
387    id
388}
389
390pub(crate) fn route_reverse_request_registry(
391    id: u64,
392) -> Result<ReverseRequestRegistry, ReverseRequestRegistrationError> {
393    if id == 0 {
394        return Err(ReverseRequestRegistrationError::NotConsumerRoute);
395    }
396    reverse_request_registries()
397        .lock()
398        .unwrap_or_else(|poisoned| poisoned.into_inner())
399        .get(&id)
400        .cloned()
401        .ok_or(ReverseRequestRegistrationError::NotConsumerRoute)
402}
403
404fn release_reverse_request_registry(handle: RouteHandle) {
405    let id = handle.reverse_request_registry_id();
406    if id != 0 {
407        reverse_request_registries()
408            .lock()
409            .unwrap_or_else(|poisoned| poisoned.into_inner())
410            .remove(&id);
411    }
412}
413
414/// Capped exponential backoff used for reconnects and transient route-open retry.
415/// Each delay is jittered before it is slept: half of it is kept and the other
416/// half is random.
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub struct RetryBackoff {
419    pub base: Duration,
420    pub cap: Duration,
421    /// Maximum attempts, including the first immediate attempt.
422    pub max_attempts: usize,
423}
424
425impl Default for RetryBackoff {
426    fn default() -> Self {
427        Self {
428            base: Duration::from_millis(100),
429            cap: Duration::from_secs(2),
430            max_attempts: 6,
431        }
432    }
433}
434
435impl RetryBackoff {
436    fn delay_after_attempt(self, attempt: usize) -> Duration {
437        let mut delay = self.base;
438        for _ in 1..attempt {
439            delay = (delay * 2).min(self.cap);
440        }
441        delay
442    }
443}
444
445/// Transport used for the initial connection and every reconnect attempt.
446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447enum ConsumerTransport {
448    /// Use the connection file's TCP endpoint (the default).
449    Tcp,
450    /// Use only `local_endpoint`, re-read on every connection attempt.
451    Local,
452}
453
454/// Options for [`SubcConsumer::connect`].
455#[derive(Debug, Clone, PartialEq, Eq)]
456pub struct ConsumerOptions {
457    pub handshake_timeout: Duration,
458    /// Deadline for channel-0 calls that do not take per-call options.
459    pub call_timeout: Duration,
460    pub reconnect_backoff: RetryBackoff,
461    pub restored_debounce: Duration,
462    /// Window a post-deadline Ping waits for any inbound frame before the connection is
463    /// treated as half-open. Exposed so callers can use a shorter deterministic test window.
464    pub liveness_probe_window: Duration,
465}
466
467impl Default for ConsumerOptions {
468    fn default() -> Self {
469        Self {
470            handshake_timeout: DEFAULT_HANDSHAKE_TIMEOUT,
471            call_timeout: DEFAULT_CALL_TIMEOUT,
472            reconnect_backoff: RetryBackoff::default(),
473            restored_debounce: DEFAULT_RESTORED_DEBOUNCE,
474            liveness_probe_window: DEFAULT_LIVENESS_PROBE_WINDOW,
475        }
476    }
477}
478
479/// A consumer-capability declaration was empty, contained whitespace or
480/// non-printable/non-ASCII bytes, or exceeded 64 bytes.
481#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct ConsumerCapabilityError {
483    capability: String,
484}
485
486impl ConsumerCapabilityError {
487    /// The invalid declaration value.
488    pub fn capability(&self) -> &str {
489        &self.capability
490    }
491}
492
493impl fmt::Display for ConsumerCapabilityError {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        write!(
496            f,
497            "invalid consumer capability {:?}: expected 1-64 printable ASCII bytes without whitespace",
498            self.capability
499        )
500    }
501}
502
503impl Error for ConsumerCapabilityError {}
504
505/// Options for [`SubcConsumer::close_route`].
506#[derive(Debug, Clone)]
507pub struct CloseRouteOptions {
508    /// Scope used to open the cached route. Defaults to `None`, which selects
509    /// only the unscoped entry; other scopes and epochs are never closed here.
510    /// [`SubcConsumer::close_handle`] rejects this option because the handle
511    /// already selects exactly one route.
512    pub scope: Option<ScopeSelector>,
513    /// Await in-flight unary requests on the route to settle naturally before tearing
514    /// it down. Defaults to false: close immediately, settling anything in flight as
515    /// at-most-once failures (outcome_unknown if already sent, not_sent otherwise).
516    pub drain: bool,
517    /// Upper bound on the drain wait (ignored when `drain` is false).
518    pub drain_timeout: Duration,
519    /// Override for the consumer identity used to locate the route being closed;
520    /// when absent, the supervised launch identity identifies the route, except
521    /// on connections created by [`SubcConsumer::connect_operator_app`].
522    /// On claim-bound connections, a legacy nonce identity conflicts with the
523    /// binding; `close_route` refuses it by doing nothing.
524    pub consumer_identity: Option<ConsumerIdentity>,
525    /// Reverse-request handlers plus extra capability strings added through
526    /// [`Self::with_consumer_capability`]. Together, they identify the route being closed.
527    pub reverse_requests: ReverseRequestRegistry,
528    /// The role versions the route being closed was opened with (see
529    /// [`CallOptions::role_versions`]); part of the route's identity.
530    pub role_versions: Option<BTreeMap<String, String>>,
531}
532
533impl Default for CloseRouteOptions {
534    fn default() -> Self {
535        Self {
536            scope: None,
537            drain: false,
538            drain_timeout: DEFAULT_CALL_TIMEOUT,
539            consumer_identity: None,
540            reverse_requests: ReverseRequestRegistry::new(),
541            role_versions: None,
542        }
543    }
544}
545
546impl CloseRouteOptions {
547    /// Add a provider-contract capability declaration to the route identity.
548    ///
549    /// Values are merged with the reverse-request families. For example,
550    /// `tool-result/v1` declares the tool-provider content result format; the
551    /// declaration is not verified and grants no privilege.
552    ///
553    /// Like reverse-request handlers, declarations are kept in the options'
554    /// shared reverse-request state, so options cloned before this call share
555    /// the declaration. Add declarations before cloning options for other
556    /// routes.
557    pub fn with_consumer_capability(
558        self,
559        capability: impl Into<String>,
560    ) -> Result<Self, ConsumerCapabilityError> {
561        self.reverse_requests
562            .declare_consumer_capability(capability.into())?;
563        Ok(self)
564    }
565
566    /// The extra capability strings added with `with_consumer_capability`, not
567    /// the reverse-request handler families. For example, `tool-result/v1` declares
568    /// tool-provider content-result support; declarations are unverified and
569    /// grant nothing.
570    pub fn consumer_capabilities(&self) -> Vec<String> {
571        self.reverse_requests.consumer_capabilities()
572    }
573}
574
575/// Per-call options for [`SubcConsumer::call`].
576#[derive(Debug, Clone, PartialEq, Eq)]
577pub struct CallOptions {
578    /// Scope for a managed call's cached route, including reconnect reopens.
579    /// Each owner/ref/epoch has a separate cache entry, apart from unscoped routes.
580    /// Admission, retries and terminal refusals follow [`SubcConsumer::open_route_scoped`].
581    /// A later call after a scope-related close tries a fresh route; the daemon
582    /// refuses it as `scope_ended` for an old epoch or `scope_not_live` if the
583    /// scope ref is gone. No tombstone is cached.
584    /// Defaults to `None`. Methods using an already-open handle reject this option;
585    /// select the scope when opening the route instead.
586    pub scope: Option<ScopeSelector>,
587    /// Deadline for the whole managed call, including route-open retry and the response wait.
588    pub timeout: Duration,
589    pub priority: Priority,
590    /// Admission behavior stamped into the request frame. Defaults to NORMAL.
591    pub admission_class: AdmissionClass,
592    pub route_retry: RetryBackoff,
593    /// Maximum real-time limit for retrying route.open attempts when the target is temporarily absent.
594    /// Bounds the whole route open, including the first attempt: a zero budget
595    /// means no open is attempted. For a single attempt, allow that attempt's time.
596    pub route_retry_deadline: Duration,
597    /// Explicit consumer identity for route.open; when absent, the supervised
598    /// launch identity is used, except on [`SubcConsumer::connect_operator_app`]
599    /// connections, which omit implicit identity.
600    /// A claim-bound connection rejects legacy nonce identity overrides as not
601    /// sent, rather than changing the connection's authority.
602    pub consumer_identity: Option<ConsumerIdentity>,
603    /// Reverse-request handlers plus extra capability strings added with
604    /// [`Self::with_consumer_capability`]. For example, `tool-result/v1` declares
605    /// tool-provider content-result support. These declarations are unverified
606    /// and grant nothing; both sets are merged and omitted when empty.
607    pub reverse_requests: ReverseRequestRegistry,
608    /// The versions of provider roles this consumer speaks on the route, role
609    /// name to version (`{"tool-provider": "v1"}`), sent on `route.open` and
610    /// forwarded by the daemon to the provider's bind. An unverified
611    /// declaration that grants nothing. Routes that differ only here are
612    /// separate routes, so a legacy route and a versioned one to the same
613    /// target are never shared; an empty map is the same as `None`.
614    ///
615    /// A daemon that does not advertise `route-role-versions/v1`
616    /// ([`subc_protocol::scope::CAP_ROUTE_ROLE_VERSIONS_V1`]) drops the field
617    /// without telling the provider, so check the capability before relying
618    /// on it. A malformed map (see
619    /// [`subc_protocol::session::validate_role_versions`]) is refused by the
620    /// daemon as `invalid_request` and the call fails as not sent.
621    pub role_versions: Option<BTreeMap<String, String>>,
622}
623
624impl Default for CallOptions {
625    fn default() -> Self {
626        Self {
627            scope: None,
628            timeout: DEFAULT_CALL_TIMEOUT,
629            priority: Priority::Interactive,
630            admission_class: AdmissionClass::Normal,
631            route_retry: RetryBackoff::default(),
632            route_retry_deadline: DEFAULT_ROUTE_RETRY_DEADLINE,
633            consumer_identity: None,
634            reverse_requests: ReverseRequestRegistry::new(),
635            role_versions: None,
636        }
637    }
638}
639
640impl CallOptions {
641    fn reject_scope(&self) -> Result<(), CallError> {
642        if self.scope.is_some() {
643            return Err(CallError::not_sent(
644                "CallOptions.scope is not supported here; select the scope with open_route_scoped or a managed call",
645            ));
646        }
647        Ok(())
648    }
649
650    /// Add a provider-contract capability declaration to the route.
651    ///
652    /// The list is merged with reverse-request handler families, sorted and
653    /// de-duplicated. For example, `tool-result/v1` declares the tool-provider
654    /// content result format. This remains an unverified declaration and grants
655    /// no privilege. Invalid values are rejected here, before route.open can be
656    /// sent.
657    ///
658    /// Like reverse-request handlers, declarations are kept in the options'
659    /// shared reverse-request state, so options cloned before this call share
660    /// the declaration. Add declarations before cloning options for other
661    /// routes.
662    pub fn with_consumer_capability(
663        self,
664        capability: impl Into<String>,
665    ) -> Result<Self, ConsumerCapabilityError> {
666        self.reverse_requests
667            .declare_consumer_capability(capability.into())?;
668        Ok(self)
669    }
670
671    /// The extra capability strings added with `with_consumer_capability`, not
672    /// the reverse-request handler families. For example, `tool-result/v1` declares
673    /// tool-provider content-result support; declarations are unverified and
674    /// grant nothing.
675    pub fn consumer_capabilities(&self) -> Vec<String> {
676        self.reverse_requests.consumer_capabilities()
677    }
678}
679
680/// Options for [`SubcConsumer::subscribe`].
681#[derive(Debug, Clone, PartialEq, Eq)]
682pub struct SubscribeOptions {
683    /// Scope for the cached route and its reopen attempts. Defaults to `None`.
684    /// Cache separation and daemon refusals follow [`CallOptions::scope`].
685    /// [`SubcConsumer::subscribe_route`] rejects this option because its handle
686    /// already fixes the scope. A scope-related close ends the subscription;
687    /// it is not automatically reopened under this or any other selector.
688    pub scope: Option<ScopeSelector>,
689    pub priority: Priority,
690    /// Admission behavior stamped into the subscription request. Defaults to NORMAL.
691    pub admission_class: AdmissionClass,
692    /// Maximum number of events buffered for the caller before the subscription is dropped.
693    /// The reader task never awaits a slow event consumer; if this bounded channel fills,
694    /// `closed()` resolves with [`CallError::SubscriptionBackpressure`].
695    pub event_buffer: usize,
696    pub route_retry: RetryBackoff,
697    /// Maximum real-time limit for retrying route.open attempts when the target is temporarily absent.
698    pub route_retry_deadline: Duration,
699    /// Deadline for opening the managed route and queuing the held-open request.
700    /// The subscription itself has no response timeout once the request is sent.
701    pub route_open_timeout: Duration,
702    /// Explicit consumer identity for route.open; when absent, the supervised
703    /// launch identity is used, except on [`SubcConsumer::connect_operator_app`]
704    /// connections, which omit implicit identity.
705    /// Claim-bound connections reject legacy nonce identity overrides as not sent.
706    pub consumer_identity: Option<ConsumerIdentity>,
707    /// Reverse-request handlers plus extra capability strings added with
708    /// [`Self::with_consumer_capability`]. For example, `tool-result/v1` declares
709    /// tool-provider content-result support. These declarations are unverified
710    /// and grant nothing; both sets are merged and omitted when empty.
711    pub reverse_requests: ReverseRequestRegistry,
712    /// The role versions declared on the subscription's route; see
713    /// [`CallOptions::role_versions`].
714    pub role_versions: Option<BTreeMap<String, String>>,
715}
716
717impl Default for SubscribeOptions {
718    fn default() -> Self {
719        Self {
720            scope: None,
721            priority: Priority::Interactive,
722            admission_class: AdmissionClass::Normal,
723            event_buffer: DEFAULT_SUBSCRIPTION_EVENT_BUFFER,
724            route_retry: RetryBackoff::default(),
725            route_retry_deadline: DEFAULT_ROUTE_RETRY_DEADLINE,
726            route_open_timeout: DEFAULT_CALL_TIMEOUT,
727            consumer_identity: None,
728            reverse_requests: ReverseRequestRegistry::new(),
729            role_versions: None,
730        }
731    }
732}
733
734impl SubscribeOptions {
735    /// Add a provider-contract capability declaration to the subscription route.
736    ///
737    /// This merges with reverse-request families. For example, `tool-result/v1`
738    /// declares the tool-provider content result format. The declaration is
739    /// unverified and grants no privilege; invalid values are refused before
740    /// route.open is sent.
741    pub fn with_consumer_capability(
742        self,
743        capability: impl Into<String>,
744    ) -> Result<Self, ConsumerCapabilityError> {
745        self.reverse_requests
746            .declare_consumer_capability(capability.into())?;
747        Ok(self)
748    }
749
750    /// The extra capability strings added with `with_consumer_capability`, not
751    /// the reverse-request handler families. For example, `tool-result/v1` declares
752    /// tool-provider content-result support; declarations are unverified and
753    /// grant nothing.
754    pub fn consumer_capabilities(&self) -> Vec<String> {
755        self.reverse_requests.consumer_capabilities()
756    }
757}
758
759/// Minimal connection lifecycle signal. It is useful for logging and route-cache invalidation,
760/// but callers must not use the consumer epoch as proof that a target provider is current.
761#[derive(Debug, Clone, PartialEq, Eq)]
762pub enum ConnectionState {
763    Dropped,
764    Restored { epoch: u64 },
765}
766
767/// Result of a route-scoped status or liveness poll.
768#[derive(Debug, Clone, PartialEq, Eq)]
769pub struct RoutePollResult {
770    pub handle: RouteHandle,
771    pub status: Option<String>,
772    pub live: Option<bool>,
773}
774
775/// Typed response from the daemon's channel-0 `catalog.list` operation.
776///
777/// Each module entry exposes the provider roles and tool definitions advertised by
778/// that module.
779#[derive(Debug, Clone, serde::Deserialize, PartialEq)]
780pub struct CatalogList {
781    pub generation: u64,
782    #[serde(default)]
783    pub modules: Vec<CatalogEntry>,
784    #[serde(default)]
785    pub subc_ops: Vec<String>,
786}
787
788/// Typed response from the daemon's channel-0 `supervisor.list` operation.
789///
790/// Unlike `catalog.list`, this includes configured modules that are stopped or
791/// disabled, along with their current supervisor state.
792#[derive(Debug, Clone, PartialEq)]
793pub struct SupervisorListResponse {
794    pub generation: u64,
795    pub modules: Vec<SupervisorEntry>,
796    pub daemon: Option<subc_control::DaemonResources>,
797    pub agent_commands: Option<Vec<subc_control::AgentCommandResources>>,
798}
799
800/// A provider-originated push delivered on one live route.
801#[derive(Debug, Clone, PartialEq, Eq)]
802pub struct PushEvent {
803    /// The connection-fenced route identity on which the push arrived.
804    pub handle: RouteHandle,
805    /// Opaque payload bytes sent by the provider.
806    pub body: Vec<u8>,
807}
808
809/// Disposition of one provider push at delivery time, so the two drop causes
810/// land on their own counters (issue #40): the remedies differ.
811enum DroppedPush {
812    Delivered,
813    NoReceiver,
814    ReceiverFull,
815}
816
817/// A parsed daemon-originated channel-0 control push.
818#[derive(Debug, Clone)]
819pub struct ControlPush {
820    /// The push discriminator, e.g. `route.closing` / `route.closed`.
821    pub op: String,
822    /// The full parsed body, `op` included, for op-specific fields.
823    pub body: serde_json::Value,
824}
825
826/// A route-close reason accepted from the daemon control-push wire.
827///
828/// The protocol may add reasons before this SDK is upgraded. Preserve that fact
829/// as [`Self::Unknown`] and classify it conservatively rather than refusing to
830/// deliver the enclosing control push.
831#[derive(Debug, Clone, PartialEq, Eq)]
832#[non_exhaustive]
833pub enum RouteCloseReason {
834    Reload,
835    Restart,
836    AuthorityChanged,
837    Disable,
838    Crash,
839    CapabilityDenied,
840    ScopeEnded,
841    ScopeCarrierRemoved,
842    ScopeDelegationChanged,
843    ScopeParentEnded,
844    Unknown(String),
845}
846
847/// Close reasons understood by this SDK, declared only after the daemon
848/// advertises `route-close-reasons/v1` so older daemons see unchanged requests.
849pub const ACCEPTED_CLOSE_REASONS: &[&str] = &[
850    "reload",
851    "restart",
852    "authority_changed",
853    "disable",
854    "crash",
855    "capability_denied",
856    "scope_ended",
857    "scope_carrier_removed",
858    "scope_delegation_changed",
859    "scope_parent_ended",
860];
861
862/// Why a route ended. Even a planned closure can leave a call's outcome unknown.
863#[derive(Debug, Clone, PartialEq, Eq)]
864#[non_exhaustive]
865pub enum RouteEndReason {
866    Daemon(RouteCloseReason),
867    ClosedByCaller,
868    ConnectionLost,
869    Unknown,
870}
871
872#[derive(Debug, Clone)]
873struct RouteEnd {
874    reason: RouteEndReason,
875    terminal: Option<bool>,
876}
877
878impl From<RouteEndReason> for RouteEnd {
879    fn from(reason: RouteEndReason) -> Self {
880        Self {
881            reason,
882            terminal: None,
883        }
884    }
885}
886
887/// Whether a closed route may be reopened automatically from its reason alone.
888#[derive(Debug, Clone, Copy, PartialEq, Eq)]
889pub enum RouteCloseDisposition {
890    MayReopen,
891    MustNotReopen,
892}
893
894impl RouteCloseReason {
895    /// Decode a wire reason without making a new daemon reason fatal to push delivery.
896    pub fn from_wire(reason: &str) -> Self {
897        match reason {
898            "reload" => Self::Reload,
899            "restart" => Self::Restart,
900            "authority_changed" => Self::AuthorityChanged,
901            "disable" => Self::Disable,
902            "crash" => Self::Crash,
903            "capability_denied" => Self::CapabilityDenied,
904            "scope_ended" => Self::ScopeEnded,
905            "scope_carrier_removed" => Self::ScopeCarrierRemoved,
906            "scope_delegation_changed" => Self::ScopeDelegationChanged,
907            "scope_parent_ended" => Self::ScopeParentEnded,
908            other => Self::Unknown(other.to_string()),
909        }
910    }
911
912    /// Unknown reasons take the strictest action: never reopen on their behalf.
913    pub fn disposition(&self) -> RouteCloseDisposition {
914        match self {
915            Self::Reload | Self::Restart | Self::AuthorityChanged => {
916                RouteCloseDisposition::MayReopen
917            }
918            Self::Disable
919            | Self::Crash
920            | Self::CapabilityDenied
921            | Self::ScopeEnded
922            | Self::ScopeCarrierRemoved
923            | Self::ScopeDelegationChanged
924            | Self::ScopeParentEnded
925            | Self::Unknown(_) => RouteCloseDisposition::MustNotReopen,
926        }
927    }
928}
929
930impl ControlPush {
931    /// Decode the close reason from a route lifecycle push, if this is one.
932    pub fn route_close_reason(&self) -> Option<RouteCloseReason> {
933        matches!(self.op.as_str(), "route.closing" | "route.closed")
934            .then(|| {
935                self.body
936                    .get("reason")?
937                    .as_str()
938                    .map(RouteCloseReason::from_wire)
939            })
940            .flatten()
941    }
942}
943
944/// Managed Rust consumer for subc route calls.
945pub struct SubcConsumer {
946    shared: Arc<Shared>,
947}
948
949/// The daemon's view of this connection at the time of the query.
950/// Recognition may change after revalidation or a reconnect.
951#[non_exhaustive]
952#[derive(Debug, Clone, PartialEq, Eq)]
953pub struct ConnectionFacts {
954    local: bool,
955    operator_app: Option<subc_protocol::peer::OperatorApp>,
956}
957
958impl ConnectionFacts {
959    /// Whether this connection arrived on the Unix socket or Windows named pipe.
960    pub fn local(&self) -> bool {
961        self.local
962    }
963
964    /// The operator app currently recognised for this connection. `route.bind`
965    /// sends it only to targets that advertise `operator-app/v1`.
966    pub fn operator_app(&self) -> Option<&subc_protocol::peer::OperatorApp> {
967        self.operator_app.as_ref()
968    }
969}
970
971/// Failure to ask the daemon to open an installed operator app.
972#[non_exhaustive]
973#[derive(Debug)]
974pub enum AppOpenError {
975    /// A daemon error frame. Codes are open strings so future refusals survive.
976    /// The current checks, in order, are `app_open_not_used`,
977    /// `app_open_disabled`, `app_unknown`, `app_not_installed`, and
978    /// `app_verification_failed` (see `subc_control::APP_OPEN_ERROR_CODES`).
979    /// An already-running app succeeds between the unknown and installed checks.
980    Refused { code: String, message: String },
981    /// A transport or protocol failure rather than a daemon refusal.
982    Call(CallError),
983}
984
985impl fmt::Display for AppOpenError {
986    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
987        match self {
988            Self::Refused { code, message } => write!(f, "{code}: {message}"),
989            Self::Call(err) => err.fmt(f),
990        }
991    }
992}
993
994impl Error for AppOpenError {
995    fn source(&self) -> Option<&(dyn Error + 'static)> {
996        match self {
997            Self::Call(err) => Some(err),
998            Self::Refused { .. } => None,
999        }
1000    }
1001}
1002
1003impl From<CallError> for AppOpenError {
1004    fn from(err: CallError) -> Self {
1005        Self::Call(err)
1006    }
1007}
1008
1009/// A managed unary reply with the module's raw-body declaration preserved.
1010#[non_exhaustive]
1011#[derive(Debug, Clone, PartialEq, Eq)]
1012pub struct CallReply {
1013    body: Vec<u8>,
1014    binary: bool,
1015}
1016
1017impl CallReply {
1018    /// The body bytes, unchanged from the terminal Response frame.
1019    /// A StreamEnd without a Response has an empty body.
1020    pub fn body(&self) -> &[u8] {
1021        &self.body
1022    }
1023
1024    /// Consume the reply and return its body bytes without copying them.
1025    pub fn into_body(self) -> Vec<u8> {
1026        self.body
1027    }
1028
1029    /// Whether the terminal Response carried `FLAG_BINARY` (raw bytes, not JSON).
1030    /// A StreamEnd without a Response returns `false`.
1031    pub fn is_binary(&self) -> bool {
1032        self.binary
1033    }
1034}
1035
1036/// The first terminal outcome of a subscription.
1037#[derive(Debug, Clone, PartialEq)]
1038#[non_exhaustive]
1039pub enum SubscriptionEnd {
1040    Response(Vec<u8>),
1041    StreamEnd,
1042    Error(ErrorBody),
1043    /// An Error frame reported that the established route is no longer usable.
1044    RouteDead(ErrorBody),
1045    RouteClosed {
1046        reason: RouteEndReason,
1047    },
1048    ConnectionLost,
1049    Cancelled,
1050    /// The bounded event channel filled before the caller drained it.
1051    Backpressure,
1052}
1053
1054impl SubscriptionEnd {
1055    /// Whether an Error frame reported that the established route is no longer usable.
1056    pub fn is_route_dead(&self) -> bool {
1057        matches!(self, Self::RouteDead(_))
1058    }
1059}
1060
1061/// A live subscription to a provider event stream.
1062///
1063/// The event receiver yields each `StreamData` payload for the held-open request's
1064/// correlation id. Await [`Subscription::closed`] to learn whether the provider ended
1065/// the stream cleanly (`Response` or `StreamEnd`) or the stream was rejected by an Error frame,
1066/// route GOODBYE, connection drop, or local backpressure. Dropping the subscription
1067/// sends a best-effort Cancel frame, the same as calling [`Subscription::unsubscribe`].
1068pub struct Subscription {
1069    events: mpsc::Receiver<Vec<u8>>,
1070    closed: SubscriptionClosed,
1071    ended: watch::Receiver<Option<SubscriptionEnd>>,
1072    cancel: SubscriptionCancel,
1073}
1074
1075impl Subscription {
1076    /// Receive event payloads emitted as `StreamData` frames for this subscription.
1077    pub fn events(&mut self) -> &mut mpsc::Receiver<Vec<u8>> {
1078        &mut self.events
1079    }
1080
1081    /// Future that resolves when the subscription reaches a terminal state.
1082    ///
1083    /// It resolves with `Ok(())` on `Response`, `StreamEnd` or local unsubscribe, and returns a
1084    /// [`CallError`] for module Error frames, route teardown, connection loss, or
1085    /// event-channel backpressure. Await it after the event receiver returns `None`
1086    /// to distinguish a clean end from an error.
1087    pub fn closed(&mut self) -> &mut SubscriptionClosed {
1088        &mut self.closed
1089    }
1090
1091    /// Wait for the terminal outcome, retaining a Response body or module Error.
1092    ///
1093    /// This is independent of the one-shot [`Self::closed`] future: either can be
1094    /// awaited first, and `ended` can be awaited again after completion. Neither
1095    /// method reads frames; both observe the same pending request's settlement.
1096    pub async fn ended(&mut self) -> SubscriptionEnd {
1097        loop {
1098            if let Some(end) = self.ended.borrow().clone() {
1099                return end;
1100            }
1101            if self.ended.changed().await.is_err() {
1102                return SubscriptionEnd::ConnectionLost;
1103            }
1104        }
1105    }
1106
1107    /// Cancel the held-open request.
1108    ///
1109    /// This sends a best-effort header-only Cancel frame for the subscription's
1110    /// `(channel, corr)` and settles [`Subscription::closed`] promptly with `Ok(())`.
1111    /// The provider may still send a terminal frame later; it is ignored because the
1112    /// local subscription is already closed.
1113    pub fn unsubscribe(&self) -> Result<(), CallError> {
1114        self.cancel.unsubscribe()
1115    }
1116}
1117
1118impl Drop for Subscription {
1119    fn drop(&mut self) {
1120        let _ = self.cancel.unsubscribe();
1121    }
1122}
1123
1124/// A held `supervisor.spawn_subscribe` request: the daemon's spawn events, in cursor
1125/// order, until the stream ends. Dropping it cancels the request.
1126pub struct SpawnSubscription {
1127    inner: Subscription,
1128    finished: bool,
1129}
1130
1131impl SpawnSubscription {
1132    /// The next event. `Ok(None)` is a clean end (the daemon ended the stream, or it was
1133    /// unsubscribed); every later call returns it too.
1134    ///
1135    /// Every event the daemon queued before a terminal error is yielded first, so the
1136    /// last event received is the cursor to resume from. A refused cursor or a dropped
1137    /// subscriber comes back as the matching [`SpawnStreamError`] variant; anything else
1138    /// that ends the stream (connection loss, local backpressure, an event that does not
1139    /// decode) is [`SpawnStreamError::Call`] or [`SpawnStreamError::Decode`].
1140    pub async fn next(&mut self) -> Result<Option<SpawnEvent>, SpawnStreamError> {
1141        if self.finished {
1142            return Ok(None);
1143        }
1144        if let Some(body) = self.inner.events().recv().await {
1145            return serde_json::from_slice::<SpawnEvent>(&body)
1146                .map(Some)
1147                .map_err(|err| {
1148                    self.finished = true;
1149                    let _ = self.inner.unsubscribe();
1150                    SpawnStreamError::Decode(err.to_string())
1151                });
1152        }
1153        // Marked finished only once the terminal has been read: a caller that drops this
1154        // future mid-await (a `select!` arm) still gets the terminal on its next call.
1155        let terminal = self.inner.closed().await;
1156        self.finished = true;
1157        match terminal {
1158            Ok(()) => Ok(None),
1159            Err(err) => Err(SpawnStreamError::from_call_error(err)),
1160        }
1161    }
1162
1163    /// Cancel the held request; the daemon releases the subscriber.
1164    pub fn unsubscribe(&self) -> Result<(), CallError> {
1165        self.inner.unsubscribe()
1166    }
1167}
1168
1169/// Why a spawn stream ended with an error, by the daemon's code where it sent one.
1170#[derive(Debug)]
1171pub enum SpawnStreamError {
1172    /// `spawn_cursor_incarnation_mismatch`: the cursor names another daemon incarnation,
1173    /// so every event since it is unknowable from this daemon.
1174    CursorIncarnationMismatch {
1175        current_daemon_incarnation: String,
1176        body: Box<ErrorBody>,
1177    },
1178    /// `spawn_cursor_too_old`: events after the cursor have left the daemon's ring.
1179    CursorTooOld {
1180        oldest_retained_cursor: SpawnCursor,
1181        body: Box<ErrorBody>,
1182    },
1183    /// `spawn_subscriber_lagged`: the daemon dropped this subscriber for falling behind,
1184    /// after delivering every event it had queued for it.
1185    SubscriberLagged {
1186        first_undelivered_cursor: SpawnCursor,
1187        body: Box<ErrorBody>,
1188    },
1189    /// Any other end: another daemon error (one of the codes above with a detail that
1190    /// does not parse included, so its code is still readable), connection loss, or
1191    /// local backpressure.
1192    Call(CallError),
1193    /// An event body that is not a `SpawnEvent`.
1194    Decode(String),
1195}
1196
1197impl SpawnStreamError {
1198    fn from_call_error(err: CallError) -> Self {
1199        let CallError::Module(body) = err else {
1200            return Self::Call(err);
1201        };
1202        let detail = |key: &str| body.detail.as_ref().and_then(|detail| detail.get(key));
1203        let cursor = |key: &str| {
1204            detail(key).and_then(|value| serde_json::from_value::<SpawnCursor>(value.clone()).ok())
1205        };
1206        match body.code.as_str() {
1207            SPAWN_CURSOR_INCARNATION_MISMATCH => {
1208                match detail("current_daemon_incarnation").and_then(|value| value.as_str()) {
1209                    Some(current) => Self::CursorIncarnationMismatch {
1210                        current_daemon_incarnation: current.to_string(),
1211                        body: Box::new(body),
1212                    },
1213                    None => Self::Call(CallError::Module(body)),
1214                }
1215            }
1216            SPAWN_CURSOR_TOO_OLD => match cursor("oldest_retained_cursor") {
1217                Some(oldest_retained_cursor) => Self::CursorTooOld {
1218                    oldest_retained_cursor,
1219                    body: Box::new(body),
1220                },
1221                None => Self::Call(CallError::Module(body)),
1222            },
1223            SPAWN_SUBSCRIBER_LAGGED => match cursor("first_undelivered_cursor") {
1224                Some(first_undelivered_cursor) => Self::SubscriberLagged {
1225                    first_undelivered_cursor,
1226                    body: Box::new(body),
1227                },
1228                None => Self::Call(CallError::Module(body)),
1229            },
1230            _ => Self::Call(CallError::Module(body)),
1231        }
1232    }
1233
1234    /// The daemon's error code, when the stream ended with one.
1235    pub fn code(&self) -> Option<&str> {
1236        match self {
1237            Self::CursorIncarnationMismatch { .. } => Some(SPAWN_CURSOR_INCARNATION_MISMATCH),
1238            Self::CursorTooOld { .. } => Some(SPAWN_CURSOR_TOO_OLD),
1239            Self::SubscriberLagged { .. } => Some(SPAWN_SUBSCRIBER_LAGGED),
1240            Self::Call(err) => err.code(),
1241            Self::Decode(_) => None,
1242        }
1243    }
1244}
1245
1246impl fmt::Display for SpawnStreamError {
1247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248        match self {
1249            Self::CursorIncarnationMismatch {
1250                current_daemon_incarnation,
1251                ..
1252            } => write!(
1253                f,
1254                "{SPAWN_CURSOR_INCARNATION_MISMATCH}: the daemon is incarnation \
1255                 {current_daemon_incarnation}"
1256            ),
1257            Self::CursorTooOld {
1258                oldest_retained_cursor,
1259                ..
1260            } => write!(
1261                f,
1262                "{SPAWN_CURSOR_TOO_OLD}: the oldest retained event is seq {}",
1263                oldest_retained_cursor.seq
1264            ),
1265            Self::SubscriberLagged {
1266                first_undelivered_cursor,
1267                ..
1268            } => write!(
1269                f,
1270                "{SPAWN_SUBSCRIBER_LAGGED}: the first undelivered event is seq {}",
1271                first_undelivered_cursor.seq
1272            ),
1273            Self::Call(err) => write!(f, "spawn stream ended: {err}"),
1274            Self::Decode(message) => write!(f, "spawn event did not decode: {message}"),
1275        }
1276    }
1277}
1278
1279impl Error for SpawnStreamError {}
1280
1281/// Future returned by [`Subscription::closed`].
1282pub struct SubscriptionClosed {
1283    rx: oneshot::Receiver<Result<(), CallError>>,
1284}
1285
1286impl Unpin for SubscriptionClosed {}
1287
1288impl Future for SubscriptionClosed {
1289    type Output = Result<(), CallError>;
1290
1291    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1292        let this = self.get_mut();
1293        match Pin::new(&mut this.rx).poll(cx) {
1294            Poll::Ready(Ok(result)) => Poll::Ready(result),
1295            Poll::Ready(Err(_)) => Poll::Ready(Err(CallError::outcome_unknown(
1296                "subscription closed result channel dropped",
1297                OutcomeUnknownCause::CompletionFailed,
1298            ))),
1299            Poll::Pending => Poll::Pending,
1300        }
1301    }
1302}
1303
1304struct SubscriptionCancel {
1305    shared: Arc<Shared>,
1306    position: Arc<SubscriptionPosition>,
1307    priority: Priority,
1308    cancelled: AtomicBool,
1309}
1310
1311impl SubscriptionCancel {
1312    fn new(shared: Arc<Shared>, position: Arc<SubscriptionPosition>, priority: Priority) -> Self {
1313        Self {
1314            shared,
1315            position,
1316            priority,
1317            cancelled: AtomicBool::new(false),
1318        }
1319    }
1320
1321    fn unsubscribe(&self) -> Result<(), CallError> {
1322        let key = *self
1323            .position
1324            .key
1325            .lock()
1326            .unwrap_or_else(|err| err.into_inner());
1327        let handle = RouteHandle::new(key.channel, key.epoch, key.generation);
1328        self.shared.validate_current_handle(handle)?;
1329        if self.cancelled.swap(true, Ordering::AcqRel) {
1330            return Ok(());
1331        }
1332        self.shared
1333            .unsubscribe_subscription(&self.position, self.priority)
1334    }
1335}
1336
1337impl SubcConsumer {
1338    /// Connect through an explicit connection-file path. The initial connection
1339    /// generation uses epoch 1; each reconnect advances it.
1340    /// In a supervised process, the module's primary registration connection
1341    /// mints a fresh self claim for
1342    /// every connection, including reconnects. Mint/presentation failure is an
1343    /// error, never a direct connection: dropping the binding would change the
1344    /// caller's authority. Unsupervised processes retain the legacy behavior.
1345    pub async fn connect(
1346        connection_file: &Path,
1347        opts: ConsumerOptions,
1348    ) -> Result<Self, ConsumerError> {
1349        Self::connect_with_transport(connection_file, opts, ConsumerTransport::Tcp, true).await
1350    }
1351
1352    /// Connect only to the connection file's same-user Unix socket or Windows pipe.
1353    ///
1354    /// Each connection attempt, including reconnects, reads the current local
1355    /// endpoint and key from the same owner-checked file. A missing
1356    /// `local_endpoint` returns [`ConsumerError::NoEndpoint`]; a local connect
1357    /// failure retains its endpoint and I/O error. Neither case falls back to TCP.
1358    pub async fn connect_local(
1359        connection_file: &Path,
1360        opts: ConsumerOptions,
1361    ) -> Result<Self, ConsumerError> {
1362        Self::connect_with_transport(connection_file, opts, ConsumerTransport::Local, true).await
1363    }
1364
1365    async fn connect_with_transport(
1366        connection_file: &Path,
1367        opts: ConsumerOptions,
1368        transport: ConsumerTransport,
1369        identity_from_environment: bool,
1370    ) -> Result<Self, ConsumerError> {
1371        let opened =
1372            open_connection(connection_file, opts.handshake_timeout, transport, None).await?;
1373        let mut shared = Shared::with_transport(connection_file.to_path_buf(), opts, transport);
1374        shared.identity_from_environment = identity_from_environment;
1375        let shared = Arc::new(shared);
1376        shared.install_initial(opened)?;
1377        Ok(Self { shared })
1378    }
1379
1380    /// Discover the daemon's connection file, authenticate, and start the I/O loop.
1381    pub async fn connect_default(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1382        let discovered = connection_file::discover(None)
1383            .map_err(|source| ConsumerError::Discovery { source })?;
1384        let opened =
1385            open_connection_with_info(&discovered.path, &discovered.info, opts.handshake_timeout)
1386                .await?;
1387        let shared = Arc::new(Shared::new(discovered.path, opts));
1388        shared.install_initial(opened)?;
1389        Ok(Self { shared })
1390    }
1391
1392    /// Discover the daemon's connection file and connect only to its local endpoint.
1393    ///
1394    /// Uses [`Self::connect_local`], including its per-attempt file reads and
1395    /// refusal to fall back to TCP.
1396    pub async fn connect_default_local(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1397        let discovered = connection_file::discover(None)
1398            .map_err(|source| ConsumerError::Discovery { source })?;
1399        Self::connect_local(&discovered.path, opts).await
1400    }
1401
1402    /// Connect the desktop operator app to the installed daemon without reading
1403    /// environment variables for discovery or consumer identity.
1404    ///
1405    /// Tries [`crate::operator_app_candidates`] in order on every attempt,
1406    /// selecting the first existing owner-checked file. Uses the
1407    /// same per-attempt file reads and local-only transport as
1408    /// [`Self::connect_local`], never falling back to TCP. Requests omit implicit
1409    /// consumer identity, including after reconnect; explicit identities in
1410    /// [`CallOptions`] and [`CloseRouteOptions`] are still honoured.
1411    pub async fn connect_operator_app(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1412        Self::connect_operator_app_resolving(
1413            opts,
1414            ConsumerTransport::Local,
1415            crate::operator_app_candidates,
1416        )
1417        .await
1418    }
1419
1420    /// Open the desktop operator app's plain connection over TCP.
1421    ///
1422    /// Selects and owner-checks the installed daemon's connection file with the
1423    /// same [`crate::operator_app_candidates`] policy as
1424    /// [`Self::connect_operator_app`], then connects to the file's first TCP
1425    /// endpoint instead of its Unix socket or Windows named pipe.
1426    ///
1427    /// The daemon recognises a connection as the operator app only when it
1428    /// arrives over its Unix socket or named pipe, so this connection never
1429    /// carries the `operator_app` stamp and can't skip the daemon's
1430    /// confirmation. Its privileged requests follow the daemon's configured
1431    /// policy like any other client's. The caller decides which actions to send
1432    /// here, for example those made through assistive technology. This API
1433    /// doesn't classify input.
1434    ///
1435    /// When the daemon supports `connection.describe`,
1436    /// [`Self::describe_connection`] reports this connection with
1437    /// `local() == false`. There, `local` means the Unix socket or named pipe,
1438    /// not loopback.
1439    ///
1440    /// Like [`Self::connect_operator_app`], it reads no environment variable for
1441    /// discovery or consumer identity, including after reconnect, and never
1442    /// falls back to the local endpoint.
1443    pub async fn connect_operator_app_plain(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1444        Self::connect_operator_app_resolving(
1445            opts,
1446            ConsumerTransport::Tcp,
1447            crate::operator_app_candidates,
1448        )
1449        .await
1450    }
1451
1452    async fn connect_operator_app_resolving(
1453        opts: ConsumerOptions,
1454        transport: ConsumerTransport,
1455        resolve: impl FnOnce() -> Result<Vec<PathBuf>, crate::OperatorAppPathError>,
1456    ) -> Result<Self, ConsumerError> {
1457        let candidates = resolve().map_err(|source| ConsumerError::ConnectionFile {
1458            path: PathBuf::new(),
1459            source: ConnectionFileError::Io {
1460                op: "resolve installed daemon connection-file path",
1461                path: PathBuf::new(),
1462                source: io::Error::other(source),
1463            },
1464        })?;
1465        let path = candidates[0].clone();
1466        let opened =
1467            open_connection(&path, opts.handshake_timeout, transport, Some(&candidates)).await?;
1468        let mut shared = Shared::with_transport(path, opts, transport);
1469        shared.operator_app_candidates = Some(candidates);
1470        shared.identity_from_environment = false;
1471        let shared = Arc::new(shared);
1472        shared.install_initial(opened)?;
1473        Ok(Self { shared })
1474    }
1475
1476    /// Open or reuse an unscoped managed route and return a handle tied to its
1477    /// current connection (stale after a reconnect).
1478    /// A scope in `opts` is an argument error; use [`Self::open_route_scoped`].
1479    pub async fn open_route(
1480        &self,
1481        target: RouteTarget,
1482        identity: BindIdentity,
1483        opts: CallOptions,
1484    ) -> Result<RouteHandle, CallError> {
1485        opts.reject_scope()?;
1486        let deadline = Instant::now() + opts.timeout;
1487        let consumer_identity = self.shared.route_open_consumer_identity(&opts)?;
1488        let consumer_capabilities = route_open_consumer_capabilities(&opts);
1489        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
1490        let key = RouteKey::new(
1491            &target,
1492            &identity,
1493            consumer_identity.as_ref(),
1494            consumer_capabilities.as_deref(),
1495        )
1496        .with_role_versions(role_versions.as_ref());
1497        let params = RouteOpenParams {
1498            target: &target,
1499            identity: &identity,
1500            consumer_identity: &consumer_identity,
1501            consumer_capabilities: &consumer_capabilities,
1502            role_versions: &role_versions,
1503            reverse_requests: &opts.reverse_requests,
1504            scope: None,
1505        };
1506        self.shared
1507            .ensure_route(&key, &params, &opts, deadline)
1508            .await
1509            .map(|route| route.handle)
1510    }
1511
1512    /// Open or reuse a managed route admitted under `scope`, and return a handle
1513    /// tied to its current connection (stale after a reconnect).
1514    ///
1515    /// This is how a carrier opens its onward route for a session. The daemon
1516    /// admits the open only when the opener (the consumer identity in `opts`,
1517    /// or the supervised module's own identity from the environment) is the
1518    /// scope's owner or one of its listed carriers, and it stamps the
1519    /// provider's bind with the scope. `scope.scope_epoch` must be set: the
1520    /// daemon refuses an open without it (`scope_epoch_required`).
1521    ///
1522    /// The route is cached under the whole selector (owner, ref and epoch) as
1523    /// well as the target and identities, so a route opened under one scope or
1524    /// epoch is never returned to a caller asking for another, and a scoped
1525    /// route is never returned by [`Self::open_route`] (nor an unscoped one
1526    /// here). Once the route closes, the next call with the same selector opens
1527    /// a fresh route under that selector. Close it early with
1528    /// [`Self::close_handle`].
1529    ///
1530    /// Refusals: `scope_not_synced` (the owner has not synced since the daemon
1531    /// started) and `scope_changed` (the scope changed while the bind was in
1532    /// flight) are retried within the call's deadline, like a module reload.
1533    /// `scope_ended`, `scope_not_live`, `scope_epoch_required` and
1534    /// `scope_not_carrier` end the call at once as [`CallError::NotSent`], with
1535    /// the daemon's code in [`CallError::route_open_refusal`].
1536    ///
1537    /// When the daemon later closes the route because its scope ended or the
1538    /// opener's authority under it was revoked, [`Self::control_pushes`]
1539    /// delivers `route.closed` with a `scope_*` reason. Its
1540    /// [`RouteCloseReason::disposition`] is
1541    /// [`RouteCloseDisposition::MustNotReopen`]: the session the route served is
1542    /// over, so callers should stop work for that session. The SDK does not
1543    /// cache a tombstone: a later explicit open or managed call with the same
1544    /// selector attempts a fresh open. The daemon refuses it as `scope_ended`
1545    /// if the ref is live at another epoch, or `scope_not_live` if the ref is gone.
1546    /// A selector in `opts.scope` must equal `scope`, or the call fails locally
1547    /// as an argument error before opening a route.
1548    pub async fn open_route_scoped(
1549        &self,
1550        target: RouteTarget,
1551        identity: BindIdentity,
1552        scope: ScopeSelector,
1553        opts: CallOptions,
1554    ) -> Result<RouteHandle, CallError> {
1555        if opts
1556            .scope
1557            .as_ref()
1558            .is_some_and(|selected| selected != &scope)
1559        {
1560            return Err(CallError::not_sent(
1561                "CallOptions.scope differs from open_route_scoped's explicit scope",
1562            ));
1563        }
1564        let deadline = Instant::now() + opts.timeout;
1565        let consumer_identity = self.shared.route_open_consumer_identity(&opts)?;
1566        let consumer_capabilities = route_open_consumer_capabilities(&opts);
1567        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
1568        let key = RouteKey::new(
1569            &target,
1570            &identity,
1571            consumer_identity.as_ref(),
1572            consumer_capabilities.as_deref(),
1573        )
1574        .with_role_versions(role_versions.as_ref())
1575        .with_scope(Some(&scope));
1576        let params = RouteOpenParams {
1577            target: &target,
1578            identity: &identity,
1579            consumer_identity: &consumer_identity,
1580            consumer_capabilities: &consumer_capabilities,
1581            role_versions: &role_versions,
1582            reverse_requests: &opts.reverse_requests,
1583            scope: Some(&scope),
1584        };
1585        self.shared
1586            .ensure_route(&key, &params, &opts, deadline)
1587            .await
1588            .map(|route| route.handle)
1589    }
1590
1591    /// Open one admitted route without entering the managed route cache.
1592    ///
1593    /// Admitted routes are never cached or reopened after a connection drop. If
1594    /// this call fails or the route later closes, the caller must perform admission
1595    /// again and call this method with fresh facts.
1596    ///
1597    /// The route declares no reverse-request capabilities, so the provider cannot
1598    /// send it requests. Use [`Self::open_route_with_admission_facts_and_options`]
1599    /// when the provider asks the consumer questions on the route (elicitation).
1600    pub async fn open_route_with_admission_facts(
1601        &self,
1602        target: RouteTarget,
1603        identity: BindIdentity,
1604        facts: serde_json::Value,
1605    ) -> Result<RouteHandle, CallError> {
1606        let deadline = Instant::now() + self.shared.opts.call_timeout;
1607        self.open_admitted_route(
1608            target,
1609            identity,
1610            facts,
1611            &CallOptions::default(),
1612            None,
1613            deadline,
1614        )
1615        .await
1616    }
1617
1618    /// Open one admitted route, with the reverse-request handlers, capability
1619    /// declarations and timeout in `opts`.
1620    ///
1621    /// The route declares the method families of handlers registered on
1622    /// `opts.reverse_requests`, together with any provider-contract declarations
1623    /// in the extra declarations reported by `opts.consumer_capabilities()`. For example, `tool-result/v1` declares the
1624    /// tool-provider content result format. These are unverified declarations,
1625    /// not privilege grants. Requests the provider sends back (elicitation,
1626    /// sampling) reach the registered handlers, exactly as on a managed route.
1627    /// Handlers must be registered before this call: the registry is sealed
1628    /// when the route opens, because the declared method families are what the
1629    /// provider was told.
1630    ///
1631    /// Like [`Self::open_route_with_admission_facts`], the route is never cached
1632    /// or reopened; after a failure or a close the caller performs admission again.
1633    /// A non-`None` `opts.scope` is rejected as an argument error.
1634    pub async fn open_route_with_admission_facts_and_options(
1635        &self,
1636        target: RouteTarget,
1637        identity: BindIdentity,
1638        facts: serde_json::Value,
1639        opts: CallOptions,
1640    ) -> Result<RouteHandle, CallError> {
1641        opts.reject_scope()?;
1642        let deadline = Instant::now() + opts.timeout;
1643        let reverse_requests = opts.reverse_requests.clone();
1644        self.open_admitted_route(
1645            target,
1646            identity,
1647            facts,
1648            &opts,
1649            Some(reverse_requests),
1650            deadline,
1651        )
1652        .await
1653    }
1654
1655    /// One admitted route.open. With `reverse_requests`, the route is opened the
1656    /// way the managed path opens one: the capabilities are declared, the socket
1657    /// reader installs the handle before the open resolves (so a request the
1658    /// provider sends right after binding is not lost), and the handle carries
1659    /// the registry. Without it, the route has no reverse-request handling.
1660    async fn open_admitted_route(
1661        &self,
1662        target: RouteTarget,
1663        identity: BindIdentity,
1664        facts: serde_json::Value,
1665        opts: &CallOptions,
1666        reverse_requests: Option<ReverseRequestRegistry>,
1667        deadline: Instant,
1668    ) -> Result<RouteHandle, CallError> {
1669        let consumer_capabilities = route_open_consumer_capabilities(opts);
1670        let target_label = route_target_label(&target);
1671        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
1672            busy_refusals: Some(true),
1673            target,
1674            identity,
1675            consumer_identity: self.shared.route_open_consumer_identity(opts)?,
1676            consumer_capabilities,
1677            role_versions: route_open_role_versions(opts.role_versions.as_ref()),
1678            admission_facts: Some(facts),
1679            scope: None,
1680        })
1681        .map_err(|err| CallError::not_sent(format!("failed to encode route.open: {err}")))?;
1682
1683        let terminal = self
1684            .shared
1685            .paced_route_open(body, deadline, reverse_requests.clone())
1686            .await?;
1687        let (generation, body) = match terminal {
1688            TerminalFrame::Response {
1689                generation, body, ..
1690            } => (generation, body),
1691            // The daemon refused the open. Keep its code and detail, as the
1692            // plain route.open does, so a caller can tell "retry shortly"
1693            // (module_warming) from "this configuration will never work"
1694            // (admission_facts_not_permitted).
1695            TerminalFrame::Error { body, .. } => {
1696                return Err(CallError::route_open_refused(target_label, body));
1697            }
1698            _ => {
1699                return Err(CallError::not_sent_with_cause(
1700                    "route.open returned a non-response frame",
1701                    NotSentCause::RouteOpenAbandoned,
1702                ));
1703            }
1704        };
1705        let ClientControlResponse::RouteOpen {
1706            route_channel,
1707            route_epoch,
1708            request_window,
1709            watch_window,
1710            ..
1711        } = decode_route_open_response(&body)
1712            .map_err(|err| {
1713                CallError::not_sent_with_cause(
1714                    format!("failed to decode route.open response: {err}"),
1715                    NotSentCause::RouteOpenAbandoned,
1716                )
1717            })?
1718            .0
1719        else {
1720            return Err(CallError::not_sent_with_cause(
1721                "route.open returned an unexpected control response",
1722                NotSentCause::RouteOpenAbandoned,
1723            ));
1724        };
1725        // Adopt the handle the socket reader installed for this response, which
1726        // carries the registry passed to control_call; build one only if the
1727        // reader did not (the connection moved on before the response landed).
1728        let handle = self
1729            .shared
1730            .ingress_handle(generation, route_channel, route_epoch)
1731            .unwrap_or_else(|| match reverse_requests {
1732                Some(reverse_requests) => RouteHandle::new_consumer(
1733                    route_channel,
1734                    route_epoch,
1735                    generation,
1736                    reverse_requests,
1737                ),
1738                None => RouteHandle::new(route_channel, route_epoch, generation),
1739            });
1740        let route = RouteState::windows(handle, request_window, watch_window);
1741        self.shared.install_one_shot_route(route.clone())?;
1742        Ok(route.handle)
1743    }
1744
1745    /// Describe this connection without prompting or granting any privilege.
1746    /// An older daemon's `unknown_control_op` refusal returns `None`: that daemon
1747    /// doesn't support this query, which says nothing about recognition.
1748    pub async fn describe_connection(&self) -> Result<Option<ConnectionFacts>, CallError> {
1749        let body =
1750            serde_json::to_vec(&subc_control::ConnectionDescribeRequest::new()).map_err(|err| {
1751                CallError::not_sent(format!("failed to encode connection.describe: {err}"))
1752            })?;
1753        let deadline = Instant::now() + self.shared.opts.call_timeout;
1754        match self
1755            .shared
1756            .control_call(body, deadline, false, None)
1757            .await?
1758        {
1759            TerminalFrame::Response { body, .. } => {
1760                let reply: subc_control::ConnectionDescribeReply = serde_json::from_slice(&body)
1761                    .map_err(|err| {
1762                        CallError::invalid_response(format!(
1763                            "failed to decode connection.describe: {err}"
1764                        ))
1765                    })?;
1766                Ok(Some(ConnectionFacts {
1767                    local: reply.local,
1768                    operator_app: reply.operator_app,
1769                }))
1770            }
1771            // The client-control dispatcher uses this exact code for unknown ops.
1772            TerminalFrame::Error { body, .. } if body.code == "unknown_control_op" => Ok(None),
1773            TerminalFrame::Error { body, .. } => Err(CallError::Module(body)),
1774            TerminalFrame::StreamEnd => Err(CallError::invalid_response(
1775                "connection.describe returned StreamEnd",
1776            )),
1777        }
1778    }
1779
1780    /// Ask the daemon to open a known installed app. Starting it grants nothing.
1781    /// Future success statuses and refusal codes are preserved for the caller.
1782    pub async fn app_open(&self, app: &str) -> Result<subc_control::AppOpenReply, AppOpenError> {
1783        let body = serde_json::to_vec(&subc_control::AppOpenRequest::new(app))
1784            .map_err(|err| CallError::not_sent(format!("failed to encode app.open: {err}")))?;
1785        let deadline = Instant::now() + self.shared.opts.call_timeout;
1786        match self
1787            .shared
1788            .control_call(body, deadline, false, None)
1789            .await?
1790        {
1791            TerminalFrame::Response { body, .. } => serde_json::from_slice(&body).map_err(|err| {
1792                CallError::invalid_response(format!("failed to decode app.open: {err}")).into()
1793            }),
1794            TerminalFrame::Error { body, .. } => Err(AppOpenError::Refused {
1795                code: body.code,
1796                message: body.message,
1797            }),
1798            TerminalFrame::StreamEnd => {
1799                Err(CallError::invalid_response("app.open returned StreamEnd").into())
1800            }
1801        }
1802    }
1803
1804    /// Fetch the daemon's module catalog over channel 0.
1805    /// Transport retries use the consumer's reconnect backoff and call deadline.
1806    pub async fn catalog_list(&self) -> Result<CatalogList, CallError> {
1807        let deadline = Instant::now() + self.shared.opts.call_timeout;
1808        let body = serde_json::to_vec(&serde_json::json!({
1809            "op": subc_control::ops::CATALOG_LIST,
1810        }))
1811        .map_err(|err| CallError::not_sent(format!("failed to encode catalog.list: {err}")))?;
1812
1813        let mut attempt = 0usize;
1814        loop {
1815            attempt = attempt.saturating_add(1);
1816            match self
1817                .shared
1818                .control_call(body.clone(), deadline, false, None)
1819                .await
1820            {
1821                Ok(TerminalFrame::Response { body, .. }) => {
1822                    let response =
1823                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
1824                            CallError::invalid_response(format!(
1825                                "failed to decode catalog.list response: {err}"
1826                            ))
1827                        })?;
1828                    let ClientControlResponse::CatalogList {
1829                        generation,
1830                        modules,
1831                        subc_ops,
1832                    } = response
1833                    else {
1834                        return Err(CallError::invalid_response(
1835                            "catalog.list returned an unexpected control response",
1836                        ));
1837                    };
1838                    return Ok(CatalogList {
1839                        generation,
1840                        modules,
1841                        subc_ops,
1842                    });
1843                }
1844                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
1845                Ok(TerminalFrame::StreamEnd) => {
1846                    return Err(CallError::invalid_response(
1847                        "catalog.list returned StreamEnd",
1848                    ));
1849                }
1850                Err(err)
1851                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
1852                {
1853                    // Connection-file and discovery failures can complete without
1854                    // yielding. Pace the outer retry as well as reconnect itself,
1855                    // so repeated immediate failures cannot monopolize the executor.
1856                    let delay = self.shared.jittered(
1857                        self.shared
1858                            .opts
1859                            .reconnect_backoff
1860                            .delay_after_attempt(attempt),
1861                    );
1862                    self.shared.sleep_until_retry(deadline, delay).await?;
1863                    continue;
1864                }
1865                Err(err) => return Err(err),
1866            }
1867        }
1868    }
1869
1870    /// Fetch the supervisor's configured module list over channel 0.
1871    /// Transport retries use the consumer's reconnect backoff and call deadline.
1872    pub async fn supervisor_list(&self) -> Result<SupervisorListResponse, CallError> {
1873        let deadline = Instant::now() + self.shared.opts.call_timeout;
1874        let body = serde_json::to_vec(&ClientControlRequest::SupervisorList {}).map_err(|err| {
1875            CallError::not_sent(format!("failed to encode supervisor.list: {err}"))
1876        })?;
1877
1878        let mut attempt = 0usize;
1879        loop {
1880            attempt = attempt.saturating_add(1);
1881            match self
1882                .shared
1883                .control_call(body.clone(), deadline, false, None)
1884                .await
1885            {
1886                Ok(TerminalFrame::Response { body, .. }) => {
1887                    let response =
1888                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
1889                            CallError::invalid_response(format!(
1890                                "failed to decode supervisor.list response: {err}"
1891                            ))
1892                        })?;
1893                    let ClientControlResponse::SupervisorList {
1894                        generation,
1895                        modules,
1896                        daemon,
1897                        agent_commands,
1898                    } = response
1899                    else {
1900                        return Err(CallError::invalid_response(
1901                            "supervisor.list returned an unexpected control response",
1902                        ));
1903                    };
1904                    return Ok(SupervisorListResponse {
1905                        generation,
1906                        modules,
1907                        daemon,
1908                        agent_commands,
1909                    });
1910                }
1911                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
1912                Ok(TerminalFrame::StreamEnd) => {
1913                    return Err(CallError::invalid_response(
1914                        "supervisor.list returned StreamEnd",
1915                    ));
1916                }
1917                Err(err)
1918                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
1919                {
1920                    // Pace immediate discovery failures so retries cannot monopolize the executor.
1921                    let delay = self.shared.jittered(
1922                        self.shared
1923                            .opts
1924                            .reconnect_backoff
1925                            .delay_after_attempt(attempt),
1926                    );
1927                    self.shared.sleep_until_retry(deadline, delay).await?;
1928                    continue;
1929                }
1930                Err(err) => return Err(err),
1931            }
1932        }
1933    }
1934
1935    /// Fetch the supervisor's atomic spawn snapshot (`supervisor.spawn_snapshot`)
1936    /// over channel 0: the live processes with their spawn generations, and the
1937    /// cursor at which they were observed.
1938    ///
1939    /// A daemon refusal comes back as [`CallError::Module`], so its code is readable
1940    /// through [`CallError::code`]. Transport failures are retried until the
1941    /// consumer's call deadline with its reconnect backoff, as for
1942    /// [`SubcConsumer::catalog_list`].
1943    pub async fn spawn_snapshot(&self) -> Result<SpawnSnapshot, CallError> {
1944        let deadline = Instant::now() + self.shared.opts.call_timeout;
1945        let body = serde_json::to_vec(&ClientControlRequest::SupervisorSpawnSnapshot {}).map_err(
1946            |err| CallError::not_sent(format!("failed to encode supervisor.spawn_snapshot: {err}")),
1947        )?;
1948
1949        let mut attempt = 0usize;
1950        loop {
1951            attempt = attempt.saturating_add(1);
1952            match self
1953                .shared
1954                .control_call(body.clone(), deadline, false, None)
1955                .await
1956            {
1957                Ok(TerminalFrame::Response { body, .. }) => {
1958                    let response =
1959                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
1960                            CallError::invalid_response(format!(
1961                                "failed to decode supervisor.spawn_snapshot response: {err}"
1962                            ))
1963                        })?;
1964                    let ClientControlResponse::SupervisorSpawnSnapshot { snapshot } = response
1965                    else {
1966                        return Err(CallError::invalid_response(
1967                            "supervisor.spawn_snapshot returned an unexpected control response",
1968                        ));
1969                    };
1970                    return Ok(snapshot);
1971                }
1972                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
1973                Ok(TerminalFrame::StreamEnd) => {
1974                    return Err(CallError::invalid_response(
1975                        "supervisor.spawn_snapshot returned StreamEnd",
1976                    ));
1977                }
1978                Err(err)
1979                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
1980                {
1981                    let delay = self.shared.jittered(
1982                        self.shared
1983                            .opts
1984                            .reconnect_backoff
1985                            .delay_after_attempt(attempt),
1986                    );
1987                    self.shared.sleep_until_retry(deadline, delay).await?;
1988                    continue;
1989                }
1990                Err(err) => return Err(err),
1991            }
1992        }
1993    }
1994
1995    /// Query the newest-first activity ledger. The reply preserves entries, the
1996    /// continuation cursor and the head to subscribe from without a query/follow gap.
1997    /// Except for operator-app connections, identity is filled from the supervised
1998    /// launch environment, as for route.open; without one the daemon treats the
1999    /// caller as Direct. Refusals retain their code
2000    /// through [`CallError::code`]. Transport retries are paced to the call deadline.
2001    pub async fn query_activity(
2002        &self,
2003        request: ActivityQueryRequest,
2004    ) -> Result<ActivityQueryResponse, CallError> {
2005        let deadline = Instant::now() + self.shared.opts.call_timeout;
2006        let body = self.shared.activity_read_body(request)?;
2007        let mut attempt = 0usize;
2008        loop {
2009            attempt = attempt.saturating_add(1);
2010            match self
2011                .shared
2012                .control_call(body.clone(), deadline, false, None)
2013                .await
2014            {
2015                Ok(TerminalFrame::Response { body, .. }) => {
2016                    return serde_json::from_slice(&body).map_err(|err| {
2017                        CallError::invalid_response(format!(
2018                            "invalid activity.query response: {err}"
2019                        ))
2020                    });
2021                }
2022                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
2023                Ok(TerminalFrame::StreamEnd) => {
2024                    return Err(CallError::invalid_response(
2025                        "activity.query returned StreamEnd",
2026                    ));
2027                }
2028                Err(err)
2029                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
2030                {
2031                    let delay = self.shared.jittered(
2032                        self.shared
2033                            .opts
2034                            .reconnect_backoff
2035                            .delay_after_attempt(attempt),
2036                    );
2037                    self.shared.sleep_until_retry(deadline, delay).await?;
2038                }
2039                Err(err) => return Err(err),
2040            }
2041        }
2042    }
2043
2044    /// Follow durable activity entries after `since`, or from now if absent.
2045    /// The launch identity is filled as for [`Self::query_activity`]. Refused cursors
2046    /// and subscriber lag are terminal stream errors whose daemon code is readable
2047    /// through [`crate::ActivityStreamError::code`]. On reconnect the stream ends;
2048    /// recover with a query and subscribe from its head.
2049    pub async fn subscribe_activity(
2050        &self,
2051        since: Option<ActivityCursor>,
2052    ) -> Result<ActivitySubscription, CallError> {
2053        let deadline = Instant::now() + self.shared.opts.call_timeout;
2054        let body = self
2055            .shared
2056            .activity_read_body(ActivitySubscribeRequest { since })?;
2057        loop {
2058            self.shared.ensure_connected_for_call(deadline).await?;
2059            let permit = Arc::new(Semaphore::new(1))
2060                .acquire_owned()
2061                .await
2062                .map_err(|_| CallError::not_sent("activity subscription permit closed"))?;
2063            match self
2064                .shared
2065                .send_subscription(SubscriptionSend {
2066                    expected_handle: None,
2067                    channel: 0,
2068                    epoch: 0,
2069                    body: body.clone(),
2070                    priority: Priority::Interactive,
2071                    admission_class: AdmissionClass::Normal,
2072                    event_buffer: ACTIVITY_EVENT_BUFFER,
2073                    deadline,
2074                    permit: RoutePermit::legacy(permit),
2075                })
2076                .await
2077            {
2078                Ok(inner) => {
2079                    return Ok(ActivitySubscription {
2080                        inner,
2081                        finished: false,
2082                    })
2083                }
2084                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
2085                Err(err) => return Err(err),
2086            }
2087        }
2088    }
2089
2090    /// Follow the supervisor's spawn event stream (`supervisor.spawn_subscribe`) over
2091    /// channel 0, from just after `since` (a cursor copied from a snapshot or an event),
2092    /// or from now when `since` is `None`.
2093    ///
2094    /// The request is held open: the returned [`SpawnSubscription`] yields each event
2095    /// until the stream ends. A cursor the daemon refuses, and the daemon dropping a
2096    /// subscriber that fell behind, arrive as the stream's terminal error (see
2097    /// [`SpawnStreamError`]). A reconnect ends the stream; the caller resubscribes from
2098    /// the last cursor it received. Sending is retried until the consumer's call
2099    /// deadline, as for [`SubcConsumer::spawn_snapshot`].
2100    pub async fn spawn_subscribe(
2101        &self,
2102        since: Option<SpawnCursor>,
2103    ) -> Result<SpawnSubscription, CallError> {
2104        let deadline = Instant::now() + self.shared.opts.call_timeout;
2105        let body = serde_json::to_vec(&ClientControlRequest::SupervisorSpawnSubscribe { since })
2106            .map_err(|err| {
2107                CallError::not_sent(format!(
2108                    "failed to encode supervisor.spawn_subscribe: {err}"
2109                ))
2110            })?;
2111        loop {
2112            self.shared.ensure_connected_for_call(deadline).await?;
2113            // Channel 0 has no route flow-control window; the subscription holds a
2114            // permit of its own so it is shaped like a route subscription.
2115            let permit = Arc::new(Semaphore::new(1))
2116                .acquire_owned()
2117                .await
2118                .map_err(|_| CallError::not_sent("spawn subscription permit closed"))?;
2119            match self
2120                .shared
2121                .send_subscription(SubscriptionSend {
2122                    expected_handle: None,
2123                    channel: 0,
2124                    epoch: 0,
2125                    body: body.clone(),
2126                    priority: Priority::Interactive,
2127                    admission_class: AdmissionClass::Normal,
2128                    event_buffer: SPAWN_EVENT_BUFFER,
2129                    deadline,
2130                    permit: RoutePermit::legacy(permit),
2131                })
2132                .await
2133            {
2134                Ok(inner) => {
2135                    return Ok(SpawnSubscription {
2136                        inner,
2137                        finished: false,
2138                    })
2139                }
2140                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
2141                Err(err) => return Err(err),
2142            }
2143        }
2144    }
2145
2146    /// Resolve the sole catalog claimant for a capability.
2147    ///
2148    /// Resolution is deliberately based only on the static capabilities mirror in
2149    /// `catalog.list`; module ids and role names are not fallback claims. Calling
2150    /// this method expresses singular intent, so a plural catalog result is an
2151    /// explicit ambiguity rather than an arbitrary choice.
2152    pub async fn resolve_provider(&self, capability: &str) -> Result<String, CallError> {
2153        let claimants = self.resolve_providers(capability).await?;
2154        match claimants.as_slice() {
2155            [] => Err(CallError::CapabilityUnprovided {
2156                capability: capability.to_string(),
2157            }),
2158            [claimant] => Ok(claimant.clone()),
2159            _ => Err(CallError::CapabilityAmbiguous {
2160                capability: capability.to_string(),
2161                claimants,
2162            }),
2163        }
2164    }
2165
2166    /// Resolve every catalog claimant for a capability in module-id order.
2167    ///
2168    /// The identifier is validated before any channel-0 request is made, so a
2169    /// typo cannot become a network-dependent "unprovided" result.
2170    pub async fn resolve_providers(&self, capability: &str) -> Result<Vec<String>, CallError> {
2171        validate_capability_for_resolution(capability)?;
2172        let catalog = self.catalog_list().await?;
2173        Ok(capability_claimants(&catalog, capability))
2174    }
2175
2176    /// Send one request using an already-opened route handle.
2177    /// `opts.scope` must be `None`: the handle's scope was selected at route open.
2178    pub async fn request(
2179        &self,
2180        handle: &RouteHandle,
2181        body: Vec<u8>,
2182        opts: CallOptions,
2183    ) -> Result<Vec<u8>, CallError> {
2184        self.request_inner(handle, body, opts, None).await
2185    }
2186
2187    /// Like [`Self::request`], with explicit cancellation of the in-flight request.
2188    ///
2189    /// The returned future is lazy and has the same result and deadline as `request`.
2190    /// Calling [`CancelHandle::cancel`] sends at most one header-only Cancel on the
2191    /// request's route; it does not stop waiting for the provider's Response or Error.
2192    /// Dropping the handle sends nothing. Dropping the future only removes its
2193    /// pending registration, **without sending Cancel**.
2194    ///
2195    /// ```no_run
2196    /// # async fn turn(consumer: &subc_client_rs::SubcConsumer,
2197    /// # route: &subc_client_rs::RouteHandle,
2198    /// # turn_stopped: impl std::future::Future<Output = ()>) -> Result<(), subc_client_rs::CallError> {
2199    /// let (cancel, reply) = consumer.request_cancellable(
2200    ///     route, b"work".to_vec(), subc_client_rs::CallOptions::default());
2201    /// tokio::pin!(reply);
2202    /// tokio::select! {
2203    ///     result = &mut reply => { let _body = result?; }
2204    ///     () = turn_stopped => {
2205    ///         cancel.cancel().await;
2206    ///         let _body = reply.await?; // Keep any final Response body.
2207    ///     }
2208    /// }
2209    /// # Ok(())
2210    /// # }
2211    /// ```
2212    pub fn request_cancellable(
2213        &self,
2214        handle: &RouteHandle,
2215        body: Vec<u8>,
2216        opts: CallOptions,
2217    ) -> (
2218        CancelHandle,
2219        impl Future<Output = Result<Vec<u8>, CallError>> + Send + '_,
2220    ) {
2221        let consumer = self;
2222        let handle = *handle;
2223        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
2224        let future = async move {
2225            let guard = registration;
2226            consumer
2227                .request_inner(&handle, body, opts, Some(Arc::clone(&guard.state)))
2228                .await
2229        };
2230        (cancel, future)
2231    }
2232
2233    async fn request_inner(
2234        &self,
2235        handle: &RouteHandle,
2236        body: Vec<u8>,
2237        opts: CallOptions,
2238        cancel: Option<Arc<UnaryCancel>>,
2239    ) -> Result<Vec<u8>, CallError> {
2240        opts.reject_scope()?;
2241        let deadline = Instant::now() + opts.timeout;
2242        let route = self.shared.route_state(*handle)?;
2243        let permit = route.acquire(false, deadline, cancel.as_ref()).await?;
2244        let mut busy_delay = Duration::from_millis(25);
2245        loop {
2246            let result = self
2247                .shared
2248                .send_request_with_slot(
2249                    RequestSend {
2250                        binary: false,
2251                        expected_handle: Some(*handle),
2252                        channel: handle.channel,
2253                        epoch: handle.epoch,
2254                        body: body.clone(),
2255                        priority: opts.priority,
2256                        admission_class: opts.admission_class,
2257                        deadline,
2258                        retain_late_route_open: false,
2259                        route_open_reverse_requests: None,
2260                    },
2261                    cancel.clone(),
2262                    Some(Arc::clone(&permit)),
2263                )
2264                .await;
2265            match result? {
2266                TerminalFrame::Response { body, .. } => return Ok(body),
2267                TerminalFrame::StreamEnd => return Ok(Vec::new()),
2268                TerminalFrame::Error { body, flags }
2269                    if error_codes::is_route_busy_retryable(flags, &body.code, route.opted_in) =>
2270                {
2271                    if !self
2272                        .shared
2273                        .busy_backoff(deadline, busy_delay, cancel.as_ref())
2274                        .await
2275                    {
2276                        return Err(busy_error(&body));
2277                    }
2278                    busy_delay = (busy_delay * 2).min(Duration::from_secs(1));
2279                    self.shared.validate_current_handle(*handle)?;
2280                }
2281                TerminalFrame::Error { body, flags } => {
2282                    return Err(CallError::from_established_route_error(flags, body));
2283                }
2284            }
2285        }
2286    }
2287
2288    /// Start a held-open request using an already-opened route handle.
2289    /// `opts.scope` must be `None`: the handle's scope was selected at route open.
2290    pub async fn subscribe_route(
2291        &self,
2292        handle: &RouteHandle,
2293        body: Vec<u8>,
2294        opts: SubscribeOptions,
2295    ) -> Result<Subscription, CallError> {
2296        if opts.scope.is_some() {
2297            return Err(CallError::not_sent(
2298                "SubscribeOptions.scope is not supported on subscribe_route; select the scope when opening the route",
2299            ));
2300        }
2301        let deadline = Instant::now() + opts.route_open_timeout;
2302        let route = self.shared.route_state(*handle)?;
2303        let permit = route.acquire(true, deadline, None).await?;
2304        self.shared
2305            .send_subscription(SubscriptionSend {
2306                expected_handle: Some(*handle),
2307                channel: handle.channel,
2308                epoch: handle.epoch,
2309                body,
2310                priority: opts.priority,
2311                admission_class: opts.admission_class,
2312                event_buffer: opts.event_buffer,
2313                deadline,
2314                permit,
2315            })
2316            .await
2317    }
2318
2319    /// Poll status or liveness for exactly this route handle.
2320    /// A daemon refusal is returned as [`CallError::Module`] with its original body.
2321    pub async fn poll_route(
2322        &self,
2323        handle: &RouteHandle,
2324        kind: PollKind,
2325        timeout: Duration,
2326    ) -> Result<RoutePollResult, CallError> {
2327        let deadline = Instant::now() + timeout;
2328        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
2329            route_channel: handle.channel,
2330            route_epoch: handle.epoch,
2331            kind,
2332        })
2333        .map_err(|err| CallError::not_sent(format!("failed to encode route.poll: {err}")))?;
2334        let terminal = self
2335            .shared
2336            .send_request(RequestSend {
2337                binary: false,
2338                expected_handle: Some(*handle),
2339                channel: 0,
2340                epoch: 0,
2341                body,
2342                priority: Priority::Interactive,
2343                admission_class: AdmissionClass::Normal,
2344                deadline,
2345                retain_late_route_open: false,
2346                route_open_reverse_requests: None,
2347            })
2348            .await?;
2349        let body = match terminal {
2350            TerminalFrame::Response { body, .. } => body,
2351            TerminalFrame::Error { body, .. } => return Err(CallError::Module(body)),
2352            TerminalFrame::StreamEnd => {
2353                return Err(CallError::invalid_response(
2354                    "route.poll returned a non-response frame",
2355                ));
2356            }
2357        };
2358        let ClientControlResponse::RoutePoll {
2359            route_channel,
2360            route_epoch,
2361            status,
2362            live,
2363        } = serde_json::from_slice(&body).map_err(|err| {
2364            CallError::invalid_response(format!("failed to decode route.poll: {err}"))
2365        })?
2366        else {
2367            return Err(CallError::invalid_response(
2368                "route.poll returned an unexpected control response",
2369            ));
2370        };
2371        if route_channel != handle.channel || route_epoch != handle.epoch {
2372            return Err(CallError::invalid_response(
2373                "route.poll response echoed a different route handle",
2374            ));
2375        }
2376        self.shared.validate_current_handle(*handle)?;
2377        Ok(RoutePollResult {
2378            handle: *handle,
2379            status,
2380            live,
2381        })
2382    }
2383
2384    /// Locally observed count of unknown or stale route frames dropped by layer-2 validation.
2385    pub fn dropped_route_frames(&self) -> u64 {
2386        self.shared.lock_inner().dropped_route_frames
2387    }
2388
2389    /// Register a receiver for provider-originated Push frames on exactly one live route.
2390    ///
2391    /// Registering another receiver for the same route replaces and closes the prior receiver.
2392    /// The receiver closes when its route closes or the connection drops. A FULL buffer drops
2393    /// the overflowing push and counts it on `pushes_dropped_receiver_full` while the
2394    /// subscription survives (issue #40; push is a lossy latency optimization and polling
2395    /// remains the correctness backstop). The reader never waits for an application that is
2396    /// not draining pushes.
2397    pub fn push_events(
2398        &self,
2399        handle: &RouteHandle,
2400    ) -> Result<mpsc::Receiver<PushEvent>, CallError> {
2401        self.shared.register_push_events(*handle)
2402    }
2403
2404    /// Number of Push frames dropped because their live route has no active receiver.
2405    ///
2406    /// Push is a one-way latency optimization, not a durable feed: the client does not
2407    /// acknowledge it, and callers retain polling as their correctness backstop. Counting
2408    /// intentional default-path drops makes an application that has not opted in observable.
2409    pub fn pushes_dropped_no_receiver(&self) -> u64 {
2410        self.shared
2411            .pushes_dropped_no_receiver
2412            .load(Ordering::Relaxed)
2413    }
2414
2415    /// Pushes dropped because the registered receiver's bounded buffer was full.
2416    /// The subscription SURVIVES a burst (the receiver stays registered); this
2417    /// counter is the trace the burst leaves. Distinct from
2418    /// `pushes_dropped_no_receiver` because the remedies differ: full means
2419    /// drain faster or register with more capacity, no-receiver means nobody
2420    /// subscribed.
2421    pub fn pushes_dropped_receiver_full(&self) -> u64 {
2422        self.shared
2423            .pushes_dropped_receiver_full
2424            .load(Ordering::Relaxed)
2425    }
2426
2427    /// Register the consumer-level receiver for daemon-originated channel-0
2428    /// control pushes (`route.closing`, `route.closed`, and any op added
2429    /// later). Advisory by contract: GOODBYE remains the load-bearing
2430    /// route-death signal and nothing in the client's own lifecycle consumes
2431    /// these. Unrecognized ops are DELIVERED (the must-ignore choice belongs
2432    /// to the consumer); unparseable bodies are dropped and counted. The
2433    /// receiver survives reconnects. Registering again replaces the prior
2434    /// receiver; a full or closed receiver drops the push and counts it
2435    /// rather than blocking the reader.
2436    pub fn control_pushes(&self, capacity: usize) -> mpsc::Receiver<ControlPush> {
2437        let (sender, receiver) = mpsc::channel(capacity.max(1));
2438        self.shared.lock_inner().control_push_receiver = Some(sender);
2439        receiver
2440    }
2441
2442    /// Always-present count of dropped channel-0 control pushes (no receiver
2443    /// registered, receiver full or closed, or unparseable body). Emitted as a
2444    /// counter rather than silence so an application that has not opted in is
2445    /// observable, mirroring `pushes_dropped_no_receiver`.
2446    pub fn control_pushes_dropped(&self) -> u64 {
2447        self.shared.control_pushes_dropped.load(Ordering::Relaxed)
2448    }
2449
2450    /// Managed unary call. Route-open failures happen before the body is sent and are
2451    /// classified as `NotSent`; module handler Error frames are the only `Module` errors.
2452    ///
2453    /// A daemon refusal that proves the module never received the request
2454    /// (`unknown_channel`, `stale_route_epoch`, or `module_reloading` while the
2455    /// module drains for a restart, reload or disable) evicts the cached route,
2456    /// reopens it and resends the request once, within the call deadline and
2457    /// only if the call has not been cancelled. Reopening during a drain waits
2458    /// out the daemon's `route.open` refusals until the replacement process
2459    /// registers, so the resend reaches the new process. A second such refusal
2460    /// is returned as `CallError::Module`.
2461    pub async fn call(
2462        &self,
2463        target: RouteTarget,
2464        identity: BindIdentity,
2465        body: Vec<u8>,
2466        opts: CallOptions,
2467    ) -> Result<Vec<u8>, CallError> {
2468        self.call_with_reply(target, identity, body, opts)
2469            .await
2470            .map(CallReply::into_body)
2471    }
2472
2473    /// Like [`Self::call`], retaining the terminal Response's binary flag as well
2474    /// as its unchanged body bytes. A StreamEnd yields an empty, non-binary reply.
2475    pub async fn call_with_reply(
2476        &self,
2477        target: RouteTarget,
2478        identity: BindIdentity,
2479        body: Vec<u8>,
2480        opts: CallOptions,
2481    ) -> Result<CallReply, CallError> {
2482        self.call_inner(target, identity, (body, false), opts, None)
2483            .await
2484    }
2485
2486    /// Managed unary call with explicit cancellation, like [`Self::request_cancellable`].
2487    ///
2488    /// Uses the same route opening, options, errors and deadline as [`Self::call`].
2489    /// Once cancellation is requested, a dead-route or `module_reloading` refusal is
2490    /// returned rather than retrying work the caller has asked to stop. Cancellation during route opening
2491    /// is remembered and sent after the Request is queued. Dropping either value
2492    /// sends no Cancel; dropping the future removes its pending registration.
2493    pub fn call_cancellable(
2494        &self,
2495        target: RouteTarget,
2496        identity: BindIdentity,
2497        body: Vec<u8>,
2498        opts: CallOptions,
2499    ) -> (
2500        CancelHandle,
2501        impl Future<Output = Result<Vec<u8>, CallError>> + Send + '_,
2502    ) {
2503        let (cancel, reply) = self.call_cancellable_with_reply(target, identity, body, opts);
2504        (cancel, async move { reply.await.map(CallReply::into_body) })
2505    }
2506
2507    /// Like [`Self::call_cancellable`], retaining the terminal Response's binary
2508    /// flag and unchanged bytes in [`CallReply`]. Cancellation, retries, deadlines
2509    /// and drop behavior are identical. A StreamEnd yields an empty, non-binary reply.
2510    pub fn call_cancellable_with_reply(
2511        &self,
2512        target: RouteTarget,
2513        identity: BindIdentity,
2514        body: Vec<u8>,
2515        opts: CallOptions,
2516    ) -> (
2517        CancelHandle,
2518        impl Future<Output = Result<CallReply, CallError>> + Send + '_,
2519    ) {
2520        let consumer = self;
2521        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
2522        let future = async move {
2523            let guard = registration;
2524            consumer
2525                .call_inner(
2526                    target,
2527                    identity,
2528                    (body, false),
2529                    opts,
2530                    Some(Arc::clone(&guard.state)),
2531                )
2532                .await
2533        };
2534        (cancel, future)
2535    }
2536
2537    /// Sends a framed JSON object head and opaque payload with `FLAG_BINARY`.
2538    /// Only use this for management operations that declare `operation_payload`.
2539    /// The caller enforces the operation's limit; the codec only bounds the head.
2540    pub async fn call_framed_with_reply(
2541        &self,
2542        target: RouteTarget,
2543        identity: BindIdentity,
2544        head: serde_json::Value,
2545        payload: Vec<u8>,
2546        opts: CallOptions,
2547    ) -> Result<CallReply, CallError> {
2548        let body = subc_protocol::framed_body::encode(&head, &payload)
2549            .map_err(|error| CallError::not_sent(format!("invalid framed request: {error}")))?;
2550        self.call_inner(target, identity, (body, true), opts, None)
2551            .await
2552    }
2553
2554    /// Cancellable companion to [`Self::call_framed_with_reply`], with the same
2555    /// lazy send, cancellation, retry and deadline behavior as other managed calls.
2556    pub fn call_framed_cancellable_with_reply(
2557        &self,
2558        target: RouteTarget,
2559        identity: BindIdentity,
2560        head: serde_json::Value,
2561        payload: Vec<u8>,
2562        opts: CallOptions,
2563    ) -> (
2564        CancelHandle,
2565        impl Future<Output = Result<CallReply, CallError>> + Send + '_,
2566    ) {
2567        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
2568        (cancel, async move {
2569            let guard = registration;
2570            let body = subc_protocol::framed_body::encode(&head, &payload)
2571                .map_err(|error| CallError::not_sent(format!("invalid framed request: {error}")))?;
2572            self.call_inner(
2573                target,
2574                identity,
2575                (body, true),
2576                opts,
2577                Some(Arc::clone(&guard.state)),
2578            )
2579            .await
2580        })
2581    }
2582
2583    async fn call_inner(
2584        &self,
2585        target: RouteTarget,
2586        identity: BindIdentity,
2587        body: (Vec<u8>, bool),
2588        opts: CallOptions,
2589        cancel: Option<Arc<UnaryCancel>>,
2590    ) -> Result<CallReply, CallError> {
2591        let mut history = CallAttemptHistory {
2592            never_forwarded: true,
2593            sent: false,
2594        };
2595        self.call_attempts(target, identity, body, opts, cancel, &mut history)
2596            .await
2597            .map_err(|err| {
2598                let err = if history.sent && matches!(err, CallError::StaleRouteHandle(_)) {
2599                    CallError::not_sent(err.to_string())
2600                } else {
2601                    err
2602                };
2603                err.with_never_forwarded(history.never_forwarded)
2604            })
2605    }
2606
2607    async fn call_attempts(
2608        &self,
2609        target: RouteTarget,
2610        identity: BindIdentity,
2611        body: (Vec<u8>, bool),
2612        opts: CallOptions,
2613        cancel: Option<Arc<UnaryCancel>>,
2614        history: &mut CallAttemptHistory,
2615    ) -> Result<CallReply, CallError> {
2616        let (body, binary) = body;
2617        let call_deadline = Instant::now() + opts.timeout;
2618        // Preserve the single resend policy even for older daemons whose
2619        // unmarked refusals cannot prove that the module never saw the request.
2620        let mut resent_after_unsent_refusal = false;
2621        let consumer_identity = self.shared.route_open_consumer_identity(&opts)?;
2622        let consumer_capabilities = route_open_consumer_capabilities(&opts);
2623        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
2624        let route_key = RouteKey::new(
2625            &target,
2626            &identity,
2627            consumer_identity.as_ref(),
2628            consumer_capabilities.as_deref(),
2629        )
2630        .with_role_versions(role_versions.as_ref())
2631        .with_scope(opts.scope.as_ref());
2632
2633        let route_open = RouteOpenParams {
2634            target: &target,
2635            identity: &identity,
2636            consumer_identity: &consumer_identity,
2637            consumer_capabilities: &consumer_capabilities,
2638            role_versions: &role_versions,
2639            reverse_requests: &opts.reverse_requests,
2640            scope: opts.scope.as_ref(),
2641        };
2642
2643        let mut busy_permit: Option<Arc<RoutePermit>> = None;
2644        let mut busy_delay = Duration::from_millis(25);
2645        loop {
2646            let route = self
2647                .shared
2648                .ensure_route(&route_key, &route_open, &opts, call_deadline)
2649                .await
2650                .map_err(request_not_sent_after_route_open_failure)?;
2651            if busy_permit
2652                .as_ref()
2653                .is_some_and(|permit| !permit.belongs_to(&route))
2654            {
2655                busy_permit.take();
2656            }
2657            let permit = match busy_permit.take() {
2658                Some(permit) => permit,
2659                None => route
2660                    .acquire(false, call_deadline, cancel.as_ref())
2661                    .await
2662                    .map_err(|err| {
2663                        if matches!(err, CallError::StaleRouteHandle(_)) {
2664                            self.shared.route_not_sent_error(route.handle)
2665                        } else {
2666                            err
2667                        }
2668                    })?,
2669            };
2670
2671            if !self.shared.route_is_current(&route_key, &route) {
2672                drop(permit);
2673                self.shared
2674                    .sleep_until_retry(call_deadline, opts.route_retry.base)
2675                    .await?;
2676                continue;
2677            }
2678
2679            // Snapshot trust for the route's generation before awaiting its reply;
2680            // a reconnect must not lend a newer daemon's guarantees to an old frame.
2681            let daemon_origin_trusted = {
2682                let inner = self.shared.lock_inner();
2683                inner.generation == route.handle.connection_token() && inner.daemon_origin_trusted
2684            };
2685            let response = self
2686                .shared
2687                .send_request_with_slot(
2688                    RequestSend {
2689                        expected_handle: Some(route.handle),
2690                        channel: route.handle.channel,
2691                        epoch: route.handle.epoch,
2692                        body: body.clone(),
2693                        binary,
2694                        priority: opts.priority,
2695                        admission_class: opts.admission_class,
2696                        deadline: call_deadline,
2697                        retain_late_route_open: false,
2698                        route_open_reverse_requests: None,
2699                    },
2700                    cancel.clone(),
2701                    Some(Arc::clone(&permit)),
2702                )
2703                .await;
2704
2705            history.sent |= response.is_ok();
2706            let proven_undelivered = match &response {
2707                Ok(TerminalFrame::Error { body, flags }) => {
2708                    is_refusal_on_route(daemon_origin_trusted, *flags, &body.code, route.opted_in)
2709                }
2710                Err(err) => {
2711                    err.never_forwarded() == Some(true)
2712                        || matches!(err, CallError::StaleRouteHandle(_))
2713                }
2714                _ => false,
2715            };
2716            history.never_forwarded &= proven_undelivered;
2717
2718            match response {
2719                Ok(TerminalFrame::Response { body, flags, .. }) => {
2720                    return Ok(CallReply {
2721                        body,
2722                        binary: flags.is_binary(),
2723                    });
2724                }
2725                Ok(TerminalFrame::StreamEnd) => {
2726                    return Ok(CallReply {
2727                        body: Vec::new(),
2728                        binary: false,
2729                    });
2730                }
2731                Ok(TerminalFrame::Error { body, flags })
2732                    if error_codes::is_route_busy_retryable(flags, &body.code, route.opted_in) =>
2733                {
2734                    if !self
2735                        .shared
2736                        .busy_backoff(call_deadline, busy_delay, cancel.as_ref())
2737                        .await
2738                    {
2739                        return Err(busy_error(&body));
2740                    }
2741                    busy_delay = (busy_delay * 2).min(Duration::from_secs(1));
2742                    busy_permit = Some(permit);
2743                    continue;
2744                }
2745                // Route-dead and drain refusals share one eviction/resend budget.
2746                // Only a trusted daemon-origin flag proves non-delivery; the retry
2747                // policy itself stays compatible with older daemons.
2748                Ok(TerminalFrame::Error { body, flags })
2749                    if (error_codes::is_established_route_dead(flags, &body.code)
2750                        || is_data_plane_drain_refusal(&body.code))
2751                        && !resent_after_unsent_refusal
2752                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested())
2753                        && Instant::now() < call_deadline =>
2754                {
2755                    resent_after_unsent_refusal = true;
2756                    self.shared.invalidate_route(&route_key, Some(route.handle));
2757                    continue;
2758                }
2759                Ok(TerminalFrame::Error { body, flags })
2760                    if is_daemon_refusal_before_forward(
2761                        daemon_origin_trusted,
2762                        flags,
2763                        &body.code,
2764                    ) =>
2765                {
2766                    return Err(CallError::not_sent_with_cause(
2767                        format!(
2768                            "daemon refused before forwarding: {} ({})",
2769                            body.code, body.message
2770                        ),
2771                        NotSentCause::DaemonRefusedBeforeForward { code: body.code },
2772                    ));
2773                }
2774                Ok(TerminalFrame::Error { body, flags }) => {
2775                    return Err(CallError::from_established_route_error(flags, body));
2776                }
2777                Err(err)
2778                    if err.is_not_sent()
2779                        && Instant::now() < call_deadline
2780                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested()) =>
2781                {
2782                    self.shared.invalidate_route(&route_key, Some(route.handle));
2783                    self.shared.ensure_connected_for_call(call_deadline).await?;
2784                    continue;
2785                }
2786                Err(err)
2787                    if err.outcome_cause() == Some(OutcomeUnknownCause::Deadline)
2788                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested()) =>
2789                {
2790                    self.shared.invalidate_route_with_deadline(
2791                        &route_key,
2792                        Some(route.handle),
2793                        true,
2794                    );
2795                    return Err(err);
2796                }
2797                Err(err) => return Err(err),
2798            }
2799        }
2800    }
2801
2802    /// Open a held-open subscription on a managed route.
2803    ///
2804    /// This opens or reuses the same `(target, identity, consumer_identity, consumer_capabilities, role_versions, scope)` route as
2805    /// [`SubcConsumer::call`], sends one Request that the provider keeps open, and
2806    /// returns a [`Subscription`] whose event receiver yields each matching
2807    /// `StreamData` payload. The request holds one route flow-control permit until
2808    /// `StreamEnd`, an Error frame, route teardown or connection loss. On negotiated
2809    /// routes, local backpressure and unsubscribe keep credit until a wire terminal.
2810    /// Reconnects reject the
2811    /// subscription; callers that need durable replay should resubscribe with their
2812    /// own cursor after observing the failure.
2813    pub async fn subscribe(
2814        &self,
2815        target: RouteTarget,
2816        identity: BindIdentity,
2817        body: Vec<u8>,
2818        opts: SubscribeOptions,
2819    ) -> Result<Subscription, CallError> {
2820        let open_deadline = Instant::now() + opts.route_open_timeout;
2821        let route_opts = CallOptions {
2822            scope: opts.scope.clone(),
2823            timeout: opts.route_open_timeout,
2824            priority: opts.priority,
2825            admission_class: opts.admission_class,
2826            route_retry: opts.route_retry,
2827            route_retry_deadline: opts.route_retry_deadline,
2828            consumer_identity: opts.consumer_identity.clone(),
2829            reverse_requests: opts.reverse_requests.clone(),
2830            role_versions: opts.role_versions.clone(),
2831        };
2832        let consumer_identity = self.shared.route_open_consumer_identity(&route_opts)?;
2833        let consumer_capabilities = route_open_consumer_capabilities(&route_opts);
2834        let role_versions = route_open_role_versions(route_opts.role_versions.as_ref());
2835        let route_key = RouteKey::new(
2836            &target,
2837            &identity,
2838            consumer_identity.as_ref(),
2839            consumer_capabilities.as_deref(),
2840        )
2841        .with_role_versions(role_versions.as_ref())
2842        .with_scope(opts.scope.as_ref());
2843
2844        let route_open = RouteOpenParams {
2845            target: &target,
2846            identity: &identity,
2847            consumer_identity: &consumer_identity,
2848            consumer_capabilities: &consumer_capabilities,
2849            role_versions: &role_versions,
2850            reverse_requests: &opts.reverse_requests,
2851            scope: opts.scope.as_ref(),
2852        };
2853
2854        loop {
2855            let route = self
2856                .shared
2857                .ensure_route(&route_key, &route_open, &route_opts, open_deadline)
2858                .await
2859                .map_err(request_not_sent_after_route_open_failure)?;
2860            let permit = route
2861                .acquire(true, open_deadline, None)
2862                .await
2863                .map_err(|err| {
2864                    if matches!(err, CallError::StaleRouteHandle(_)) {
2865                        self.shared.route_not_sent_error(route.handle)
2866                    } else {
2867                        err
2868                    }
2869                })?;
2870
2871            if !self.shared.route_is_current(&route_key, &route) {
2872                drop(permit);
2873                self.shared
2874                    .sleep_until_retry(open_deadline, opts.route_retry.base)
2875                    .await?;
2876                continue;
2877            }
2878
2879            match self
2880                .shared
2881                .send_subscription(SubscriptionSend {
2882                    expected_handle: Some(route.handle),
2883                    channel: route.handle.channel,
2884                    epoch: route.handle.epoch,
2885                    body: body.clone(),
2886                    priority: opts.priority,
2887                    admission_class: opts.admission_class,
2888                    event_buffer: opts.event_buffer,
2889                    deadline: open_deadline,
2890                    permit,
2891                })
2892                .await
2893            {
2894                Ok(subscription) => return Ok(subscription),
2895                Err(err) if err.is_not_sent() && Instant::now() < open_deadline => {
2896                    self.shared.invalidate_route(&route_key, Some(route.handle));
2897                    self.shared.ensure_connected_for_call(open_deadline).await?;
2898                    continue;
2899                }
2900                Err(err) => return Err(err),
2901            }
2902        }
2903    }
2904
2905    /// Tear down ONE route, keyed by its route-open identity tuple — the parity of the TS
2906    /// client's `closeRoute`. For a long-lived consumer that opens unbounded distinct
2907    /// routes (one per session), this releases a route on session-end without dropping
2908    /// the whole consumer: it drops the cached route, settles in-flight requests on it
2909    /// at-most-once (OutcomeUnknown if already sent, NotSent otherwise), and queues a
2910    /// route GOODBYE so the daemon releases it and notifies the module. When closing
2911    /// a cached route returns, its GOODBYE is queued ahead of any frame sent later on
2912    /// this connection, so the caller may release its per-route budget. If the
2913    /// connection died instead, the daemon releases all its routes on disconnect.
2914    /// `opts.scope` selects only that scope's cache entry; `None` selects only
2915    /// the unscoped entry. Calls and subscriptions use the same route cache.
2916    ///
2917    /// Idempotent: a no-op if the route was never opened or is already closed (callers
2918    /// over-call on session-end). NOT a permanent tombstone — a later `call()` for the
2919    /// same key opens a fresh route. The close-beats-reopen guard ensures a close that
2920    /// races an in-flight route.open WINS (the opened channel is GOODBYE'd, not cached).
2921    ///
2922    /// # Cancel safety
2923    /// Once the cached route is removed, dropping this future abandons any drain
2924    /// wait but still settles pending requests and queues its GOODBYE in the
2925    /// background. The handle stays installed until GOODBYE is queued, unless the
2926    /// connection dies. Cancellation does not queue a second GOODBYE if the close
2927    /// already completed.
2928    pub async fn close_route(
2929        &self,
2930        target: RouteTarget,
2931        identity: BindIdentity,
2932        opts: CloseRouteOptions,
2933    ) {
2934        let Ok(consumer_identity) = self.shared.close_route_consumer_identity(&opts) else {
2935            return;
2936        };
2937        let consumer_capabilities = close_route_consumer_capabilities(&opts);
2938        let key = RouteKey::new(
2939            &target,
2940            &identity,
2941            consumer_identity.as_ref(),
2942            consumer_capabilities.as_deref(),
2943        )
2944        .with_role_versions(route_open_role_versions(opts.role_versions.as_ref()).as_ref())
2945        .with_scope(opts.scope.as_ref());
2946        self.shared.close_route(&key, &opts).await;
2947    }
2948
2949    /// Close exactly this route handle. A stale connection token fails locally and emits no frame.
2950    /// `opts.scope` must be `None`: the handle already selects exactly one route.
2951    ///
2952    /// # Cancel safety
2953    /// After the handle is validated and its route removed, dropping this future
2954    /// abandons any drain wait but still settles pending requests and queues its
2955    /// GOODBYE in the background. The handle is uninstalled after queueing, or when
2956    /// the connection dies; a completed close never queues a second GOODBYE on drop.
2957    pub async fn close_handle(
2958        &self,
2959        handle: &RouteHandle,
2960        opts: CloseRouteOptions,
2961    ) -> Result<(), CallError> {
2962        if opts.scope.is_some() {
2963            return Err(CallError::not_sent(
2964                "CloseRouteOptions.scope is not supported on close_handle; the handle already selects the route",
2965            ));
2966        }
2967        self.shared.close_handle(*handle, &opts).await
2968    }
2969
2970    /// Current transport epoch: 1 on initial connect, then +1 per successful reconnect.
2971    pub fn current_epoch(&self) -> u64 {
2972        self.shared.lock_inner().epoch
2973    }
2974
2975    pub(crate) fn pool_reusable(&self) -> bool {
2976        !self.shared.close_token.is_cancelled()
2977    }
2978
2979    /// Register a connection-state callback. Callbacks are best-effort observability hooks.
2980    pub fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
2981        self.shared
2982            .lock_inner()
2983            .callbacks
2984            .push(Arc::new(Mutex::new(Box::new(cb))));
2985    }
2986
2987    /// Close the consumer and settle every pending caller.
2988    pub async fn close(&self) {
2989        self.shared.close_sync("consumer closed");
2990        tokio::task::yield_now().await;
2991    }
2992}
2993
2994impl Drop for SubcConsumer {
2995    fn drop(&mut self) {
2996        self.shared.close_sync("consumer dropped");
2997    }
2998}
2999
3000/// Error returned by [`SubcConsumer`]'s TCP and local connection constructors.
3001#[derive(Debug)]
3002pub enum ConsumerError {
3003    Discovery {
3004        source: connection_file::DiscoveryError,
3005    },
3006    ConnectionFile {
3007        path: PathBuf,
3008        source: ConnectionFileError,
3009    },
3010    /// No endpoint for the requested transport. [`SubcConsumer::connect_local`]
3011    /// returns this when the connection file has no `local_endpoint`.
3012    NoEndpoint {
3013        path: PathBuf,
3014    },
3015    Connect {
3016        path: PathBuf,
3017        endpoint: String,
3018        source: io::Error,
3019    },
3020    Auth {
3021        path: PathBuf,
3022        endpoint: String,
3023        source: AuthError,
3024    },
3025    Closed,
3026}
3027
3028impl ConsumerError {
3029    pub(crate) fn claim(error: crate::ClaimError) -> Self {
3030        Self::Connect {
3031            path: PathBuf::new(),
3032            endpoint: "claim binding".into(),
3033            source: io::Error::other(error),
3034        }
3035    }
3036}
3037
3038impl fmt::Display for ConsumerError {
3039    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3040        match self {
3041            Self::Discovery { source } => source.fmt(f),
3042            Self::ConnectionFile { path, source } => write!(
3043                f,
3044                "failed to read subc connection file '{}': {source}",
3045                path.display()
3046            ),
3047            Self::NoEndpoint { path } => {
3048                write!(
3049                    f,
3050                    "subc connection file '{}' has no endpoint for the requested transport",
3051                    path.display()
3052                )
3053            }
3054            Self::Connect {
3055                path,
3056                endpoint,
3057                source,
3058            } => write!(
3059                f,
3060                "failed to connect to subc endpoint {endpoint} from '{}': {source}",
3061                path.display()
3062            ),
3063            Self::Auth {
3064                path,
3065                endpoint,
3066                source,
3067            } => write!(
3068                f,
3069                "failed to authenticate to subc endpoint {endpoint} from '{}': {source}",
3070                path.display()
3071            ),
3072            Self::Closed => write!(f, "consumer closed"),
3073        }
3074    }
3075}
3076
3077impl Error for ConsumerError {
3078    fn source(&self) -> Option<&(dyn Error + 'static)> {
3079        match self {
3080            Self::Discovery { source } => Some(source),
3081            Self::ConnectionFile { source, .. } => Some(source),
3082            Self::Connect { source, .. } => Some(source),
3083            Self::Auth { source, .. } => Some(source),
3084            Self::NoEndpoint { .. } | Self::Closed => None,
3085        }
3086    }
3087}
3088
3089/// Why a sent request has no observed terminal response.
3090#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3091#[non_exhaustive]
3092pub enum OutcomeUnknownCause {
3093    /// The reply deadline elapsed after the request was sent.
3094    Deadline,
3095    /// The connection's writer closed or failed after send.
3096    WriterClosed,
3097    /// The caller closed the consumer while a request was pending.
3098    ConsumerClosed,
3099    /// The daemon connection failed or dropped.
3100    ConnectionFailed,
3101    /// The route ended; [`CallError::close_reason`] gives its reason.
3102    RouteEnded,
3103    /// An internal completion channel dropped or an unexpected completion arrived.
3104    CompletionFailed,
3105}
3106
3107#[derive(Debug, Clone)]
3108struct OutcomeUnknownSource {
3109    message: String,
3110    cause: OutcomeUnknownCause,
3111    route_reason: Option<RouteEnd>,
3112}
3113
3114impl fmt::Display for OutcomeUnknownSource {
3115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3116        f.write_str(&self.message)
3117    }
3118}
3119impl Error for OutcomeUnknownSource {}
3120
3121/// Why an attempt was classified as [`CallError::NotSent`]. For resend safety
3122/// across all attempts, also check [`CallError::never_forwarded`].
3123#[derive(Debug, Clone, PartialEq, Eq)]
3124#[non_exhaustive]
3125pub enum NotSentCause {
3126    /// The daemon or module refused route.open before the data request.
3127    RouteOpenRefused { code: String },
3128    /// Route opening ended without a usable answer, including cancellation.
3129    RouteOpenAbandoned,
3130    /// Local validation, connection state or flow control prevented queueing.
3131    BeforeQueue,
3132    /// The deadline elapsed waiting for the writer's cancel-safe queue send.
3133    WriterCapacity,
3134    /// The writer did not accept the request for transmission.
3135    WriterRejected,
3136    /// A control response could not be decoded or had an unexpected shape.
3137    InvalidResponse,
3138    /// No longer produced: since 0.34.2 a dropped completion channel, which
3139    /// can't prove non-delivery, is reported as [`CallError::OutcomeUnknown`]
3140    /// with [`OutcomeUnknownCause::CompletionFailed`]. Kept so existing
3141    /// matches still compile.
3142    CompletionFailed,
3143    /// A daemon-marked data-plane refusal proved this attempt was not forwarded.
3144    DaemonRefusedBeforeForward { code: String },
3145}
3146
3147#[derive(Debug, Clone)]
3148struct NotSentSource {
3149    message: String,
3150    cause: NotSentCause,
3151    never_forwarded: bool,
3152    route_reason: Option<RouteEnd>,
3153    refusal: Option<Box<RouteOpenRefused>>,
3154}
3155
3156impl fmt::Display for NotSentSource {
3157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3158        f.write_str(&self.message)
3159    }
3160}
3161impl Error for NotSentSource {}
3162
3163/// Managed call or subscription failure.
3164#[derive(Debug)]
3165pub enum CallError {
3166    /// Local compatibility policy refusal: the version retained from the
3167    /// connection file for this connection is not an exact numeric
3168    /// `major.minor.patch` version at least 0.39.0. Unrecognized strings,
3169    /// including prereleases and build suffixes, are refused too. This
3170    /// route-open attempt was refused before being queued for writing.
3171    /// The handshake authenticates the daemon ID, not this version metadata.
3172    DaemonTooOld { daemon_ver: String },
3173    /// A pre-send failure, proven non-delivery, or unusable reply or internal completion.
3174    /// Check [`CallError::never_forwarded`] before treating the whole call as safe to resend.
3175    NotSent(Box<dyn Error + Send + Sync>),
3176    /// The request body was accepted by the writer path, but no terminal response was observed.
3177    OutcomeUnknown(Box<dyn Error + Send + Sync>),
3178    /// The target module handler returned an Error frame. Application-level rejections
3179    /// are returned as ordinary successful response bytes and do not produce this variant.
3180    Module(ErrorBody),
3181    /// An Error frame reported that the established route is no longer usable.
3182    RouteDead(Box<ErrorBody>),
3183    /// A subscription event receiver stopped keeping up with its bounded channel.
3184    ///
3185    /// The reader task must never await a slow consumer while it is dispatching frames
3186    /// for the whole connection, so a full event channel terminates only that subscription.
3187    SubscriptionBackpressure(Box<dyn Error + Send + Sync>),
3188    /// The handle belongs to an earlier connection and no frame was emitted.
3189    StaleRouteHandle(RouteHandle),
3190    /// No registered catalog entry claims the requested capability.
3191    CapabilityUnprovided { capability: String },
3192    /// More than one registered catalog entry claims a singularly requested capability.
3193    CapabilityAmbiguous {
3194        capability: String,
3195        claimants: Vec<String>,
3196    },
3197    /// The resolver rejected a malformed capability identifier before querying the daemon.
3198    InvalidCapabilityIdentifier { capability: String },
3199}
3200
3201impl CallError {
3202    /// Whether an Error frame reported that the established route is no longer usable.
3203    /// This classification does not establish whether an earlier attempt was delivered.
3204    pub fn is_route_dead(&self) -> bool {
3205        matches!(self, Self::RouteDead(_))
3206    }
3207
3208    /// A typed terminal scope bind-proof refusal, if the daemon returned one.
3209    pub fn scope_bind_proof_refusal(&self) -> Option<ScopeBindProofRefusal> {
3210        match self.route_open_refusal()?.code.as_str() {
3211            error_codes::SCOPE_BIND_PROOF_REQUIRED => Some(ScopeBindProofRefusal::Required),
3212            error_codes::SCOPE_BIND_PROOF_MISMATCH => Some(ScopeBindProofRefusal::Mismatch),
3213            _ => None,
3214        }
3215    }
3216
3217    /// Why the route ended. The error remains `NotSent` or `OutcomeUnknown`:
3218    /// this reason never makes a sent call safe to resend.
3219    pub fn close_reason(&self) -> Option<&RouteEndReason> {
3220        self.route_end().map(|end| &end.reason)
3221    }
3222
3223    fn route_end(&self) -> Option<&RouteEnd> {
3224        match self {
3225            Self::NotSent(source) => source
3226                .downcast_ref::<NotSentSource>()?
3227                .route_reason
3228                .as_ref(),
3229            Self::OutcomeUnknown(source) => source
3230                .downcast_ref::<OutcomeUnknownSource>()?
3231                .route_reason
3232                .as_ref(),
3233            _ => None,
3234        }
3235    }
3236
3237    /// The daemon's recovery verdict from `route.closed`, if it carried one.
3238    /// `Some(true)` means the daemon will leave the module down until an operator
3239    /// acts. `None` means unknown: older daemons, client-side ends and non-route
3240    /// errors have no verdict. This flag does not change resend safety or the
3241    /// close reason's reopen disposition.
3242    pub fn terminal(&self) -> Option<bool> {
3243        self.route_end()?.terminal
3244    }
3245
3246    /// Why the outcome is unknown, without parsing the error's message.
3247    /// Errors constructed outside this crate with an untyped source return `None`.
3248    pub fn outcome_cause(&self) -> Option<OutcomeUnknownCause> {
3249        match self {
3250            Self::OutcomeUnknown(source) => source
3251                .downcast_ref::<OutcomeUnknownSource>()
3252                .map(|source| source.cause),
3253            _ => None,
3254        }
3255    }
3256
3257    /// Why the final attempt was classified as `NotSent`, without parsing its message.
3258    /// Returns `None` for other variants and externally constructed untyped errors.
3259    pub fn not_sent_cause(&self) -> Option<NotSentCause> {
3260        match self {
3261            Self::NotSent(source) => source
3262                .downcast_ref::<NotSentSource>()
3263                .map(|source| source.cause.clone()),
3264            _ => None,
3265        }
3266    }
3267
3268    /// Whether no attempt of this call may have reached the module.
3269    ///
3270    /// `Some(false)` means this or an earlier attempt may have been forwarded.
3271    /// For data-plane errors, only daemon-marked refusals prove non-delivery;
3272    /// unmarked replies remain conservative on older daemons. Managed calls
3273    /// include every attempt. Returns `None` except for crate-built `NotSent` errors.
3274    pub fn never_forwarded(&self) -> Option<bool> {
3275        match self {
3276            Self::NotSent(source) => source
3277                .downcast_ref::<NotSentSource>()
3278                .map(|source| source.never_forwarded),
3279            _ => None,
3280        }
3281    }
3282
3283    /// Return the stable machine-readable code for typed errors.
3284    pub fn code(&self) -> Option<&str> {
3285        match self {
3286            Self::Module(body) => Some(&body.code),
3287            Self::RouteDead(body) => Some(&body.code),
3288            Self::DaemonTooOld { .. } => Some("daemon_too_old"),
3289            Self::CapabilityUnprovided { .. } => Some("capability_unprovided"),
3290            Self::CapabilityAmbiguous { .. } => Some("capability_ambiguous"),
3291            Self::InvalidCapabilityIdentifier { .. } => Some("invalid_capability_identifier"),
3292            Self::NotSent(source) => match &source.downcast_ref::<NotSentSource>()?.cause {
3293                NotSentCause::DaemonRefusedBeforeForward { code }
3294                    if code == error_codes::ROUTE_BUSY =>
3295                {
3296                    Some(code)
3297                }
3298                _ => None,
3299            },
3300            Self::OutcomeUnknown(_)
3301            | Self::SubscriptionBackpressure(_)
3302            | Self::StaleRouteHandle(_) => None,
3303        }
3304    }
3305
3306    fn not_sent(reason: impl Into<String>) -> Self {
3307        Self::not_sent_with_cause(reason, NotSentCause::BeforeQueue)
3308    }
3309
3310    fn not_sent_with_cause(reason: impl Into<String>, cause: NotSentCause) -> Self {
3311        Self::NotSent(Box::new(NotSentSource {
3312            message: reason.into(),
3313            cause,
3314            never_forwarded: true,
3315            route_reason: None,
3316            refusal: None,
3317        }))
3318    }
3319
3320    fn with_never_forwarded(mut self, never_forwarded: bool) -> Self {
3321        if let Self::NotSent(source) = &mut self {
3322            if let Some(source) = source.downcast_mut::<NotSentSource>() {
3323                source.never_forwarded &= never_forwarded;
3324            }
3325        }
3326        self
3327    }
3328
3329    fn invalid_response(reason: impl Into<String>) -> Self {
3330        Self::not_sent_with_cause(reason, NotSentCause::InvalidResponse).with_never_forwarded(false)
3331    }
3332
3333    fn outcome_unknown(reason: impl Into<String>, cause: OutcomeUnknownCause) -> Self {
3334        Self::outcome_unknown_source(OutcomeUnknownSource {
3335            message: reason.into(),
3336            cause,
3337            route_reason: None,
3338        })
3339    }
3340
3341    fn outcome_unknown_source(source: OutcomeUnknownSource) -> Self {
3342        Self::OutcomeUnknown(Box::new(source))
3343    }
3344
3345    fn is_not_sent(&self) -> bool {
3346        matches!(self, Self::NotSent(_))
3347    }
3348
3349    /// The daemon's refusal body when this failure is a route.open the daemon
3350    /// refused, with its `code`, `message` and machine-readable `detail`
3351    /// intact, for example `module_warming` with
3352    /// `detail.reason = "required_capability_unprovided"`.
3353    ///
3354    /// When retryable refusals ran out the route-retry deadline, this is the
3355    /// most informative refusal seen during the retries, so a caller can tell
3356    /// "the module was reloading" from "the connection failed". Refusals rank:
3357    /// `module_reloading` / `module_warming`, then `delegation_not_registered`,
3358    /// then admission pressure (too many binds in flight), then anything else;
3359    /// at equal rank the later one wins. The failure is still `NotSent`: a
3360    /// refused route.open never delivered the request.
3361    pub fn route_open_refusal(&self) -> Option<&ErrorBody> {
3362        match self {
3363            Self::NotSent(err) => err
3364                .downcast_ref::<NotSentSource>()
3365                .and_then(|source| source.refusal.as_ref())
3366                .map(|refused| &refused.body),
3367            _ => None,
3368        }
3369    }
3370
3371    fn subscription_backpressure(reason: impl Into<String>) -> Self {
3372        Self::SubscriptionBackpressure(Box::new(SimpleError(reason.into())))
3373    }
3374}
3375
3376impl fmt::Display for CallError {
3377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3378        match self {
3379            Self::DaemonTooOld { daemon_ver } => write!(
3380                f,
3381                "daemon_too_old: route.open requires daemon 0.39.0 or newer (connected version: {daemon_ver})"
3382            ),
3383            Self::NotSent(err) => write!(f, "request not sent: {err}"),
3384            Self::OutcomeUnknown(err) => write!(f, "request outcome unknown: {err}"),
3385            Self::Module(body) => write!(f, "module error {}: {}", body.code, body.message),
3386            Self::RouteDead(body) => write!(f, "route dead {}: {}", body.code, body.message),
3387            Self::SubscriptionBackpressure(err) => {
3388                write!(f, "subscription event channel backpressure: {err}")
3389            }
3390            Self::StaleRouteHandle(handle) => write!(f, "stale route handle: {handle:?}"),
3391            Self::CapabilityUnprovided { capability } => {
3392                write!(
3393                    f,
3394                    "capability_unprovided: no catalog claimant for {capability}"
3395                )
3396            }
3397            Self::CapabilityAmbiguous {
3398                capability,
3399                claimants,
3400            } => write!(
3401                f,
3402                "capability_ambiguous: multiple catalog claimants for {capability}: {claimants:?}"
3403            ),
3404            Self::InvalidCapabilityIdentifier { capability } => write!(
3405                f,
3406                "invalid_capability_identifier: malformed capability identifier {capability:?}"
3407            ),
3408        }
3409    }
3410}
3411
3412impl Error for CallError {
3413    fn source(&self) -> Option<&(dyn Error + 'static)> {
3414        match self {
3415            Self::NotSent(err)
3416            | Self::OutcomeUnknown(err)
3417            | Self::SubscriptionBackpressure(err) => Some(err.as_ref()),
3418            Self::Module(_)
3419            | Self::RouteDead(_)
3420            | Self::DaemonTooOld { .. }
3421            | Self::StaleRouteHandle(_)
3422            | Self::CapabilityUnprovided { .. }
3423            | Self::CapabilityAmbiguous { .. }
3424            | Self::InvalidCapabilityIdentifier { .. } => None,
3425        }
3426    }
3427}
3428
3429/// A route.open the daemon refused, kept typed inside [`CallError::NotSent`]
3430/// so the refusal's code and `detail` survive. Read it through
3431/// [`CallError::route_open_refusal`].
3432#[derive(Debug, Clone)]
3433struct RouteOpenRefused {
3434    target: String,
3435    body: ErrorBody,
3436    /// The last refusal of a retry loop, when it is not `body`: kept so the
3437    /// message still says what the daemon answered most recently.
3438    most_recent: Option<ErrorBody>,
3439}
3440
3441/// Terminal refusals requiring the caller to supply the scope's current proof.
3442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3443#[non_exhaustive]
3444pub enum ScopeBindProofRefusal {
3445    Required,
3446    Mismatch,
3447}
3448
3449impl fmt::Display for RouteOpenRefused {
3450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3451        write!(
3452            f,
3453            "route.open failed for target {}: {}",
3454            self.target,
3455            DescribeRefusal(&self.body)
3456        )?;
3457        if let Some(most_recent) = &self.most_recent {
3458            write!(
3459                f,
3460                "; the most recent refusal was {}",
3461                DescribeRefusal(most_recent)
3462            )?;
3463        }
3464        Ok(())
3465    }
3466}
3467
3468impl Error for RouteOpenRefused {}
3469
3470/// A refusal as `code (reason r) (message)`, the reason read from
3471/// `detail.reason` and omitted when the daemon sent none.
3472struct DescribeRefusal<'a>(&'a ErrorBody);
3473
3474impl fmt::Display for DescribeRefusal<'_> {
3475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3476        write!(f, "{}", self.0.code)?;
3477        if let Some(reason) = refusal_reason(self.0) {
3478            write!(f, " (reason {reason})")?;
3479        }
3480        write!(f, " ({})", self.0.message)
3481    }
3482}
3483
3484fn refusal_reason(body: &ErrorBody) -> Option<&str> {
3485    body.detail.as_ref()?.get("reason")?.as_str()
3486}
3487
3488/// The daemon's reasons for refusing a route.open because too many binds are
3489/// already in flight, on the consumer's connection or towards the target module
3490/// (`crates/subc-daemon/src/control/route_open.rs`, `route_open_capacity_refusal`
3491/// and `route_open_target_capacity_refusal`). Both are sent as `target_unavailable`.
3492const ADMISSION_PRESSURE_REASONS: [&str; 2] = ["open_admission_full", "target_binds_full"];
3493/// Markers in the messages of those same admission-pressure refusals. The
3494/// daemon currently logs the reason but leaves it out of the refusal's detail,
3495/// so the message is the only way to recognise them.
3496const ADMISSION_PRESSURE_MESSAGES: [&str; 2] =
3497    ["route.open binds in flight", "route.bind relays in flight"];
3498
3499/// How much a route.open refusal says about why the target was unreachable,
3500/// highest first: the module was changing state (reloading or warming); a
3501/// delegation was not registered; admission pressure; anything else.
3502fn route_open_refusal_rank(body: &ErrorBody) -> u8 {
3503    if body.code == error_codes::MODULE_RELOADING || body.code == error_codes::MODULE_WARMING {
3504        return 3;
3505    }
3506    let reason = refusal_reason(body);
3507    if body.code == "delegation_not_registered" || reason == Some("delegation_not_registered") {
3508        return 2;
3509    }
3510    if body.code == error_codes::TARGET_UNAVAILABLE {
3511        let admission_pressure = match reason {
3512            Some(reason) => ADMISSION_PRESSURE_REASONS.contains(&reason),
3513            None => ADMISSION_PRESSURE_MESSAGES
3514                .iter()
3515                .any(|marker| body.message.contains(marker)),
3516        };
3517        if admission_pressure {
3518            return 1;
3519        }
3520    }
3521    0
3522}
3523
3524/// The route.open refusals one retry loop has seen. When the deadline runs out,
3525/// the error is built from the best-ranked one: after a module restart the most
3526/// recent refusal is often admission pressure ("8 binds in flight"), which
3527/// points a reader at the consumer's concurrency when the module was simply down.
3528#[derive(Default)]
3529struct RouteOpenRefusals {
3530    best: Option<ErrorBody>,
3531    /// Set only while the latest refusal ranked below `best`.
3532    most_recent: Option<ErrorBody>,
3533}
3534
3535impl RouteOpenRefusals {
3536    fn record(&mut self, body: ErrorBody) {
3537        // At equal rank the newer refusal wins: it describes the target's latest state.
3538        let outranks = self
3539            .best
3540            .as_ref()
3541            .is_none_or(|best| route_open_refusal_rank(&body) >= route_open_refusal_rank(best));
3542        if outranks {
3543            self.best = Some(body);
3544            self.most_recent = None;
3545        } else {
3546            self.most_recent = Some(body);
3547        }
3548    }
3549
3550    fn into_error(self, target: String) -> Option<CallError> {
3551        let body = self.best?;
3552        Some(CallError::from_route_open_refusal(RouteOpenRefused {
3553            target,
3554            body,
3555            most_recent: self.most_recent,
3556        }))
3557    }
3558}
3559
3560/// The label a route.open refusal names its target by, the same spelling the
3561/// managed route cache uses.
3562fn route_target_label(target: &RouteTarget) -> String {
3563    match target {
3564        RouteTarget::ToolProvider { module_id } => format!("tool_provider:{module_id}"),
3565        RouteTarget::ManagementSurface { module_id } => format!("management_surface:{module_id}"),
3566        RouteTarget::InternalService {
3567            module_id,
3568            service_id,
3569        } => format!("internal_service:{module_id}:{service_id}"),
3570    }
3571}
3572
3573impl CallError {
3574    fn route_open_refused(target: String, body: ErrorBody) -> Self {
3575        Self::from_route_open_refusal(RouteOpenRefused {
3576            target,
3577            body,
3578            most_recent: None,
3579        })
3580    }
3581
3582    fn from_route_open_refusal(refusal: RouteOpenRefused) -> Self {
3583        Self::NotSent(Box::new(NotSentSource {
3584            message: refusal.to_string(),
3585            cause: NotSentCause::RouteOpenRefused {
3586                code: refusal.body.code.clone(),
3587            },
3588            never_forwarded: true,
3589            route_reason: None,
3590            refusal: Some(Box::new(refusal)),
3591        }))
3592    }
3593}
3594
3595#[derive(Debug)]
3596struct SimpleError(String);
3597
3598impl fmt::Display for SimpleError {
3599    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3600        f.write_str(&self.0)
3601    }
3602}
3603
3604impl Error for SimpleError {}
3605
3606type Callback = Arc<Mutex<Box<dyn Fn(ConnectionState) + Send + 'static>>>;
3607
3608type OpeningWaiter = oneshot::Sender<Result<RouteState, SharedCallFailure>>;
3609
3610/// An in-flight route.open for one key: the waiters parked behind the lead opener,
3611/// plus a `closed` flag a concurrent `close_route` flips so the lead opener refuses
3612/// to install its channel (the close-beats-reopen guard). The flag lives here, with
3613/// the in-flight open, so it vanishes when the open finishes — no lingering per-key
3614/// state to leak for a long-lived consumer with unbounded distinct routes.
3615struct Opening {
3616    waiters: Vec<OpeningWaiter>,
3617    closed: bool,
3618}
3619
3620struct Shared {
3621    claim_bound: bool,
3622    connection_file: PathBuf,
3623    operator_app_candidates: Option<Vec<PathBuf>>,
3624    opts: ConsumerOptions,
3625    transport: ConsumerTransport,
3626    identity_from_environment: bool,
3627    inner: Mutex<Inner>,
3628    notify: Notify,
3629    #[cfg(test)]
3630    before_wait: Mutex<Option<Box<dyn FnOnce() + Send>>>,
3631    close_token: CancellationToken,
3632    /// Epoch milliseconds of the last frame dispatched from the current connection.
3633    /// The liveness probe reads this to distinguish a healthy slow request from a
3634    /// socket that has silently stopped delivering inbound traffic.
3635    last_inbound_ms: AtomicU64,
3636    /// Only one deadline-triggered liveness probe may be active across generations.
3637    liveness_probe_running: AtomicBool,
3638    pushes_dropped_no_receiver: AtomicU64,
3639    /// Always-present drop counter for channel-0 control pushes (no receiver,
3640    /// receiver full/closed, or unparseable body). Before this surface existed
3641    /// the drop was SILENT -- not even a counter -- which is how #31's push
3642    /// family shipped unreachable to every Rust consumer (issue #35).
3643    control_pushes_dropped: AtomicU64,
3644    /// Pushes dropped because a registered receiver's bounded buffer was full
3645    /// at delivery time. Distinct from `pushes_dropped_no_receiver` because the
3646    /// operator remedies differ: full means the consumer is too slow (widen the
3647    /// buffer or drain faster), no-receiver means it never subscribed.
3648    pushes_dropped_receiver_full: AtomicU64,
3649    /// Random source in [0, 1) for retry jitter. Tests replace it with a seeded
3650    /// one so jittered delays are reproducible.
3651    random_unit: Box<dyn Fn() -> f64 + Send + Sync>,
3652    /// One permit per route.open the consumer may have outstanding; see
3653    /// [`MAX_ROUTE_OPENS_IN_FLIGHT`]. tokio's semaphore grants permits in
3654    /// request order, which makes the wait first come first served. The consumer
3655    /// holds one connection at a time and a dropped connection fails every open
3656    /// in flight on it, so one semaphore is a per-connection limit.
3657    route_open_slots: Semaphore,
3658    // Serialize the first description lookup, not ordinary opens. The cached
3659    // result belongs to Inner's generation and is reset on reconnect.
3660    route_description: tokio::sync::Mutex<()>,
3661}
3662
3663struct Inner {
3664    generation: u64,
3665    daemon_origin_trusted: bool,
3666    daemon_ver: String,
3667    accepts_close_reasons: Option<bool>,
3668    epoch: u64,
3669    next_corr: Option<u64>,
3670    writer: Option<mpsc::Sender<WriteCommand>>,
3671    pending: HashMap<PendingKey, PendingEntry>,
3672    wire_slots: HashMap<PendingKey, Arc<RoutePermit>>,
3673    routes: HashMap<RouteKey, RouteState>,
3674    route_by_channel: HashMap<u16, RouteKey>,
3675    one_shot_routes: HashMap<u16, RouteState>,
3676    route_epochs: HashMap<u16, RouteHandle>,
3677    route_targets: HashMap<RouteHandle, RouteOpenTarget>,
3678    retired_routes: HashSet<RouteHandle>,
3679    retirement_goodbyes: HashSet<RouteHandle>,
3680    retirement_queue: VecDeque<RouteHandle>,
3681    retirement_notify: Arc<Notify>,
3682    retirement_task: Option<JoinHandle<()>>,
3683    route_modules: HashMap<u16, String>,
3684    route_end_reasons: HashMap<u16, (RouteEnd, bool)>,
3685    legacy_channel_reasons: HashMap<u16, RouteEnd>,
3686    push_event_receivers: HashMap<RouteHandle, mpsc::Sender<PushEvent>>,
3687    /// Consumer-level receiver for daemon-originated channel-0 control pushes
3688    /// (`route.closing`, `route.closed`, future ops). Connection-independent:
3689    /// control pushes are advisory daemon events, so the receiver survives
3690    /// reconnects rather than being keyed by generation.
3691    control_push_receiver: Option<mpsc::Sender<ControlPush>>,
3692    dropped_route_frames: u64,
3693    openings: HashMap<RouteKey, Opening>,
3694    callbacks: Vec<Callback>,
3695    closed: bool,
3696    reconnect: ReconnectState,
3697    restored_token: u64,
3698    reader_task: Option<JoinHandle<()>>,
3699    writer_task: Option<JoinHandle<()>>,
3700}
3701
3702impl Inner {
3703    fn record_route_end(&mut self, push: &ControlPush) {
3704        let Some(reason) = push.route_close_reason() else {
3705            return;
3706        };
3707        let end = RouteEnd {
3708            reason: RouteEndReason::Daemon(reason),
3709            terminal: (push.op == "route.closed")
3710                .then(|| {
3711                    push.body
3712                        .get("terminal")
3713                        .and_then(serde_json::Value::as_bool)
3714                })
3715                .flatten(),
3716        };
3717        if let Some(channels) = push.body.get("channels") {
3718            if let Some(channels) = channels.as_array() {
3719                for channel in channels
3720                    .iter()
3721                    .filter_map(|v| v.as_u64().and_then(|v| u16::try_from(v).ok()))
3722                {
3723                    let final_reason = push.op == "route.closed";
3724                    if final_reason
3725                        || !self
3726                            .route_end_reasons
3727                            .get(&channel)
3728                            .is_some_and(|(_, final_reason)| *final_reason)
3729                    {
3730                        self.route_end_reasons
3731                            .insert(channel, (end.clone(), final_reason));
3732                    }
3733                }
3734            }
3735        } else if let Some(module) = push.body.get("module_id").and_then(|v| v.as_str()) {
3736            for (&channel, target) in &self.route_modules {
3737                if target == module {
3738                    self.legacy_channel_reasons.insert(channel, end.clone());
3739                }
3740            }
3741        }
3742    }
3743
3744    fn route_end(&self, channel: u16) -> RouteEnd {
3745        self.route_end_reasons
3746            .get(&channel)
3747            .map(|(reason, _)| reason.clone())
3748            .or_else(|| self.legacy_channel_reasons.get(&channel).cloned())
3749            .unwrap_or_else(|| RouteEndReason::Unknown.into())
3750    }
3751
3752    #[cfg(test)]
3753    fn route_end_reason(&self, channel: u16) -> RouteEndReason {
3754        self.route_end(channel).reason
3755    }
3756
3757    fn cache_route(&mut self, key: RouteKey, route: RouteState) -> RouteState {
3758        let cached = self.routes.entry(key.clone()).or_insert(route).clone();
3759        let previous = self
3760            .route_by_channel
3761            .insert(cached.handle.channel, key.clone());
3762        debug_assert!(previous.as_ref().is_none_or(|previous| previous == &key));
3763        self.route_epochs
3764            .insert(cached.handle.channel, cached.handle);
3765        cached
3766    }
3767
3768    fn remove_route(&mut self, key: &RouteKey) -> Option<RouteState> {
3769        let route = self.evict_route(key)?;
3770        release_reverse_request_registry(route.handle);
3771        Some(route)
3772    }
3773
3774    fn evict_route(&mut self, key: &RouteKey) -> Option<RouteState> {
3775        let route = self.routes.remove(key)?;
3776        let indexed = self.route_by_channel.remove(&route.handle.channel);
3777        debug_assert_eq!(indexed.as_ref(), Some(key));
3778        Some(route)
3779    }
3780
3781    fn reap_retired_route(&mut self, handle: RouteHandle) {
3782        // A caller may be gone while its written correlation still owns credit.
3783        // Keep ingress for those tombstones as well as live pending callers.
3784        if !self.retired_routes.contains(&handle)
3785            || self
3786                .pending
3787                .keys()
3788                .chain(self.wire_slots.keys())
3789                .any(|key| {
3790                    key.generation == handle.connection_token()
3791                        && key.channel == handle.channel
3792                        && key.epoch == handle.epoch
3793                })
3794        {
3795            return;
3796        }
3797        // Pending keys carry only the wire identity. Use the retained handle
3798        // when releasing its reverse-request registry after retirement.
3799        let handle = *self
3800            .retired_routes
3801            .get(&handle)
3802            .expect("retired route exists");
3803        if self.retirement_goodbyes.contains(&handle) {
3804            if !self.queue_retirement_goodbye(handle) {
3805                // Keep the ingress handle occupied until the flusher queues the
3806                // GOODBYE, so a reopened route cannot take this channel first.
3807                return;
3808            }
3809            self.retirement_goodbyes.remove(&handle);
3810        }
3811        self.retired_routes.remove(&handle);
3812        if self.route_epochs.get(&handle.channel) == Some(&handle) {
3813            self.route_epochs.remove(&handle.channel);
3814            self.route_targets.remove(&handle);
3815            self.push_event_receivers.remove(&handle);
3816        }
3817        release_reverse_request_registry(handle);
3818    }
3819
3820    fn queue_retirement_goodbye(&mut self, handle: RouteHandle) -> bool {
3821        if self.generation != handle.connection_token()
3822            || self.route_epochs.get(&handle.channel) != Some(&handle)
3823            || self.writer.is_none()
3824        {
3825            return true;
3826        }
3827        if self.retirement_queue.is_empty() {
3828            let frame = Frame::build(
3829                FrameType::Goodbye,
3830                Flags::new(false, Priority::Interactive, false),
3831                handle.channel,
3832                handle.epoch,
3833                0,
3834                Vec::new(),
3835            )
3836            .expect("header-only route GOODBYE is valid");
3837            if self
3838                .writer
3839                .as_ref()
3840                .unwrap()
3841                .try_send(WriteCommand {
3842                    frame,
3843                    pending: None,
3844                })
3845                .is_ok()
3846            {
3847                return true;
3848            }
3849        }
3850        // Once one retirement is waiting, later retirements join the same FIFO
3851        // rather than overtaking it through the synchronous fast path.
3852        if !self.retirement_queue.contains(&handle) {
3853            self.retirement_queue.push_back(handle);
3854        }
3855        self.retirement_notify.notify_one();
3856        false
3857    }
3858
3859    fn remove_pending(&mut self, key: &PendingKey) -> Option<PendingEntry> {
3860        let entry = self.pending.remove(key);
3861        if entry.as_ref().is_some_and(|entry| !entry.accepted) {
3862            if let Some(slot) = self.wire_slots.remove(key) {
3863                slot.release();
3864            }
3865        }
3866        self.reap_retired_route(RouteHandle::new(key.channel, key.epoch, key.generation));
3867        entry
3868    }
3869
3870    fn release_wire_slots(&mut self, handle: RouteHandle) {
3871        self.wire_slots.retain(|key, slot| {
3872            let keep = key.generation != handle.connection_token()
3873                || key.channel != handle.channel
3874                || key.epoch != handle.epoch;
3875            if !keep {
3876                slot.release();
3877            }
3878            keep
3879        });
3880    }
3881
3882    fn remove_route_by_handle(&mut self, handle: RouteHandle) -> Option<RouteState> {
3883        if let Some(key) = self.route_by_channel.get(&handle.channel).cloned() {
3884            let matches = self
3885                .routes
3886                .get(&key)
3887                .is_some_and(|route| route.handle == handle);
3888            debug_assert!(matches);
3889            if matches {
3890                return self.remove_route(&key);
3891            }
3892        }
3893        let route = self
3894            .one_shot_routes
3895            .get(&handle.channel)
3896            .is_some_and(|route| route.handle == handle)
3897            .then(|| self.one_shot_routes.remove(&handle.channel))
3898            .flatten();
3899        if let Some(route) = &route {
3900            release_reverse_request_registry(route.handle);
3901        }
3902        route
3903    }
3904
3905    fn drain_routes(&mut self) -> Vec<RouteState> {
3906        self.route_targets.clear();
3907        for (_, slot) in self.wire_slots.drain() {
3908            slot.release();
3909        }
3910        self.retirement_goodbyes.clear();
3911        self.retirement_queue.clear();
3912        if let Some(task) = self.retirement_task.take() {
3913            task.abort();
3914        }
3915        for handle in self.retired_routes.drain() {
3916            release_reverse_request_registry(handle);
3917        }
3918        self.route_by_channel.clear();
3919        let routes = self
3920            .routes
3921            .drain()
3922            .map(|(_, route)| route)
3923            .chain(self.one_shot_routes.drain().map(|(_, route)| route))
3924            .collect::<Vec<_>>();
3925        for route in &routes {
3926            release_reverse_request_registry(route.handle);
3927        }
3928        routes
3929    }
3930
3931    fn close_routes(&mut self) {
3932        self.push_event_receivers.clear();
3933        for route in self.drain_routes() {
3934            route.close();
3935        }
3936    }
3937}
3938
3939impl Shared {
3940    fn new(connection_file: PathBuf, opts: ConsumerOptions) -> Self {
3941        Self::with_transport(connection_file, opts, ConsumerTransport::Tcp)
3942    }
3943
3944    fn with_transport(
3945        connection_file: PathBuf,
3946        opts: ConsumerOptions,
3947        transport: ConsumerTransport,
3948    ) -> Self {
3949        Self {
3950            claim_bound: crate::registration::bound(),
3951            connection_file,
3952            operator_app_candidates: None,
3953            opts,
3954            transport,
3955            identity_from_environment: true,
3956            inner: Mutex::new(Inner {
3957                generation: 1,
3958                daemon_origin_trusted: false,
3959                daemon_ver: String::new(),
3960                accepts_close_reasons: None,
3961                epoch: 1,
3962                next_corr: Some(1),
3963                writer: None,
3964                pending: HashMap::new(),
3965                wire_slots: HashMap::new(),
3966                routes: HashMap::new(),
3967                route_by_channel: HashMap::new(),
3968                one_shot_routes: HashMap::new(),
3969                route_epochs: HashMap::new(),
3970                route_targets: HashMap::new(),
3971                retired_routes: HashSet::new(),
3972                retirement_goodbyes: HashSet::new(),
3973                retirement_queue: VecDeque::new(),
3974                retirement_notify: Arc::new(Notify::new()),
3975                retirement_task: None,
3976                route_modules: HashMap::new(),
3977                route_end_reasons: HashMap::new(),
3978                legacy_channel_reasons: HashMap::new(),
3979                push_event_receivers: HashMap::new(),
3980                control_push_receiver: None,
3981                dropped_route_frames: 0,
3982                openings: HashMap::new(),
3983                callbacks: Vec::new(),
3984                closed: false,
3985                reconnect: ReconnectState::Idle,
3986                restored_token: 0,
3987                reader_task: None,
3988                writer_task: None,
3989            }),
3990            notify: Notify::new(),
3991            #[cfg(test)]
3992            before_wait: Mutex::new(None),
3993            close_token: CancellationToken::new(),
3994            last_inbound_ms: AtomicU64::new(0),
3995            liveness_probe_running: AtomicBool::new(false),
3996            pushes_dropped_no_receiver: AtomicU64::new(0),
3997            control_pushes_dropped: AtomicU64::new(0),
3998            pushes_dropped_receiver_full: AtomicU64::new(0),
3999            random_unit: Box::new(default_random_unit),
4000            route_open_slots: Semaphore::new(MAX_ROUTE_OPENS_IN_FLIGHT),
4001            route_description: tokio::sync::Mutex::new(()),
4002        }
4003    }
4004
4005    /// "Equal jitter": keep half of `delay` and randomize the other half. Every
4006    /// route on a connection is closed together when its module drains, so
4007    /// without jitter they all retry in lock step and reach the daemon as one
4008    /// burst each round; reconnects after a daemon restart herd the same way.
4009    fn jittered(&self, delay: Duration) -> Duration {
4010        let unit = (self.random_unit)();
4011        let unit = if unit.is_finite() {
4012            unit.clamp(0.0, 1.0)
4013        } else {
4014            0.0
4015        };
4016        let half = delay / 2;
4017        half + half.mul_f64(unit)
4018    }
4019
4020    /// One route.open exchange, paced by [`MAX_ROUTE_OPENS_IN_FLIGHT`]. The
4021    /// wait for a free slot ends at `deadline` like the exchange itself.
4022    async fn paced_route_open(
4023        self: &Arc<Self>,
4024        body: Vec<u8>,
4025        deadline: Instant,
4026        reverse_requests: Option<ReverseRequestRegistry>,
4027    ) -> Result<TerminalFrame, CallError> {
4028        let _slot = match timeout_at(deadline, self.route_open_slots.acquire()).await {
4029            Ok(Ok(permit)) => permit,
4030            Ok(Err(_)) => return Err(CallError::not_sent("consumer closed")),
4031            Err(_) => {
4032                return Err(CallError::not_sent(format!(
4033                    "deadline elapsed waiting for one of {MAX_ROUTE_OPENS_IN_FLIGHT} route.open slots"
4034                )));
4035            }
4036        };
4037        self.control_call(body, deadline, true, reverse_requests)
4038            .await
4039    }
4040
4041    fn lock_inner(&self) -> MutexGuard<'_, Inner> {
4042        self.inner
4043            .lock()
4044            .unwrap_or_else(|poisoned| poisoned.into_inner())
4045    }
4046
4047    fn install_initial(self: &Arc<Self>, opened: OpenedConnection) -> Result<(), ConsumerError> {
4048        self.install_connection(opened, InstallKind::Initial)
4049            .map(|_| ())
4050    }
4051
4052    fn install_reconnected(
4053        self: &Arc<Self>,
4054        opened: OpenedConnection,
4055    ) -> Result<(u64, u64), ConsumerError> {
4056        let generation_epoch = self.install_connection(opened, InstallKind::Reconnect)?;
4057        self.notify.notify_waiters();
4058        Ok(generation_epoch)
4059    }
4060
4061    fn install_connection(
4062        self: &Arc<Self>,
4063        opened: OpenedConnection,
4064        kind: InstallKind,
4065    ) -> Result<(u64, u64), ConsumerError> {
4066        if self.close_token.is_cancelled() {
4067            return Err(ConsumerError::Closed);
4068        }
4069
4070        let (reader, writer) = tokio::io::split(opened.stream);
4071        let (tx, rx) = mpsc::channel(EGRESS_BUFFER);
4072        let (generation, epoch, old_reader, old_writer) = {
4073            let mut inner = self.lock_inner();
4074            if inner.closed {
4075                return Err(ConsumerError::Closed);
4076            }
4077            let (generation, epoch) = match kind {
4078                InstallKind::Initial => (inner.generation, inner.epoch),
4079                InstallKind::Reconnect => {
4080                    inner.generation = inner
4081                        .generation
4082                        .checked_add(1)
4083                        .ok_or(ConsumerError::Closed)?;
4084                    inner.epoch = inner.epoch.checked_add(1).ok_or(ConsumerError::Closed)?;
4085                    (inner.generation, inner.epoch)
4086                }
4087            };
4088            inner.close_routes();
4089            inner.route_epochs.clear();
4090            inner.route_targets.clear();
4091            inner.route_modules.clear();
4092            inner.route_end_reasons.clear();
4093            inner.legacy_channel_reasons.clear();
4094            inner.next_corr = Some(1);
4095            inner.writer = Some(tx);
4096            inner.daemon_origin_trusted = opened.daemon_origin_trusted;
4097            inner.daemon_ver = opened.daemon_ver;
4098            inner.accepts_close_reasons = None;
4099            self.last_inbound_ms.store(0, Ordering::Release);
4100            (
4101                generation,
4102                epoch,
4103                inner.reader_task.take(),
4104                inner.writer_task.take(),
4105            )
4106        };
4107
4108        if let Some(handle) = old_reader {
4109            handle.abort();
4110        }
4111        if let Some(handle) = old_writer {
4112            handle.abort();
4113        }
4114
4115        let reader_shared = Arc::clone(self);
4116        let reader_task = tokio::spawn(async move {
4117            reader_loop(reader_shared, reader, generation).await;
4118        });
4119        let writer_shared = Arc::clone(self);
4120        let writer_task = tokio::spawn(async move {
4121            writer_loop(writer_shared, writer, rx, generation).await;
4122        });
4123
4124        {
4125            let mut inner = self.lock_inner();
4126            if inner.closed || inner.generation != generation {
4127                reader_task.abort();
4128                writer_task.abort();
4129                return Err(ConsumerError::Closed);
4130            }
4131            inner.reader_task = Some(reader_task);
4132            inner.writer_task = Some(writer_task);
4133            let retirement_shared = Arc::clone(self);
4134            let retirement_notify = Arc::clone(&inner.retirement_notify);
4135            inner.retirement_task = Some(tokio::spawn(async move {
4136                retirement_goodbye_loop(retirement_shared, generation, retirement_notify).await;
4137            }));
4138        }
4139
4140        Ok((generation, epoch))
4141    }
4142
4143    async fn ensure_connected_for_call(
4144        self: &Arc<Self>,
4145        deadline: Instant,
4146    ) -> Result<(), CallError> {
4147        loop {
4148            if Instant::now() >= deadline {
4149                return Err(CallError::not_sent(
4150                    "call deadline elapsed waiting for reconnection",
4151                ));
4152            }
4153            // Created BEFORE the state is read, and that ordering is the fix.
4154            // Reconnect completion wakes waiters with `notify_waiters()`, which
4155            // reaches only `Notified` futures that already exist and stores no
4156            // permit. A future created after the lock is released misses a
4157            // reconnect that finishes in between, and the caller then sleeps
4158            // until its deadline on a healthy connection. (`enable()` is kept
4159            // for `notify_one` semantics; for `notify_waiters` creation alone
4160            // is what registers the waiter.)
4161            let notified = self.notify.notified();
4162            tokio::pin!(notified);
4163            let action = {
4164                let mut inner = self.lock_inner();
4165                notified.as_mut().enable();
4166                if inner.closed {
4167                    return Err(CallError::not_sent("consumer closed"));
4168                }
4169                if inner.writer.is_some() {
4170                    return Ok(());
4171                }
4172                let generation = inner.generation;
4173                let reconnect_is_live = match &inner.reconnect {
4174                    ReconnectState::Idle => false,
4175                    ReconnectState::Inline { generation: active } => *active == generation,
4176                    ReconnectState::Background {
4177                        generation: active,
4178                        task,
4179                    } => *active == generation && !task.is_finished(),
4180                };
4181                if reconnect_is_live {
4182                    EnsureAction::Wait
4183                } else {
4184                    let stale_task =
4185                        match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
4186                            ReconnectState::Background { task, .. } => Some(task),
4187                            ReconnectState::Idle | ReconnectState::Inline { .. } => None,
4188                        };
4189                    inner.reconnect = ReconnectState::Inline { generation };
4190                    EnsureAction::Lead {
4191                        generation,
4192                        stale_task,
4193                    }
4194                }
4195            };
4196
4197            match action {
4198                EnsureAction::Wait => {
4199                    #[cfg(test)]
4200                    {
4201                        let hook = self.before_wait.lock().unwrap().take();
4202                        if let Some(hook) = hook {
4203                            hook();
4204                        }
4205                    }
4206                    timeout_at(deadline, notified).await.map_err(|_| {
4207                        CallError::not_sent("call deadline elapsed waiting for reconnection")
4208                    })?;
4209                }
4210                EnsureAction::Lead {
4211                    generation,
4212                    stale_task,
4213                } => {
4214                    if let Some(handle) = stale_task {
4215                        handle.abort();
4216                    }
4217                    let mut guard = InlineReconnectGuard::new(Arc::clone(self), generation);
4218                    let result = timeout_at(deadline, self.reconnect_with_retry(generation)).await;
4219                    guard.finish();
4220                    return match result {
4221                        Ok(Ok(())) => Ok(()),
4222                        Ok(Err(err)) => Err(CallError::not_sent(err.to_string())),
4223                        Err(_) => Err(CallError::not_sent(
4224                            "call deadline elapsed waiting for reconnection",
4225                        )),
4226                    };
4227                }
4228            }
4229        }
4230    }
4231
4232    fn spawn_reconnect(self: &Arc<Self>, generation: u64) -> bool {
4233        // Reconnect ownership is fenced by the dropped transport generation. A
4234        // newer drop replaces an older attempt instead of letting that attempt
4235        // block recovery for the newer transport.
4236        let stale_task = {
4237            let mut inner = self.lock_inner();
4238            if inner.closed || inner.writer.is_some() || inner.generation != generation {
4239                return false;
4240            }
4241            let should_spawn = match &inner.reconnect {
4242                ReconnectState::Idle => true,
4243                ReconnectState::Inline { generation: active } => *active < generation,
4244                ReconnectState::Background {
4245                    generation: active,
4246                    task,
4247                } => *active < generation || (*active == generation && task.is_finished()),
4248            };
4249            if !should_spawn {
4250                return false;
4251            }
4252
4253            let stale_task = match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
4254                ReconnectState::Background { task, .. } => Some(task),
4255                ReconnectState::Idle | ReconnectState::Inline { .. } => None,
4256            };
4257            let shared = Arc::clone(self);
4258            let handle = tokio::spawn(async move {
4259                let _result = shared.reconnect_with_retry(generation).await;
4260                shared.finish_background_reconnect(generation);
4261            });
4262            inner.reconnect = ReconnectState::Background {
4263                generation,
4264                task: handle,
4265            };
4266            stale_task
4267        };
4268        if let Some(handle) = stale_task {
4269            handle.abort();
4270        }
4271        true
4272    }
4273
4274    async fn reconnect_with_retry(
4275        self: &Arc<Self>,
4276        reconnect_generation: u64,
4277    ) -> Result<(), ConsumerError> {
4278        let mut last_error: Option<ConsumerError> = None;
4279        for attempt in 1..=self.opts.reconnect_backoff.max_attempts {
4280            if self.close_token.is_cancelled() {
4281                return Err(ConsumerError::Closed);
4282            }
4283            if !self.reconnect_attempt_is_current(reconnect_generation) {
4284                return Ok(());
4285            }
4286
4287            match open_connection(
4288                &self.connection_file,
4289                self.opts.handshake_timeout,
4290                self.transport,
4291                self.operator_app_candidates.as_deref(),
4292            )
4293            .await
4294            {
4295                Ok(opened) => {
4296                    // A newer drop may have installed its own attempt while this
4297                    // connection was opening. Do not let the stale attempt replace it.
4298                    if !self.reconnect_attempt_is_current(reconnect_generation) {
4299                        return Ok(());
4300                    }
4301                    let (generation, epoch) = self.install_reconnected(opened)?;
4302                    self.schedule_restored(generation, epoch);
4303                    return Ok(());
4304                }
4305                Err(err) => {
4306                    let transient = is_reconnect_transient(&err);
4307                    last_error = Some(err);
4308                    if !transient || attempt >= self.opts.reconnect_backoff.max_attempts {
4309                        break;
4310                    }
4311                    // Jittered like the route.open retries, which share this backoff.
4312                    let delay =
4313                        self.jittered(self.opts.reconnect_backoff.delay_after_attempt(attempt));
4314                    tokio::select! {
4315                        () = self.close_token.cancelled() => return Err(ConsumerError::Closed),
4316                        () = sleep(delay) => {}
4317                    }
4318                }
4319            }
4320        }
4321        Err(last_error.unwrap_or(ConsumerError::Closed))
4322    }
4323
4324    fn reconnect_attempt_is_current(&self, generation: u64) -> bool {
4325        let inner = self.lock_inner();
4326        !inner.closed
4327            && inner.writer.is_none()
4328            && inner.generation == generation
4329            && matches!(
4330                &inner.reconnect,
4331                ReconnectState::Inline { generation: active }
4332                    | ReconnectState::Background {
4333                        generation: active,
4334                        ..
4335                    } if *active == generation
4336            )
4337    }
4338
4339    fn finish_inline_reconnect(&self, generation: u64) {
4340        let finished = {
4341            let mut inner = self.lock_inner();
4342            if matches!(
4343                &inner.reconnect,
4344                ReconnectState::Inline { generation: active } if *active == generation
4345            ) {
4346                inner.reconnect = ReconnectState::Idle;
4347                true
4348            } else {
4349                false
4350            }
4351        };
4352        if finished {
4353            self.notify.notify_waiters();
4354        }
4355    }
4356
4357    fn finish_background_reconnect(&self, generation: u64) {
4358        let completed_task = {
4359            let mut inner = self.lock_inner();
4360            if !matches!(
4361                &inner.reconnect,
4362                ReconnectState::Background { generation: active, .. } if *active == generation
4363            ) {
4364                None
4365            } else {
4366                match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
4367                    ReconnectState::Background { task, .. } => Some(task),
4368                    ReconnectState::Idle | ReconnectState::Inline { .. } => unreachable!(),
4369                }
4370            }
4371        };
4372        if completed_task.is_some() {
4373            drop(completed_task);
4374            self.notify.notify_waiters();
4375        }
4376    }
4377
4378    fn schedule_restored(self: &Arc<Self>, generation: u64, epoch: u64) {
4379        let token = {
4380            let mut inner = self.lock_inner();
4381            inner.restored_token = inner.restored_token.saturating_add(1);
4382            inner.restored_token
4383        };
4384        let shared = Arc::clone(self);
4385        tokio::spawn(async move {
4386            tokio::select! {
4387                () = shared.close_token.cancelled() => {}
4388                () = sleep(shared.opts.restored_debounce) => {
4389                    let should_emit = {
4390                        let inner = shared.lock_inner();
4391                        !inner.closed
4392                            && inner.generation == generation
4393                            && inner.epoch == epoch
4394                            && inner.restored_token == token
4395                            && inner.writer.is_some()
4396                    };
4397                    if should_emit {
4398                        shared.emit_connection_state(ConnectionState::Restored { epoch });
4399                    }
4400                }
4401            }
4402        });
4403    }
4404
4405    fn install_one_shot_route(&self, route: RouteState) -> Result<(), CallError> {
4406        let handle = route.handle;
4407        let mut inner = self.lock_inner();
4408        if inner.closed || inner.generation != handle.connection_token() || inner.writer.is_none() {
4409            return Err(CallError::StaleRouteHandle(handle));
4410        }
4411        // The socket reader installs the handle for a route.open response before
4412        // the waiter resolves (so a request the provider sends right after the
4413        // bind is routed), so this route's own channel is normally present
4414        // already, holding exactly this handle. Only a different handle on the
4415        // channel is a collision.
4416        if inner
4417            .route_epochs
4418            .get(&handle.channel)
4419            .is_some_and(|existing| *existing != handle)
4420        {
4421            return Err(CallError::not_sent(
4422                "daemon returned a route channel already in use",
4423            ));
4424        }
4425        inner.one_shot_routes.insert(handle.channel, route);
4426        inner.route_epochs.insert(handle.channel, handle);
4427        Ok(())
4428    }
4429
4430    async fn ensure_route(
4431        self: &Arc<Self>,
4432        key: &RouteKey,
4433        route_open: &RouteOpenParams<'_>,
4434        opts: &CallOptions,
4435        call_deadline: Instant,
4436    ) -> Result<RouteState, CallError> {
4437        loop {
4438            let action = {
4439                let mut inner = self.lock_inner();
4440                if inner.closed {
4441                    return Err(CallError::not_sent("consumer closed"));
4442                }
4443                if let Some(route) = inner.routes.get(key) {
4444                    if route.handle.connection_token() == inner.generation && inner.writer.is_some()
4445                    {
4446                        return Ok(route.clone());
4447                    }
4448                }
4449                if let Some(opening) = inner.openings.get_mut(key) {
4450                    let (tx, rx) = oneshot::channel();
4451                    opening.waiters.push(tx);
4452                    RouteOpenAction::Wait(rx)
4453                } else {
4454                    inner.openings.insert(
4455                        key.clone(),
4456                        Opening {
4457                            waiters: Vec::new(),
4458                            closed: false,
4459                        },
4460                    );
4461                    RouteOpenAction::Lead
4462                }
4463            };
4464
4465            match action {
4466                RouteOpenAction::Wait(rx) => match timeout_at(call_deadline, rx).await {
4467                    Ok(Ok(Ok(route))) => return Ok(route),
4468                    Ok(Ok(Err(err))) => return Err(err.into_call_error()),
4469                    Ok(Err(_)) => continue,
4470                    Err(_) => {
4471                        return Err(CallError::not_sent_with_cause(
4472                            "call deadline elapsed waiting for route.open",
4473                            NotSentCause::RouteOpenAbandoned,
4474                        ));
4475                    }
4476                },
4477                RouteOpenAction::Lead => {
4478                    let mut guard = OpeningGuard::new(Arc::clone(self), key.clone());
4479                    let result = self
4480                        .open_route_with_retry(key, route_open, opts, call_deadline)
4481                        .await
4482                        .map_err(SharedCallFailure::from);
4483                    guard.finish(result.clone());
4484                    return result.map_err(SharedCallFailure::into_call_error);
4485                }
4486            }
4487        }
4488    }
4489
4490    async fn open_route_with_retry(
4491        self: &Arc<Self>,
4492        key: &RouteKey,
4493        route_open: &RouteOpenParams<'_>,
4494        opts: &CallOptions,
4495        call_deadline: Instant,
4496    ) -> Result<RouteState, CallError> {
4497        let route_deadline = (Instant::now() + opts.route_retry_deadline).min(call_deadline);
4498        let mut attempt = 0usize;
4499        // The retryable refusals seen so far. When the deadline ends the retries,
4500        // the caller gets the most informative of them rather than a bare
4501        // "deadline elapsed", so "the module was reloading" stays
4502        // distinguishable from "the connection failed".
4503        let mut refusals = RouteOpenRefusals::default();
4504        // An attempt that ends because the deadline passed hands back the kept
4505        // refusal. That covers an attempt that never left the client (NotSent)
4506        // and one the daemon received but had not answered by the deadline
4507        // (OutcomeUnknown with the Deadline cause): a busy daemon can answer
4508        // the final retry a few milliseconds late, and the refusals before it
4509        // still say why the route never opened. Dropping the unanswered
4510        // attempt's own outcome is safe: route.open requests are sent with
4511        // `retain_late_route_open`, so a late acceptance is closed again with
4512        // a GOODBYE instead of being handed to anyone.
4513        let expired = |err: CallError, refusals: &mut RouteOpenRefusals| {
4514            let ended_by_deadline =
4515                err.is_not_sent() || err.outcome_cause() == Some(OutcomeUnknownCause::Deadline);
4516            if ended_by_deadline && Instant::now() >= route_deadline {
4517                if let Some(refused) = std::mem::take(refusals).into_error(key.target_label()) {
4518                    return refused;
4519                }
4520            }
4521            err
4522        };
4523        loop {
4524            attempt = attempt.saturating_add(1);
4525            let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
4526                busy_refusals: Some(true),
4527                target: route_open.target.clone(),
4528                identity: route_open.identity.clone(),
4529                consumer_identity: route_open.consumer_identity.clone(),
4530                consumer_capabilities: route_open.consumer_capabilities.clone(),
4531                role_versions: route_open.role_versions.clone(),
4532                admission_facts: None,
4533                scope: route_open.scope.cloned(),
4534            })
4535            .map_err(|err| CallError::not_sent(format!("failed to encode route.open: {err}")))?;
4536            match self
4537                .paced_route_open(
4538                    body,
4539                    route_deadline,
4540                    Some(route_open.reverse_requests.clone()),
4541                )
4542                .await
4543            {
4544                Ok(TerminalFrame::Response {
4545                    generation, body, ..
4546                }) => {
4547                    let (response, _) = decode_route_open_response(&body).map_err(|err| {
4548                        CallError::not_sent_with_cause(
4549                            format!("failed to decode route.open response: {err}"),
4550                            NotSentCause::RouteOpenAbandoned,
4551                        )
4552                    })?;
4553                    let ClientControlResponse::RouteOpen {
4554                        route_channel,
4555                        route_epoch,
4556                        request_window,
4557                        watch_window,
4558                        ..
4559                    } = response
4560                    else {
4561                        return Err(CallError::not_sent_with_cause(
4562                            "route.open returned an unexpected control response",
4563                            NotSentCause::RouteOpenAbandoned,
4564                        ));
4565                    };
4566                    let handle = self
4567                        .ingress_handle(generation, route_channel, route_epoch)
4568                        .unwrap_or_else(|| {
4569                            RouteHandle::new_consumer(
4570                                route_channel,
4571                                route_epoch,
4572                                generation,
4573                                route_open.reverse_requests.clone(),
4574                            )
4575                        });
4576                    let route = RouteState::windows(handle, request_window, watch_window);
4577                    let install = {
4578                        let mut inner = self.lock_inner();
4579                        if inner.closed {
4580                            return Err(CallError::not_sent("consumer closed"));
4581                        }
4582                        // Close-beats-reopen guard: a close_route may have flipped this
4583                        // opening's `closed` flag WHILE this route.open was in flight. If
4584                        // so, close wins — do NOT cache the channel; GOODBYE it below and
4585                        // fail as NotSent (the route was closed before the open landed).
4586                        let closed_during_open = inner.openings.get(key).is_some_and(|o| o.closed);
4587                        if closed_during_open
4588                            || inner.generation != generation
4589                            || inner.writer.is_none()
4590                        {
4591                            RouteInstall::Discard {
4592                                closed: closed_during_open,
4593                            }
4594                        } else {
4595                            let cached = inner.cache_route(key.clone(), route.clone());
4596                            RouteInstall::Cached(cached)
4597                        }
4598                    };
4599                    match install {
4600                        RouteInstall::Cached(cached) => return Ok(cached),
4601                        RouteInstall::Discard { closed } => {
4602                            if closed {
4603                                // GOODBYE the channel we opened so the daemon/module don't
4604                                // leak it, then report the close as a NotSent failure.
4605                                self.send_route_goodbye(route.handle, true);
4606                                self.uninstall_route_handle(route.handle);
4607                                return Err(CallError::not_sent_with_cause(
4608                                    "route was closed before route.open completed",
4609                                    NotSentCause::RouteOpenAbandoned,
4610                                ));
4611                            }
4612                            // Stale generation / writer gone: fall through to retry.
4613                        }
4614                    }
4615                    self.sleep_until_retry(route_deadline, self.jittered(opts.route_retry.base))
4616                        .await?;
4617                }
4618                Ok(TerminalFrame::Error { body, .. }) => {
4619                    // The deadline is the ONLY binder for retryable refusals.
4620                    // An attempt cap used to share this condition, and because
4621                    // the capped backoff sums to seconds it strictly dominated
4622                    // the deadline — the advertised reload patience was never
4623                    // delivered, and module restarts whose reload exceeded a
4624                    // few seconds failed every managed caller. A restart
4625                    // legitimately keeps routes refused for about a minute;
4626                    // capped per-attempt backoff bounds pressure.
4627                    if !error_codes::is_retryable_route_open_refusal(&body) {
4628                        return Err(CallError::route_open_refused(key.target_label(), body));
4629                    }
4630                    refusals.record(body);
4631                    if Instant::now() >= route_deadline {
4632                        // A refusal was just recorded, so the fallback is unreachable.
4633                        return Err(std::mem::take(&mut refusals)
4634                            .into_error(key.target_label())
4635                            .unwrap_or_else(|| {
4636                                CallError::not_sent("route.open retry deadline elapsed")
4637                            }));
4638                    }
4639                    let delay = self.jittered(opts.route_retry.delay_after_attempt(attempt));
4640                    if let Err(err) = self.sleep_until_retry(route_deadline, delay).await {
4641                        return Err(expired(err, &mut refusals));
4642                    }
4643                    continue;
4644                }
4645                Ok(TerminalFrame::StreamEnd) => {
4646                    return Err(CallError::not_sent_with_cause(
4647                        "route.open returned StreamEnd",
4648                        NotSentCause::RouteOpenAbandoned,
4649                    ));
4650                }
4651                Err(err) if err.is_not_sent() && Instant::now() < route_deadline => {
4652                    let delay = self.jittered(opts.route_retry.delay_after_attempt(attempt));
4653                    if let Err(err) = self.sleep_until_retry(route_deadline, delay).await {
4654                        return Err(expired(err, &mut refusals));
4655                    }
4656                }
4657                Err(err) => return Err(expired(err, &mut refusals)),
4658            }
4659        }
4660
4661        #[allow(unreachable_code)]
4662        Err(CallError::not_sent(format!(
4663            "route.open retry deadline elapsed for target {}",
4664            key.target_label()
4665        )))
4666    }
4667
4668    async fn sleep_until_retry(&self, deadline: Instant, delay: Duration) -> Result<(), CallError> {
4669        if Instant::now() >= deadline {
4670            return Err(CallError::not_sent("retry deadline elapsed"));
4671        }
4672        let bounded = delay.min(deadline.saturating_duration_since(Instant::now()));
4673        tokio::select! {
4674            () = self.close_token.cancelled() => Err(CallError::not_sent("consumer closed")),
4675            () = sleep(bounded) => Ok(()),
4676        }
4677    }
4678
4679    async fn control_call(
4680        self: &Arc<Self>,
4681        body: Vec<u8>,
4682        deadline: Instant,
4683        retain_late_route_open: bool,
4684        route_open_reverse_requests: Option<ReverseRequestRegistry>,
4685    ) -> Result<TerminalFrame, CallError> {
4686        self.ensure_connected_for_call(deadline).await?;
4687        if retain_late_route_open {
4688            {
4689                let inner = self.lock_inner();
4690                if !daemon_version_at_least(&inner.daemon_ver, (0, 39, 0)) {
4691                    return Err(CallError::DaemonTooOld {
4692                        daemon_ver: inner.daemon_ver.clone(),
4693                    });
4694                }
4695            }
4696            self.describe_route_close_reasons(deadline).await?;
4697        }
4698        self.send_request(RequestSend {
4699            binary: false,
4700            expected_handle: None,
4701            channel: 0,
4702            epoch: 0,
4703            body,
4704            priority: Priority::Interactive,
4705            admission_class: AdmissionClass::Normal,
4706            deadline,
4707            retain_late_route_open,
4708            route_open_reverse_requests,
4709        })
4710        .await
4711    }
4712
4713    async fn describe_route_close_reasons(
4714        self: &Arc<Self>,
4715        deadline: Instant,
4716    ) -> Result<(), CallError> {
4717        let _lookup = timeout_at(deadline, self.route_description.lock())
4718            .await
4719            .map_err(|_| CallError::not_sent("deadline waiting for server.describe"))?;
4720        loop {
4721            self.ensure_connected_for_call(deadline).await?;
4722            let generation = {
4723                let inner = self.lock_inner();
4724                if inner.accepts_close_reasons.is_some() {
4725                    return Ok(());
4726                }
4727                inner.generation
4728            };
4729            // Description is advisory. A refused, malformed or unanswered lookup
4730            // must not prevent opening routes to a daemon that predates the key.
4731            let reply = self
4732                .send_request(RequestSend {
4733                    binary: false,
4734                    expected_handle: None,
4735                    channel: 0,
4736                    epoch: 0,
4737                    body: br#"{"op":"server.describe"}"#.to_vec(),
4738                    priority: Priority::Interactive,
4739                    admission_class: AdmissionClass::Normal,
4740                    deadline: deadline.min(Instant::now() + CAPABILITY_PROBE_TIMEOUT),
4741                    retain_late_route_open: false,
4742                    route_open_reverse_requests: None,
4743                })
4744                .await;
4745            let supported = match reply {
4746                Ok(TerminalFrame::Response { body, .. }) => {
4747                    matches!(serde_json::from_slice::<ClientControlResponse>(&body),
4748                        Ok(ClientControlResponse::ServerDescribe { capabilities, .. })
4749                        if capabilities.iter().any(|cap| cap == ROUTE_CLOSE_REASONS_CAPABILITY))
4750                }
4751                _ => false,
4752            };
4753            let mut inner = self.lock_inner();
4754            if inner.generation == generation {
4755                inner.accepts_close_reasons = Some(supported);
4756                return Ok(());
4757            }
4758        }
4759    }
4760
4761    async fn send_request(
4762        self: &Arc<Self>,
4763        request: RequestSend,
4764    ) -> Result<TerminalFrame, CallError> {
4765        self.send_request_cancellable(request, None).await
4766    }
4767
4768    fn allocate_request(
4769        self: &Arc<Self>,
4770        expected_handle: Option<RouteHandle>,
4771        channel: u16,
4772        epoch: u32,
4773    ) -> Result<(PendingKey, mpsc::Sender<WriteCommand>), CallError> {
4774        let mut inner = self.lock_inner();
4775        if inner.closed {
4776            return Err(CallError::not_sent("consumer closed"));
4777        }
4778        let generation = inner.generation;
4779        if let Some(expected) = expected_handle {
4780            let route_pair_matches =
4781                channel == 0 || (expected.channel == channel && expected.epoch == epoch);
4782            if expected.connection_token() != generation
4783                || !route_pair_matches
4784                || inner.route_epochs.get(&expected.channel) != Some(&expected)
4785                || inner.retired_routes.contains(&expected)
4786            {
4787                return Err(CallError::StaleRouteHandle(expected));
4788            }
4789        }
4790        let Some(writer) = inner.writer.clone() else {
4791            return Err(CallError::not_sent("subc connection is down before send"));
4792        };
4793        let Some(corr) = inner.next_corr else {
4794            drop(inner);
4795            self.handle_generation_drop(
4796                generation,
4797                "channel-0 correlation allocator exhausted".to_string(),
4798            );
4799            return Err(CallError::not_sent(
4800                "correlation allocator exhausted; connection closed",
4801            ));
4802        };
4803        inner.next_corr = corr.checked_add(1);
4804        Ok((
4805            PendingKey {
4806                generation,
4807                channel,
4808                epoch,
4809                corr,
4810            },
4811            writer,
4812        ))
4813    }
4814
4815    async fn send_request_cancellable(
4816        self: &Arc<Self>,
4817        request: RequestSend,
4818        cancel: Option<Arc<UnaryCancel>>,
4819    ) -> Result<TerminalFrame, CallError> {
4820        self.send_request_with_slot(request, cancel, None).await
4821    }
4822
4823    async fn send_request_with_slot(
4824        self: &Arc<Self>,
4825        request: RequestSend,
4826        cancel: Option<Arc<UnaryCancel>>,
4827        slot: Option<Arc<RoutePermit>>,
4828    ) -> Result<TerminalFrame, CallError> {
4829        let RequestSend {
4830            expected_handle,
4831            channel,
4832            epoch,
4833            body,
4834            binary,
4835            priority,
4836            admission_class,
4837            deadline,
4838            retain_late_route_open,
4839            route_open_reverse_requests,
4840        } = request;
4841        if Instant::now() >= deadline {
4842            return Err(CallError::not_sent(
4843                "call deadline elapsed before request was sent",
4844            ));
4845        }
4846        let slot = match (slot, expected_handle) {
4847            (Some(slot), _) => Some(slot),
4848            (None, Some(handle)) if channel != 0 => match self.route_state(handle) {
4849                Ok(route) if route.opted_in => {
4850                    Some(route.acquire(false, deadline, cancel.as_ref()).await?)
4851                }
4852                _ => None,
4853            },
4854            (None, _) => None,
4855        };
4856        let (key, writer) = self.allocate_request(expected_handle, channel, epoch)?;
4857        let generation = key.generation;
4858
4859        let mut frame = Frame::build(
4860            FrameType::Request,
4861            Flags::new(binary, priority, false).with_admission_class(admission_class),
4862            channel,
4863            epoch,
4864            key.corr,
4865            body,
4866        )
4867        .map_err(|err| CallError::not_sent(format!("failed to build request frame: {err}")))?;
4868        let (tx, rx) = oneshot::channel();
4869        {
4870            let mut inner = self.lock_inner();
4871            if inner.closed || inner.generation != generation || inner.writer.is_none() {
4872                return Err(CallError::not_sent(
4873                    "connection changed before request registration",
4874                ));
4875            }
4876            // Check the version retained for the authenticated connection under
4877            // the same lock as registration, so reconnecting cannot send a
4878            // rootless identity after a check on a different connection.
4879            if retain_late_route_open && !daemon_version_at_least(&inner.daemon_ver, (0, 39, 0)) {
4880                return Err(CallError::DaemonTooOld {
4881                    daemon_ver: inner.daemon_ver.clone(),
4882                });
4883            }
4884            if retain_late_route_open {
4885                let supported = inner.accepts_close_reasons.ok_or_else(|| {
4886                    CallError::not_sent("connection changed before route.open capability discovery")
4887                })?;
4888                let mut body: serde_json::Value = serde_json::from_slice(&frame.body)
4889                    .map_err(|err| CallError::not_sent(format!("invalid route.open: {err}")))?;
4890                RouteOpenRequestExt::new()
4891                    .with_accepts_close_reasons(supported.then(|| {
4892                        ACCEPTED_CLOSE_REASONS
4893                            .iter()
4894                            .map(|reason| (*reason).to_string())
4895                            .collect()
4896                    }))
4897                    .write_to(&mut body)
4898                    .map_err(|err| CallError::not_sent(format!("invalid route.open: {err}")))?;
4899                frame = Frame::build(
4900                    FrameType::Request,
4901                    frame.header.flags,
4902                    channel,
4903                    epoch,
4904                    key.corr,
4905                    serde_json::to_vec(&body)
4906                        .map_err(|err| CallError::not_sent(err.to_string()))?,
4907                )
4908                .map_err(|err| CallError::not_sent(err.to_string()))?;
4909            }
4910            if let Some(expected) = expected_handle {
4911                if inner.route_epochs.get(&expected.channel) != Some(&expected)
4912                    || inner.retired_routes.contains(&expected)
4913                {
4914                    return Err(CallError::StaleRouteHandle(expected));
4915                }
4916            }
4917            let expected_control_handle = (channel == 0 && !retain_late_route_open)
4918                .then_some(expected_handle)
4919                .flatten();
4920            inner.pending.insert(
4921                key,
4922                PendingEntry::unary(
4923                    tx,
4924                    retain_late_route_open,
4925                    expected_control_handle,
4926                    route_open_reverse_requests,
4927                ),
4928            );
4929            if let Some(slot) = slot.filter(|slot| slot.opted_in()) {
4930                inner.wire_slots.insert(key, slot);
4931            }
4932            if retain_late_route_open {
4933                inner.pending.get_mut(&key).unwrap().route_open_module =
4934                    serde_json::from_slice::<serde_json::Value>(&frame.body)
4935                        .ok()
4936                        .and_then(|body| {
4937                            body.get("target")?
4938                                .get("module_id")?
4939                                .as_str()
4940                                .map(str::to_string)
4941                        });
4942            }
4943        }
4944        let mut registration =
4945            PendingRegistration::new(Arc::clone(self), key, retain_late_route_open);
4946        registration.unary_cancel = cancel.clone();
4947
4948        match timeout_at(
4949            deadline,
4950            writer.send(WriteCommand {
4951                frame,
4952                pending: Some(key),
4953            }),
4954        )
4955        .await
4956        {
4957            Ok(Ok(())) => {}
4958            Ok(Err(_)) => {
4959                let accepted = registration.remove_pending().unwrap_or(false);
4960                return Err(classify_failure(
4961                    accepted,
4962                    "writer task closed before accepting request",
4963                    OutcomeUnknownCause::WriterClosed,
4964                ));
4965            }
4966            Err(_) => {
4967                let accepted = registration.remove_pending().unwrap_or(false);
4968                return Err(classify_failure_with_not_sent_cause(
4969                    accepted,
4970                    "call deadline elapsed waiting for writer capacity",
4971                    OutcomeUnknownCause::Deadline,
4972                    NotSentCause::WriterCapacity,
4973                ));
4974            }
4975        }
4976
4977        if let Some(cancel) = cancel {
4978            cancel.activate(key, priority, deadline);
4979            if cancel.requested() {
4980                cancel.cancel().await;
4981            }
4982        }
4983
4984        self.wait_for_reply(registration, rx, deadline).await
4985    }
4986
4987    async fn wait_for_reply(
4988        self: &Arc<Self>,
4989        mut registration: PendingRegistration,
4990        rx: oneshot::Receiver<PendingResult>,
4991        deadline: Instant,
4992    ) -> Result<TerminalFrame, CallError> {
4993        let key = registration.key;
4994        let channel = key.channel;
4995        // After writer handoff, settle_pending, a connection drop or close_sync may already
4996        // have removed the entry and still be settling it. Its absence cannot prove that the
4997        // request was not written, so a missing entry is classified as possibly written.
4998        tokio::select! {
4999            result = timeout_at(deadline, rx) => match result {
5000                Ok(Ok(result)) => {
5001                    registration.disarm();
5002                    result.into_call_result()
5003                }
5004                Ok(Err(_)) => {
5005                    // The entry was settled without a result, so the request may already
5006                    // have been written: report the outcome as unknown, never `NotSent`.
5007                    registration.disarm();
5008                    Err(CallError::outcome_unknown(
5009                        "pending response channel closed",
5010                        OutcomeUnknownCause::CompletionFailed,
5011                    ))
5012                }
5013                Err(_) => {
5014                    let accepted = if registration.retain_on_drop {
5015                        registration.disarm();
5016                        self.pending_accepted(key).unwrap_or(true)
5017                    } else {
5018                        registration.remove_pending().unwrap_or(true)
5019                    };
5020                    if accepted {
5021                        // Removing the pending entry prevents an explicit cancel
5022                        // from queueing afterward. If it won that race, its sent
5023                        // state is already visible and the deadline sends nothing.
5024                        let cancel_sent = registration.unary_cancel.as_ref().is_some_and(|cancel| cancel.sent());
5025                        if !cancel_sent && self.lock_inner().wire_slots.contains_key(&key) {
5026                            self.send_cancel(RouteHandle::new(key.channel, key.epoch, key.generation), key.corr, Priority::Interactive);
5027                        }
5028                        self.spawn_liveness_probe();
5029                    }
5030                    Err(classify_failure(
5031                        accepted,
5032                        format!("request on channel {channel} timed out at its deadline"),
5033                        OutcomeUnknownCause::Deadline,
5034                    ))
5035                }
5036            },
5037            () = self.close_token.cancelled() => {
5038                let accepted = registration.remove_pending().unwrap_or(true);
5039                Err(classify_failure(accepted, "consumer closed while request was pending", OutcomeUnknownCause::ConsumerClosed))
5040            }
5041        }
5042    }
5043
5044    /// Probe a connection retained after an accepted request reaches its reply deadline.
5045    ///
5046    /// Deadline timeouts deliberately keep a connection because scheduler pressure can delay
5047    /// an otherwise healthy reply. A channel-0 Ping plus any later inbound frame separates that
5048    /// case from a half-open socket, which would otherwise pin every subsequent request.
5049    fn spawn_liveness_probe(self: &Arc<Self>) {
5050        if self.liveness_probe_running.swap(true, Ordering::AcqRel) {
5051            return;
5052        }
5053
5054        let allocation = {
5055            let mut inner = self.lock_inner();
5056            // A pending CHANNEL-0 request suspends the probe: the daemon's
5057            // connection loop is FIFO and some channel-0 handlers park it
5058            // inline for seconds (route.open awaits the module bind ack for up
5059            // to route_bind_relay_timeout, ~12s in production), during which
5060            // our Ping sits unread in the daemon's socket buffer. Silence is
5061            // then explained by our own control op, and convicting would tear
5062            // down a healthy connection mid-bind. The gate is local knowledge
5063            // (we always know our own pendings) and re-arms on the next
5064            // deadline settle; the same check runs again before conviction.
5065            let control_pending = inner
5066                .pending
5067                .keys()
5068                .any(|key| key.generation == inner.generation && key.channel == 0);
5069            if inner.closed || control_pending || !matches!(&inner.reconnect, ReconnectState::Idle)
5070            {
5071                None
5072            } else {
5073                match (inner.next_corr, inner.writer.clone()) {
5074                    (Some(corr), Some(writer)) => {
5075                        inner.next_corr = corr.checked_add(1);
5076                        Some((inner.generation, corr, writer))
5077                    }
5078                    (None, _) | (_, None) => None,
5079                }
5080            }
5081        };
5082        let Some((generation, corr, writer)) = allocation else {
5083            self.liveness_probe_running.store(false, Ordering::Release);
5084            return;
5085        };
5086
5087        let t0 = epoch_millis();
5088        let ping = match Frame::build(
5089            FrameType::Ping,
5090            Flags::new(false, Priority::Interactive, false),
5091            0,
5092            0,
5093            corr,
5094            Vec::new(),
5095        ) {
5096            Ok(ping) => ping,
5097            Err(_) => {
5098                self.liveness_probe_running.store(false, Ordering::Release);
5099                return;
5100            }
5101        };
5102        let window = self.opts.liveness_probe_window;
5103        let shared = Arc::clone(self);
5104        tokio::spawn(async move {
5105            let window_end = Instant::now() + window;
5106            // A write failure proves nothing in the healthy direction: it may be the
5107            // first sign of the same broken transport. Let the inbound window decide.
5108            let _ = timeout_at(
5109                window_end,
5110                writer.send(WriteCommand {
5111                    frame: ping,
5112                    pending: None,
5113                }),
5114            )
5115            .await;
5116            sleep_until(window_end).await;
5117
5118            let control_pending_now = {
5119                let inner = shared.lock_inner();
5120                inner
5121                    .pending
5122                    .keys()
5123                    .any(|key| key.generation == generation && key.channel == 0)
5124            };
5125            if !shared.close_token.is_cancelled()
5126                && !control_pending_now // a control op begun during the window explains the silence
5127                && shared.generation_is_current(generation)
5128                && shared.last_inbound_ms.load(Ordering::Acquire) < t0
5129            {
5130                shared.handle_generation_drop(
5131                    generation,
5132                    format!(
5133                        "liveness probe convicted a half-open socket: no inbound frame for {}ms after a channel-0 Ping",
5134                        window.as_millis()
5135                    ),
5136                );
5137            }
5138            shared
5139                .liveness_probe_running
5140                .store(false, Ordering::Release);
5141        });
5142    }
5143
5144    async fn send_subscription(
5145        self: &Arc<Self>,
5146        subscription: SubscriptionSend,
5147    ) -> Result<Subscription, CallError> {
5148        let SubscriptionSend {
5149            expected_handle,
5150            channel,
5151            epoch,
5152            body,
5153            priority,
5154            admission_class,
5155            event_buffer,
5156            deadline,
5157            permit,
5158        } = subscription;
5159        if Instant::now() >= deadline {
5160            return Err(CallError::not_sent(
5161                "subscription deadline elapsed before request was sent",
5162            ));
5163        }
5164        let (generation, corr, writer) = {
5165            let mut inner = self.lock_inner();
5166            if inner.closed {
5167                return Err(CallError::not_sent("consumer closed"));
5168            }
5169            let generation = inner.generation;
5170            if let Some(expected) = expected_handle {
5171                if expected.connection_token() != generation
5172                    || expected.channel != channel
5173                    || expected.epoch != epoch
5174                    || inner.route_epochs.get(&channel) != Some(&expected)
5175                    || inner.retired_routes.contains(&expected)
5176                {
5177                    return Err(CallError::StaleRouteHandle(expected));
5178                }
5179            }
5180            let Some(writer) = inner.writer.clone() else {
5181                return Err(CallError::not_sent("subc connection is down before send"));
5182            };
5183            let Some(corr) = inner.next_corr else {
5184                drop(inner);
5185                self.handle_generation_drop(
5186                    generation,
5187                    "correlation allocator exhausted".to_string(),
5188                );
5189                return Err(CallError::not_sent(
5190                    "correlation allocator exhausted; connection closed",
5191                ));
5192            };
5193            inner.next_corr = corr.checked_add(1);
5194            (generation, corr, writer)
5195        };
5196
5197        // Mark held subscriptions so module drains leave them out of the quiescence wait.
5198        let frame = Frame::build(
5199            FrameType::Request,
5200            Flags(
5201                Flags::new(false, priority, false)
5202                    .with_admission_class(admission_class)
5203                    .0
5204                    | FLAG_SUBSCRIPTION,
5205            ),
5206            channel,
5207            epoch,
5208            corr,
5209            body,
5210        )
5211        .map_err(|err| CallError::not_sent(format!("failed to build request frame: {err}")))?;
5212        let key = PendingKey {
5213            generation,
5214            channel,
5215            epoch,
5216            corr,
5217        };
5218        let position = Arc::new(SubscriptionPosition {
5219            key: Mutex::new(key),
5220            stop: CancellationToken::new(),
5221        });
5222        let retry = permit.opted_in().then(|| SubscriptionRetry {
5223            frame: frame.clone(),
5224            deadline,
5225            delay: Duration::from_millis(25),
5226            position: Arc::clone(&position),
5227        });
5228        let (events_tx, events_rx) = mpsc::channel(event_buffer.max(1));
5229        let (closed_tx, closed_rx) = oneshot::channel();
5230        let (ended_tx, ended_rx) = watch::channel(None);
5231        {
5232            let mut inner = self.lock_inner();
5233            if inner.closed || inner.generation != generation || inner.writer.is_none() {
5234                return Err(CallError::not_sent(
5235                    "connection changed before subscription registration",
5236                ));
5237            }
5238            if let Some(expected) = expected_handle {
5239                if inner.route_epochs.get(&expected.channel) != Some(&expected)
5240                    || inner.retired_routes.contains(&expected)
5241                {
5242                    return Err(CallError::StaleRouteHandle(expected));
5243                }
5244            }
5245            if permit.opted_in() {
5246                inner.wire_slots.insert(key, Arc::clone(&permit));
5247            }
5248            let mut entry =
5249                PendingEntry::subscription(events_tx, closed_tx, ended_tx, permit, priority);
5250            entry.retry = retry;
5251            inner.pending.insert(key, entry);
5252        }
5253        let mut registration = PendingRegistration::new(Arc::clone(self), key, false);
5254
5255        match timeout_at(
5256            deadline,
5257            writer.send(WriteCommand {
5258                frame,
5259                pending: Some(key),
5260            }),
5261        )
5262        .await
5263        {
5264            Ok(Ok(())) => {}
5265            Ok(Err(_)) => {
5266                let accepted = registration.remove_pending().unwrap_or(false);
5267                return Err(classify_failure(
5268                    accepted,
5269                    "writer task closed before accepting subscription request",
5270                    OutcomeUnknownCause::WriterClosed,
5271                ));
5272            }
5273            Err(_) => {
5274                let accepted = registration.remove_pending().unwrap_or(false);
5275                return Err(classify_failure_with_not_sent_cause(
5276                    accepted,
5277                    "subscription deadline elapsed waiting for writer capacity",
5278                    OutcomeUnknownCause::Deadline,
5279                    NotSentCause::WriterCapacity,
5280                ));
5281            }
5282        }
5283
5284        registration.disarm();
5285        Ok(Subscription {
5286            events: events_rx,
5287            closed: SubscriptionClosed { rx: closed_rx },
5288            ended: ended_rx,
5289            cancel: SubscriptionCancel::new(Arc::clone(self), position, priority),
5290        })
5291    }
5292
5293    fn unsubscribe_subscription(
5294        &self,
5295        position: &SubscriptionPosition,
5296        priority: Priority,
5297    ) -> Result<(), CallError> {
5298        let key = *position.key.lock().unwrap_or_else(|err| err.into_inner());
5299        let handle = RouteHandle::new(key.channel, key.epoch, key.generation);
5300        self.validate_current_handle(handle)?;
5301        let (key, entry) = {
5302            let mut inner = self.lock_inner();
5303            let key = *position.key.lock().unwrap_or_else(|err| err.into_inner());
5304            position.stop.cancel();
5305            let entry = inner.pending.remove(&key);
5306            if entry.as_ref().is_some_and(|entry| !entry.accepted) {
5307                if let Some(slot) = inner.wire_slots.remove(&key) {
5308                    slot.release();
5309                }
5310            }
5311            // Keep retired-route ingress until its advisory Cancel is queued.
5312            (key, entry)
5313        };
5314        if let Some(entry) = entry {
5315            let should_cancel = entry.accepted || entry.retry.is_none();
5316            entry.settle_subscription_result(Ok(()));
5317            if should_cancel {
5318                self.send_cancel(handle, key.corr, priority);
5319            }
5320            self.lock_inner().reap_retired_route(handle);
5321        }
5322        Ok(())
5323    }
5324
5325    fn route_stream_data(&self, key: PendingKey, body: Vec<u8>) {
5326        let overflow = {
5327            let mut inner = self.lock_inner();
5328            let Some(entry) = inner.pending.get(&key) else {
5329                return;
5330            };
5331            match entry.try_send_stream_data(body) {
5332                Ok(()) | Err(StreamDataDelivery::NotSubscription) => return,
5333                Err(StreamDataDelivery::Full) => {
5334                    let priority = entry
5335                        .subscription_priority()
5336                        .unwrap_or(Priority::Interactive);
5337                    let entry = inner.pending.remove(&key);
5338                    entry.map(|entry| {
5339                        (
5340                            entry,
5341                            priority,
5342                            "subscription event channel filled; reader dropped the stream instead of blocking",
5343                        )
5344                    })
5345                }
5346                Err(StreamDataDelivery::Closed) => {
5347                    let priority = entry
5348                        .subscription_priority()
5349                        .unwrap_or(Priority::Interactive);
5350                    let entry = inner.pending.remove(&key);
5351                    entry.map(|entry| {
5352                        (
5353                            entry,
5354                            priority,
5355                            "subscription event receiver closed before the stream ended",
5356                        )
5357                    })
5358                }
5359            }
5360        };
5361
5362        if let Some((entry, priority, reason)) = overflow {
5363            entry.settle_call_error(CallError::subscription_backpressure(reason));
5364            self.send_cancel(
5365                RouteHandle::new(key.channel, key.epoch, key.generation),
5366                key.corr,
5367                priority,
5368            );
5369            self.lock_inner().reap_retired_route(RouteHandle::new(
5370                key.channel,
5371                key.epoch,
5372                key.generation,
5373            ));
5374        }
5375    }
5376
5377    fn register_push_events(
5378        &self,
5379        handle: RouteHandle,
5380    ) -> Result<mpsc::Receiver<PushEvent>, CallError> {
5381        let (events_tx, events_rx) = mpsc::channel(DEFAULT_PUSH_EVENT_BUFFER);
5382        let mut inner = self.lock_inner();
5383        if inner.closed
5384            || inner.generation != handle.connection_token()
5385            || inner.writer.is_none()
5386            || inner.route_epochs.get(&handle.channel) != Some(&handle)
5387        {
5388            return Err(CallError::StaleRouteHandle(handle));
5389        }
5390        inner.push_event_receivers.insert(handle, events_tx);
5391        Ok(events_rx)
5392    }
5393
5394    fn route_push(&self, handle: RouteHandle, body: Vec<u8>) {
5395        let should_count_drop = {
5396            let mut inner = self.lock_inner();
5397            if inner.closed
5398                || inner.generation != handle.connection_token()
5399                || inner.route_epochs.get(&handle.channel) != Some(&handle)
5400            {
5401                // Deliberately uncounted: a push against a stale epoch or dead
5402                // generation has no live subscriber by definition, and the
5403                // counters below claim delivery loss on LIVE routes only.
5404                return;
5405            }
5406            match inner.push_event_receivers.get(&handle) {
5407                None => DroppedPush::NoReceiver,
5408                Some(events) => match events.try_send(PushEvent { handle, body }) {
5409                    Ok(()) => DroppedPush::Delivered,
5410                    Err(mpsc::error::TrySendError::Closed(_)) => {
5411                        inner.push_event_receivers.remove(&handle);
5412                        DroppedPush::NoReceiver
5413                    }
5414                    // A burst KEEPS the subscription (issue #40). This used to
5415                    // remove the receiver -- documented as loss-signaling via
5416                    // recv()->None -- but the fleet's real push consumers are
5417                    // idempotent wake nudges, where one missed event costs a
5418                    // poll cycle and a lost subscription costs every later wake
5419                    // until a re-register path that history says is where bugs
5420                    // live. Matches control_push below; the drop is counted on
5421                    // its own counter so a too-slow consumer is diagnosable as
5422                    // such rather than filed under "never subscribed".
5423                    Err(mpsc::error::TrySendError::Full(_)) => DroppedPush::ReceiverFull,
5424                },
5425            }
5426        };
5427        match should_count_drop {
5428            DroppedPush::Delivered => {}
5429            DroppedPush::NoReceiver => {
5430                self.pushes_dropped_no_receiver
5431                    .fetch_add(1, Ordering::Relaxed);
5432            }
5433            DroppedPush::ReceiverFull => {
5434                self.pushes_dropped_receiver_full
5435                    .fetch_add(1, Ordering::Relaxed);
5436            }
5437        }
5438    }
5439
5440    /// Deliver a daemon-originated channel-0 control push to the registered
5441    /// consumer receiver, or count the drop. Never blocks the reader.
5442    fn control_push(&self, body: &[u8]) {
5443        let parsed = serde_json::from_slice::<serde_json::Value>(body)
5444            .ok()
5445            .and_then(|value| {
5446                let op = value.get("op")?.as_str()?.to_string();
5447                Some(ControlPush { op, body: value })
5448            });
5449        let delivered = match parsed {
5450            None => false,
5451            Some(push) => {
5452                let mut inner = self.lock_inner();
5453                inner.record_route_end(&push);
5454                match inner.control_push_receiver.as_ref() {
5455                    None => false,
5456                    Some(sender) => match sender.try_send(push) {
5457                        Ok(()) => true,
5458                        Err(mpsc::error::TrySendError::Closed(_)) => {
5459                            inner.control_push_receiver = None;
5460                            false
5461                        }
5462                        Err(mpsc::error::TrySendError::Full(_)) => false,
5463                    },
5464                }
5465            }
5466        };
5467        if !delivered {
5468            self.control_pushes_dropped.fetch_add(1, Ordering::Relaxed);
5469        }
5470    }
5471
5472    fn send_cancel(&self, handle: RouteHandle, corr: u64, priority: Priority) {
5473        let writer = {
5474            let inner = self.lock_inner();
5475            if inner.closed
5476                || inner.generation != handle.connection_token()
5477                || !route_is_installed(&inner, handle)
5478            {
5479                return;
5480            }
5481            inner.writer.clone()
5482        };
5483        let Some(writer) = writer else {
5484            return;
5485        };
5486        let Ok(frame) = Frame::build(
5487            FrameType::Cancel,
5488            Flags::new(false, priority, false),
5489            handle.channel,
5490            handle.epoch,
5491            corr,
5492            Vec::new(),
5493        ) else {
5494            return;
5495        };
5496        let _ = writer.try_send(WriteCommand {
5497            frame,
5498            pending: None,
5499        });
5500    }
5501
5502    fn mark_pending_accepted(&self, key: PendingKey) -> bool {
5503        let mut inner = self.lock_inner();
5504        if inner.closed || inner.generation != key.generation {
5505            return false;
5506        }
5507        let Some(entry) = inner.pending.get_mut(&key) else {
5508            return false;
5509        };
5510        if entry
5511            .send_deadline
5512            .is_some_and(|deadline| Instant::now() >= deadline)
5513        {
5514            let entry = inner.remove_pending(&key).unwrap();
5515            drop(inner);
5516            entry.settle_call_error(CallError::not_sent_with_cause(
5517                "call deadline elapsed before request was sent",
5518                NotSentCause::WriterRejected,
5519            ));
5520            return false;
5521        }
5522        entry.accepted = true;
5523        true
5524    }
5525
5526    fn settle_pending(self: &Arc<Self>, key: PendingKey, terminal: PendingTerminal) {
5527        let (entry, retry) = {
5528            let mut inner = self.lock_inner();
5529            let entry = inner.remove_pending(&key);
5530            let slot = inner.wire_slots.remove(&key);
5531            let busy = matches!(&terminal, PendingTerminal::Error { body, flags }
5532                if error_codes::is_route_busy_retryable(*flags, &body.code, slot.as_ref().is_some_and(|slot| slot.opted_in())))
5533                && entry
5534                    .as_ref()
5535                    .is_some_and(|entry| !entry.completion_is_closed());
5536            if let Some(slot) = slot {
5537                if !busy {
5538                    slot.release();
5539                }
5540            }
5541            if busy && entry.as_ref().is_some_and(|entry| entry.retry.is_some()) {
5542                let mut entry = entry.unwrap();
5543                entry.accepted = false;
5544                let retry = entry.retry.clone();
5545                inner.pending.insert(key, entry);
5546                (None, retry)
5547            } else {
5548                inner.reap_retired_route(RouteHandle::new(key.channel, key.epoch, key.generation));
5549                (entry, None)
5550            }
5551        };
5552        if let Some(retry) = retry {
5553            let shared = Arc::clone(self);
5554            tokio::spawn(async move {
5555                shared.retry_subscription(key, retry, terminal).await;
5556            });
5557            return;
5558        }
5559        let Some(entry) = entry else {
5560            return;
5561        };
5562        if entry.retain_late_route_open && entry.completion_is_closed() {
5563            if let PendingTerminal::Response {
5564                generation, body, ..
5565            } = &terminal
5566            {
5567                if let Ok(ClientControlResponse::RouteOpen {
5568                    route_channel,
5569                    route_epoch,
5570                    ..
5571                }) = serde_json::from_slice::<ClientControlResponse>(body)
5572                {
5573                    let handle = RouteHandle::new(route_channel, route_epoch, *generation);
5574                    self.send_route_goodbye(handle, true);
5575                    self.uninstall_route_handle(handle);
5576                }
5577            }
5578            return;
5579        }
5580        entry.settle_terminal(key, terminal);
5581    }
5582
5583    fn pending_accepted(&self, key: PendingKey) -> Option<bool> {
5584        self.lock_inner()
5585            .pending
5586            .get(&key)
5587            .map(|entry| entry.accepted)
5588    }
5589
5590    fn handle_generation_drop(self: &Arc<Self>, generation: u64, reason: String) {
5591        self.handle_generation_drop_with_cause(
5592            generation,
5593            reason,
5594            OutcomeUnknownCause::ConnectionFailed,
5595        );
5596    }
5597
5598    fn handle_generation_drop_with_cause(
5599        self: &Arc<Self>,
5600        generation: u64,
5601        reason: String,
5602        cause: OutcomeUnknownCause,
5603    ) {
5604        let (should_emit, pending, callbacks) = {
5605            let mut inner = self.lock_inner();
5606            if inner.closed || inner.generation != generation || inner.writer.is_none() {
5607                return;
5608            }
5609            inner.writer = None;
5610            inner.restored_token = inner.restored_token.saturating_add(1);
5611            inner.close_routes();
5612            inner.route_epochs.clear();
5613            inner.route_modules.clear();
5614            inner.route_end_reasons.clear();
5615            inner.legacy_channel_reasons.clear();
5616            let pending = drain_pending_generation(&mut inner.pending, generation);
5617            // An opening belongs to its lead caller, not to a socket generation:
5618            // the caller may still be retrying after this transport is replaced.
5619            // Keep its waiters and close flag until its OpeningGuard finishes, so
5620            // a new caller cannot start a competing open for the same key.
5621            let callbacks = inner.callbacks.clone();
5622            (true, pending, callbacks)
5623        };
5624
5625        if should_emit {
5626            settle_route_pending_entries_with_cause(
5627                pending,
5628                reason.clone(),
5629                RouteEndReason::ConnectionLost,
5630                cause,
5631            );
5632            emit_callbacks(callbacks, ConnectionState::Dropped);
5633            self.notify.notify_waiters();
5634            let _ = self.spawn_reconnect(generation);
5635        }
5636    }
5637
5638    fn close_sync(&self, reason: &str) {
5639        let (pending, openings, routes, reader, writer, reconnect) = {
5640            let mut inner = self.lock_inner();
5641            if inner.closed {
5642                return;
5643            }
5644            inner.closed = true;
5645            // Disconnect releases every daemon route, including retirements
5646            // whose GOODBYEs are still waiting for writer capacity. Preserve
5647            // the best-effort shutdown send for retirements not yet reaped.
5648            let retirements = inner
5649                .retirement_goodbyes
5650                .iter()
5651                .copied()
5652                .collect::<Vec<_>>();
5653            for handle in retirements {
5654                inner.queue_retirement_goodbye(handle);
5655            }
5656            inner.writer = None;
5657            inner.route_epochs.clear();
5658            inner.route_modules.clear();
5659            inner.route_end_reasons.clear();
5660            inner.legacy_channel_reasons.clear();
5661            inner.push_event_receivers.clear();
5662            self.close_token.cancel();
5663            let reconnect = match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
5664                ReconnectState::Background { task, .. } => Some(task),
5665                ReconnectState::Idle | ReconnectState::Inline { .. } => None,
5666            };
5667            (
5668                inner
5669                    .pending
5670                    .drain()
5671                    .map(|(_, entry)| entry)
5672                    .collect::<Vec<_>>(),
5673                inner
5674                    .openings
5675                    .drain()
5676                    .map(|(_, opening)| opening.waiters)
5677                    .collect::<Vec<_>>(),
5678                inner.drain_routes(),
5679                inner.reader_task.take(),
5680                inner.writer_task.take(),
5681                reconnect,
5682            )
5683        };
5684        for route in routes {
5685            route.close();
5686        }
5687        if let Some(handle) = reader {
5688            handle.abort();
5689        }
5690        if let Some(mut handle) = writer {
5691            // Let already queued GOODBYEs reach the socket, but never leave
5692            // a writer blocked on an unresponsive peer alive after close.
5693            if let Ok(runtime) = tokio::runtime::Handle::try_current() {
5694                runtime.spawn(async move {
5695                    if tokio::time::timeout(Duration::from_millis(250), &mut handle)
5696                        .await
5697                        .is_err()
5698                    {
5699                        handle.abort();
5700                    }
5701                });
5702            } else {
5703                handle.abort();
5704            }
5705        }
5706        if let Some(handle) = reconnect {
5707            handle.abort();
5708        }
5709        settle_pending_entries(pending, reason.to_string());
5710        fail_openings(openings, SharedCallFailure::not_sent(reason.to_string()));
5711        self.notify.notify_waiters();
5712    }
5713
5714    fn validate_current_handle(&self, handle: RouteHandle) -> Result<(), CallError> {
5715        let inner = self.lock_inner();
5716        if inner.closed
5717            || inner.generation != handle.connection_token()
5718            || inner.writer.is_none()
5719            || !route_is_installed(&inner, handle)
5720        {
5721            Err(CallError::StaleRouteHandle(handle))
5722        } else {
5723            Ok(())
5724        }
5725    }
5726
5727    fn route_state(&self, handle: RouteHandle) -> Result<RouteState, CallError> {
5728        let inner = self.lock_inner();
5729        if inner.closed
5730            || inner.generation != handle.connection_token()
5731            || inner.writer.is_none()
5732            || inner.route_epochs.get(&handle.channel) != Some(&handle)
5733        {
5734            return Err(CallError::StaleRouteHandle(handle));
5735        }
5736
5737        let route = inner
5738            .route_by_channel
5739            .get(&handle.channel)
5740            .and_then(|key| inner.routes.get(key))
5741            .or_else(|| inner.one_shot_routes.get(&handle.channel));
5742        debug_assert!(route.is_none_or(|route| route.handle == handle));
5743        route
5744            .filter(|route| route.handle == handle)
5745            .cloned()
5746            .ok_or(CallError::StaleRouteHandle(handle))
5747    }
5748
5749    fn route_is_current(&self, key: &RouteKey, route: &RouteState) -> bool {
5750        let inner = self.lock_inner();
5751        if inner.closed
5752            || inner.generation != route.handle.connection_token()
5753            || inner.writer.is_none()
5754        {
5755            return false;
5756        }
5757        inner.routes.get(key).is_some_and(|cached| {
5758            cached.handle == route.handle && Arc::ptr_eq(&cached.sem, &route.sem)
5759        })
5760    }
5761
5762    fn invalidate_route(&self, key: &RouteKey, expected_handle: Option<RouteHandle>) {
5763        self.invalidate_route_with_deadline(key, expected_handle, false);
5764    }
5765
5766    /// An accepted call's response deadline cannot prove non-delivery, so it
5767    /// must not trigger a resend. Retiring its route instead lets the next call
5768    /// recover even when the connection-wide Ping still succeeds. A module that
5769    /// is merely slower than the deadline makes the next call open a fresh
5770    /// route. Calls already pending on the retired route still receive their
5771    /// replies until they settle.
5772    fn invalidate_route_with_deadline(
5773        &self,
5774        key: &RouteKey,
5775        expected_handle: Option<RouteHandle>,
5776        response_deadline_expired: bool,
5777    ) {
5778        let removed = {
5779            let mut inner = self.lock_inner();
5780            match inner.routes.get(key) {
5781                Some(route) if expected_handle.is_none_or(|expected| expected == route.handle) => {
5782                    let removed = inner.evict_route(key);
5783                    if let Some(route) = &removed {
5784                        // Eviction stops new calls, but siblings may already be
5785                        // executing or awaiting their own refusal. Keep ingress
5786                        // until those pending entries settle; never resend them
5787                        // merely because another call was refused.
5788                        inner.retired_routes.insert(route.handle);
5789                        if response_deadline_expired {
5790                            inner.retirement_goodbyes.insert(route.handle);
5791                            // Closing this route releases slots retained for outstanding calls.
5792                            // A module that never answers must not block the route's GOODBYE.
5793                            inner.release_wire_slots(route.handle);
5794                            let pending_calls = inner
5795                                .pending
5796                                .keys()
5797                                .filter(|pending| {
5798                                    pending.generation == route.handle.connection_token()
5799                                        && pending.channel == route.handle.channel
5800                                        && pending.epoch == route.handle.epoch
5801                                })
5802                                .count();
5803                            tracing::warn!(
5804                                target_module = %key.target_label(),
5805                                channel = route.handle.channel,
5806                                epoch = route.handle.epoch,
5807                                pending_calls,
5808                                "retiring route after call response deadline"
5809                            );
5810                        }
5811                        inner.reap_retired_route(route.handle);
5812                    }
5813                    removed
5814                }
5815                _ => None,
5816            }
5817        };
5818        if let Some(route) = removed {
5819            route.close();
5820        }
5821    }
5822
5823    fn finish_opening(&self, key: &RouteKey, result: Result<RouteState, SharedCallFailure>) {
5824        let opening = self.lock_inner().openings.remove(key);
5825        for waiter in opening.map(|o| o.waiters).unwrap_or_default() {
5826            let _ = waiter.send(result.clone());
5827        }
5828    }
5829
5830    async fn close_handle(
5831        self: &Arc<Self>,
5832        handle: RouteHandle,
5833        opts: &CloseRouteOptions,
5834    ) -> Result<(), CallError> {
5835        self.validate_current_handle(handle)?;
5836        let route = {
5837            let mut inner = self.lock_inner();
5838            inner.route_end_reasons.insert(
5839                handle.channel,
5840                (RouteEndReason::ClosedByCaller.into(), true),
5841            );
5842            inner.remove_route_by_handle(handle)
5843        };
5844        let mut closing = RouteCloseGuard::new(
5845            Arc::clone(self),
5846            handle,
5847            route,
5848            "route closed by close_handle",
5849        );
5850        if opts.drain {
5851            self.drain_channel(handle, opts.drain_timeout).await;
5852        }
5853        closing.close_pending();
5854        self.queue_route_goodbye(handle).await;
5855        closing.finish();
5856        Ok(())
5857    }
5858
5859    /// Tear down one route by key. See [`SubcConsumer::close_route`].
5860    async fn close_route(self: &Arc<Self>, key: &RouteKey, opts: &CloseRouteOptions) {
5861        // Under the lock: flip the close-beats-reopen flag on any in-flight open for
5862        // this key (so a lead-opener whose channel hasn't been cached yet refuses to
5863        // install it), and remove the cached route if one exists.
5864        let route = {
5865            let mut inner = self.lock_inner();
5866            if let Some(opening) = inner.openings.get_mut(key) {
5867                opening.closed = true;
5868            }
5869            let route = inner.remove_route(key);
5870            if let Some(route) = &route {
5871                inner.route_end_reasons.insert(
5872                    route.handle.channel,
5873                    (RouteEndReason::ClosedByCaller.into(), true),
5874                );
5875            }
5876            route
5877        };
5878
5879        // Nothing cached: either never opened (idempotent no-op) or still opening (the
5880        // racing lead-opener will see the flag and GOODBYE whatever channel it opens).
5881        let Some(route) = route else {
5882            return;
5883        };
5884        let handle = route.handle;
5885        let mut closing = RouteCloseGuard::new(
5886            Arc::clone(self),
5887            handle,
5888            Some(route),
5889            "route closed by close_route",
5890        );
5891
5892        if opts.drain {
5893            // Wait for in-flight UNARY requests on this channel to settle naturally,
5894            // bounded by drain_timeout, before tearing the route down.
5895            self.drain_channel(handle, opts.drain_timeout).await;
5896        }
5897
5898        // Closing the semaphore makes any not-yet-sent acquire() return Err -> the
5899        // caller classifies it NotSent. Already-sent pending requests are settled
5900        // at-most-once (OutcomeUnknown if the writer accepted their bytes).
5901        closing.close_pending();
5902
5903        // Fail pending requests and release their slots before waiting for the
5904        // writer. Keep the ingress handle installed until GOODBYE is queued,
5905        // preventing channel reuse from overtaking the old route's teardown.
5906        self.queue_route_goodbye(handle).await;
5907        closing.finish();
5908    }
5909
5910    fn uninstall_route_handle(&self, handle: RouteHandle) {
5911        let mut inner = self.lock_inner();
5912        inner.release_wire_slots(handle);
5913        inner.retired_routes.remove(&handle);
5914        inner.retirement_goodbyes.remove(&handle);
5915        if inner.route_epochs.get(&handle.channel) == Some(&handle) {
5916            let installed = inner.route_epochs.remove(&handle.channel).unwrap();
5917            inner.route_targets.remove(&handle);
5918            inner.push_event_receivers.remove(&handle);
5919            release_reverse_request_registry(installed);
5920        }
5921    }
5922
5923    fn route_not_sent_error(&self, handle: RouteHandle) -> CallError {
5924        let inner = self.lock_inner();
5925        let reason = if inner.generation != handle.connection_token() || inner.writer.is_none() {
5926            RouteEndReason::ConnectionLost.into()
5927        } else {
5928            inner.route_end(handle.channel)
5929        };
5930        CallError::NotSent(Box::new(NotSentSource {
5931            message: "route flow-control semaphore closed".into(),
5932            cause: NotSentCause::BeforeQueue,
5933            never_forwarded: true,
5934            route_reason: Some(reason),
5935            refusal: None,
5936        }))
5937    }
5938
5939    /// Settle every pending request on this handle as OutcomeUnknown if the writer
5940    /// accepted its bytes, or NotSent otherwise, preserving the route ending cause.
5941    fn fail_channel_pending(
5942        &self,
5943        handle: RouteHandle,
5944        reason: &str,
5945        close_reason: RouteEndReason,
5946    ) {
5947        let entries = {
5948            let mut inner = self.lock_inner();
5949            inner.release_wire_slots(handle);
5950            inner
5951                .route_end_reasons
5952                .insert(handle.channel, (close_reason.clone().into(), true));
5953            drain_pending_handle(&mut inner.pending, handle, true)
5954        };
5955        settle_route_pending_entries(entries, reason.to_string(), close_reason);
5956    }
5957
5958    /// Resolve once every in-flight unary pending on `channel` has settled, or the
5959    /// timeout elapses. Polls the pending map (entries are removed on settle); the
5960    /// volume here is tiny (a route window is small) so a short poll is adequate.
5961    async fn drain_channel(&self, handle: RouteHandle, timeout: Duration) {
5962        let deadline = Instant::now() + timeout;
5963        loop {
5964            let has_inflight = {
5965                let inner = self.lock_inner();
5966                inner.pending.iter().any(|(key, entry)| {
5967                    key.generation == handle.connection_token()
5968                        && key.channel == handle.channel
5969                        && key.epoch == handle.epoch
5970                        && !entry.is_subscription()
5971                })
5972            };
5973            if !has_inflight || Instant::now() >= deadline {
5974                return;
5975            }
5976            sleep(Duration::from_millis(5)).await;
5977        }
5978    }
5979
5980    async fn queue_route_goodbye(self: &Arc<Self>, handle: RouteHandle) {
5981        let frame = Frame::build(
5982            FrameType::Goodbye,
5983            Flags::new(false, Priority::Interactive, false),
5984            handle.channel,
5985            handle.epoch,
5986            0,
5987            Vec::new(),
5988        )
5989        .expect("header-only route GOODBYE is valid");
5990        loop {
5991            let changed = self.notify.notified();
5992            tokio::pin!(changed);
5993            changed.as_mut().enable();
5994            let writer = {
5995                let inner = self.lock_inner();
5996                // A missing writer or changed generation means the connection
5997                // is dead: the daemon releases every route on that connection,
5998                // so no GOODBYE is needed. A removed handle was already closed.
5999                if inner.closed
6000                    || inner.generation != handle.connection_token()
6001                    || inner.route_epochs.get(&handle.channel) != Some(&handle)
6002                {
6003                    return;
6004                }
6005                let Some(writer) = inner.writer.clone() else {
6006                    return;
6007                };
6008                writer
6009            };
6010            // Request deadlines bound other awaited writes, but there is no
6011            // writer-stall timeout: a live connection must admit this teardown
6012            // before its caller can release route budget.
6013            tokio::select! {
6014                result = writer.reserve() => {
6015                    let Ok(permit) = result else {
6016                        self.handle_generation_drop(
6017                            handle.connection_token(),
6018                            "writer closed before route GOODBYE".into(),
6019                        );
6020                        return;
6021                    };
6022                    let inner = self.lock_inner();
6023                    if !inner.closed
6024                        && inner.generation == handle.connection_token()
6025                        && inner.writer.as_ref().is_some_and(|current| current.same_channel(&writer))
6026                        && inner.route_epochs.get(&handle.channel) == Some(&handle)
6027                    {
6028                        permit.send(WriteCommand { frame, pending: None });
6029                    }
6030                    return;
6031                }
6032                _ = &mut changed => {}
6033                _ = self.close_token.cancelled() => return,
6034            }
6035        }
6036    }
6037
6038    /// Queue a header-only route GOODBYE if `handle` is still live on this connection.
6039    /// Late successful route.open cleanup sets `close_on_failure`: orphan prevention then
6040    /// requires closing the connection when the GOODBYE cannot enter the writer queue.
6041    fn send_route_goodbye(self: &Arc<Self>, handle: RouteHandle, close_on_failure: bool) -> bool {
6042        let writer = {
6043            let inner = self.lock_inner();
6044            if inner.closed
6045                || inner.generation != handle.connection_token()
6046                || inner.route_epochs.get(&handle.channel) != Some(&handle)
6047            {
6048                return false;
6049            }
6050            inner.writer.clone()
6051        };
6052        let Some(writer) = writer else {
6053            return false;
6054        };
6055        let Ok(frame) = Frame::build(
6056            FrameType::Goodbye,
6057            Flags::new(false, Priority::Interactive, false),
6058            handle.channel,
6059            handle.epoch,
6060            0,
6061            Vec::new(),
6062        ) else {
6063            return false;
6064        };
6065        if writer
6066            .try_send(WriteCommand {
6067                frame,
6068                pending: None,
6069            })
6070            .is_ok()
6071        {
6072            return true;
6073        }
6074        if close_on_failure {
6075            self.handle_generation_drop(
6076                handle.connection_token(),
6077                "failed to queue late route.open cleanup GOODBYE".to_string(),
6078            );
6079        }
6080        false
6081    }
6082
6083    fn emit_connection_state(&self, state: ConnectionState) {
6084        let callbacks = self.lock_inner().callbacks.clone();
6085        emit_callbacks(callbacks, state);
6086    }
6087}
6088
6089#[derive(Clone, Copy)]
6090enum InstallKind {
6091    Initial,
6092    Reconnect,
6093}
6094
6095enum EnsureAction {
6096    Wait,
6097    Lead {
6098        generation: u64,
6099        stale_task: Option<JoinHandle<()>>,
6100    },
6101}
6102
6103/// The reconnect state is fenced by the generation whose transport failed. A
6104/// newer generation can replace an older attempt, and completion only changes
6105/// the state when its generation still owns the slot.
6106enum ReconnectState {
6107    Idle,
6108    Inline {
6109        generation: u64,
6110    },
6111    Background {
6112        generation: u64,
6113        task: JoinHandle<()>,
6114    },
6115}
6116
6117/// Outcome of the install decision after a route.open response arrives, taken under
6118/// the inner lock so a racing close_route is observed atomically.
6119enum RouteInstall {
6120    /// Install (or reuse) the cached route and return it.
6121    Cached(RouteState),
6122    /// Do not install. `closed` => a close_route won the race (GOODBYE + NotSent);
6123    /// otherwise the generation moved (retry the open).
6124    Discard { closed: bool },
6125}
6126
6127enum RouteOpenAction {
6128    Wait(oneshot::Receiver<Result<RouteState, SharedCallFailure>>),
6129    Lead,
6130}
6131
6132struct RouteOpenParams<'a> {
6133    target: &'a RouteTarget,
6134    identity: &'a BindIdentity,
6135    consumer_identity: &'a Option<ConsumerIdentity>,
6136    consumer_capabilities: &'a Option<Vec<String>>,
6137    /// Already normalized: an empty map is `None` here, as in the route key.
6138    role_versions: &'a Option<BTreeMap<String, String>>,
6139    reverse_requests: &'a ReverseRequestRegistry,
6140    /// The scope every route.open for this key asks to be admitted under, so a
6141    /// reopen after the route drops carries the same selector as the first open.
6142    scope: Option<&'a ScopeSelector>,
6143}
6144
6145struct CallAttemptHistory {
6146    never_forwarded: bool,
6147    sent: bool,
6148}
6149
6150struct RequestSend {
6151    expected_handle: Option<RouteHandle>,
6152    channel: u16,
6153    epoch: u32,
6154    body: Vec<u8>,
6155    binary: bool,
6156    priority: Priority,
6157    admission_class: AdmissionClass,
6158    deadline: Instant,
6159    retain_late_route_open: bool,
6160    route_open_reverse_requests: Option<ReverseRequestRegistry>,
6161}
6162
6163struct SubscriptionSend {
6164    expected_handle: Option<RouteHandle>,
6165    channel: u16,
6166    epoch: u32,
6167    body: Vec<u8>,
6168    priority: Priority,
6169    admission_class: AdmissionClass,
6170    event_buffer: usize,
6171    deadline: Instant,
6172    permit: Arc<RoutePermit>,
6173}
6174
6175struct SubscriptionPosition {
6176    key: Mutex<PendingKey>,
6177    stop: CancellationToken,
6178}
6179
6180#[derive(Clone)]
6181struct SubscriptionRetry {
6182    frame: Frame,
6183    deadline: Instant,
6184    delay: Duration,
6185    position: Arc<SubscriptionPosition>,
6186}
6187
6188struct RouteCloseGuard {
6189    shared: Arc<Shared>,
6190    handle: RouteHandle,
6191    route: Option<RouteState>,
6192    reason: &'static str,
6193    finished: bool,
6194}
6195
6196impl RouteCloseGuard {
6197    fn new(
6198        shared: Arc<Shared>,
6199        handle: RouteHandle,
6200        route: Option<RouteState>,
6201        reason: &'static str,
6202    ) -> Self {
6203        Self {
6204            shared,
6205            handle,
6206            route,
6207            reason,
6208            finished: false,
6209        }
6210    }
6211
6212    fn close_pending(&self) {
6213        if let Some(route) = &self.route {
6214            route.close();
6215        }
6216        self.shared
6217            .fail_channel_pending(self.handle, self.reason, RouteEndReason::ClosedByCaller);
6218    }
6219
6220    fn finish(&mut self) {
6221        self.shared.uninstall_route_handle(self.handle);
6222        self.finished = true;
6223    }
6224}
6225
6226impl Drop for RouteCloseGuard {
6227    fn drop(&mut self) {
6228        if self.finished {
6229            return;
6230        }
6231        // An abandoned drain must not leave requests or their in-flight permits
6232        // waiting on the caller. Retirement owns GOODBYE admission once the close is dropped.
6233        self.close_pending();
6234        let mut inner = self.shared.lock_inner();
6235        if inner.closed
6236            || inner.generation != self.handle.connection_token()
6237            || inner.writer.is_none()
6238            || inner.route_epochs.get(&self.handle.channel) != Some(&self.handle)
6239        {
6240            return;
6241        }
6242        inner.retired_routes.insert(self.handle);
6243        inner.retirement_goodbyes.insert(self.handle);
6244        // Reaping tries synchronous admission first; otherwise the connection's
6245        // FIFO flusher keeps the handle installed until its GOODBYE is queued.
6246        inner.reap_retired_route(self.handle);
6247    }
6248}
6249
6250struct OpeningGuard {
6251    shared: Arc<Shared>,
6252    key: RouteKey,
6253    finished: bool,
6254}
6255
6256impl OpeningGuard {
6257    fn new(shared: Arc<Shared>, key: RouteKey) -> Self {
6258        Self {
6259            shared,
6260            key,
6261            finished: false,
6262        }
6263    }
6264
6265    fn finish(&mut self, result: Result<RouteState, SharedCallFailure>) {
6266        self.shared.finish_opening(&self.key, result);
6267        self.finished = true;
6268    }
6269}
6270
6271impl Drop for OpeningGuard {
6272    fn drop(&mut self) {
6273        if !self.finished {
6274            self.shared.finish_opening(
6275                &self.key,
6276                Err(SharedCallFailure::not_sent(
6277                    "route.open future was cancelled",
6278                )),
6279            );
6280        }
6281    }
6282}
6283
6284struct InlineReconnectGuard {
6285    shared: Arc<Shared>,
6286    generation: u64,
6287    finished: bool,
6288}
6289
6290impl InlineReconnectGuard {
6291    fn new(shared: Arc<Shared>, generation: u64) -> Self {
6292        Self {
6293            shared,
6294            generation,
6295            finished: false,
6296        }
6297    }
6298
6299    fn finish(&mut self) {
6300        self.shared.finish_inline_reconnect(self.generation);
6301        self.finished = true;
6302    }
6303}
6304
6305impl Drop for InlineReconnectGuard {
6306    fn drop(&mut self) {
6307        if !self.finished {
6308            self.shared.finish_inline_reconnect(self.generation);
6309        }
6310    }
6311}
6312
6313#[derive(Clone)]
6314struct RouteState {
6315    handle: RouteHandle,
6316    sem: Arc<Semaphore>,
6317    watch_sem: Option<Arc<Semaphore>>,
6318    opted_in: bool,
6319}
6320
6321#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6322struct RouteKey {
6323    target: RouteTargetKey,
6324    harness: String,
6325    session: String,
6326    consumer_identity: Option<ConsumerIdentityKey>,
6327    consumer_capabilities: Option<ConsumerCapabilitiesKey>,
6328    /// The role versions the route was opened with; `None` for a route that
6329    /// declared none. Part of the key so a legacy route and a versioned one to
6330    /// the same target are never shared: the provider chose its wire shape
6331    /// from these at bind. A `BTreeMap` is already in canonical order.
6332    role_versions: Option<BTreeMap<String, String>>,
6333    /// The scope the route was admitted under; `None` for an unscoped route.
6334    /// Part of the key so a route bound to one session's scope (or one epoch
6335    /// of it) is never reused for another, nor for an unscoped caller.
6336    scope: Option<ScopeKey>,
6337}
6338
6339impl RouteKey {
6340    fn new(
6341        target: &RouteTarget,
6342        identity: &BindIdentity,
6343        consumer_identity: Option<&ConsumerIdentity>,
6344        consumer_capabilities: Option<&[String]>,
6345    ) -> Self {
6346        Self {
6347            target: RouteTargetKey::from(target),
6348            harness: identity.harness.clone(),
6349            session: identity.session.clone(),
6350            consumer_identity: consumer_identity.map(ConsumerIdentityKey::from),
6351            consumer_capabilities: consumer_capabilities.map(ConsumerCapabilitiesKey::from_slice),
6352            role_versions: None,
6353            scope: None,
6354        }
6355    }
6356
6357    fn with_role_versions(mut self, role_versions: Option<&BTreeMap<String, String>>) -> Self {
6358        self.role_versions = role_versions.cloned();
6359        self
6360    }
6361
6362    fn with_scope(mut self, scope: Option<&ScopeSelector>) -> Self {
6363        self.scope = scope.map(ScopeKey::from);
6364        self
6365    }
6366
6367    fn target_label(&self) -> String {
6368        match &self.target {
6369            RouteTargetKey::ToolProvider { module_id } => format!("tool_provider:{module_id}"),
6370            RouteTargetKey::ManagementSurface { module_id } => {
6371                format!("management_surface:{module_id}")
6372            }
6373            RouteTargetKey::InternalService {
6374                module_id,
6375                service_id,
6376            } => format!("internal_service:{module_id}:{service_id}"),
6377        }
6378    }
6379}
6380
6381#[derive(Clone, Hash, PartialEq, Eq)]
6382struct ConsumerIdentityKey {
6383    module_id: String,
6384    launch_nonce: String,
6385}
6386
6387// Hand-written so the launch nonce is never printed. The nonce is the credential
6388// that attributes a connection to a supervised module, and a derived Debug would
6389// write it into any log line or panic message that formats this value. This key sits
6390// inside the route cache key, which is formatted in logs.
6391impl fmt::Debug for ConsumerIdentityKey {
6392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6393        f.debug_struct("ConsumerIdentityKey")
6394            .field("module_id", &self.module_id)
6395            .field(
6396                "launch_nonce",
6397                &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
6398            )
6399            .finish()
6400    }
6401}
6402
6403impl From<&ConsumerIdentity> for ConsumerIdentityKey {
6404    fn from(value: &ConsumerIdentity) -> Self {
6405        Self {
6406            module_id: value.module_id.clone(),
6407            launch_nonce: value.launch_nonce.clone(),
6408        }
6409    }
6410}
6411
6412/// Every field of a [`ScopeSelector`], in hashable form.
6413#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6414struct ScopeKey {
6415    /// The owner principal as its JSON encoding. `Principal` is not `Hash`,
6416    /// and matching on its variants here would stop compiling when the
6417    /// protocol crate adds one; the tagged encoding is unique per principal.
6418    owner: String,
6419    scope_ref: String,
6420    scope_epoch: Option<u64>,
6421    bind_proof_digest: Option<[u8; 32]>,
6422}
6423
6424impl From<&ScopeSelector> for ScopeKey {
6425    fn from(value: &ScopeSelector) -> Self {
6426        Self {
6427            owner: serde_json::to_string(&value.owner)
6428                .unwrap_or_else(|_| format!("{:?}", value.owner)),
6429            scope_ref: value.scope_ref.clone(),
6430            scope_epoch: value.scope_epoch,
6431            bind_proof_digest: value
6432                .bind_proof
6433                .as_ref()
6434                .map(|proof| Sha256::digest(proof.as_bytes()).into()),
6435        }
6436    }
6437}
6438
6439#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6440struct ConsumerCapabilitiesKey {
6441    values: Vec<String>,
6442}
6443
6444impl ConsumerCapabilitiesKey {
6445    fn from_slice(values: &[String]) -> Self {
6446        let mut values = values.to_vec();
6447        values.sort();
6448        values.dedup();
6449        Self { values }
6450    }
6451}
6452
6453#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6454enum RouteTargetKey {
6455    ToolProvider {
6456        module_id: String,
6457    },
6458    ManagementSurface {
6459        module_id: String,
6460    },
6461    InternalService {
6462        module_id: String,
6463        service_id: String,
6464    },
6465}
6466
6467impl From<&RouteTarget> for RouteTargetKey {
6468    fn from(value: &RouteTarget) -> Self {
6469        match value {
6470            RouteTarget::ToolProvider { module_id } => Self::ToolProvider {
6471                module_id: module_id.clone(),
6472            },
6473            RouteTarget::ManagementSurface { module_id } => Self::ManagementSurface {
6474                module_id: module_id.clone(),
6475            },
6476            RouteTarget::InternalService {
6477                module_id,
6478                service_id,
6479            } => Self::InternalService {
6480                module_id: module_id.clone(),
6481                service_id: service_id.clone(),
6482            },
6483        }
6484    }
6485}
6486
6487#[derive(Debug, Clone)]
6488struct SharedCallFailure {
6489    kind: FailureKind,
6490}
6491
6492impl SharedCallFailure {
6493    fn not_sent(message: impl Into<String>) -> Self {
6494        CallError::not_sent_with_cause(message, NotSentCause::RouteOpenAbandoned).into()
6495    }
6496
6497    fn into_call_error(self) -> CallError {
6498        match self.kind {
6499            FailureKind::NotSent(source) => CallError::NotSent(Box::new(source)),
6500            FailureKind::OutcomeUnknown(source) => CallError::outcome_unknown_source(source),
6501            FailureKind::DaemonTooOld(daemon_ver) => CallError::DaemonTooOld { daemon_ver },
6502        }
6503    }
6504}
6505
6506impl From<CallError> for SharedCallFailure {
6507    fn from(value: CallError) -> Self {
6508        match value {
6509            CallError::DaemonTooOld { daemon_ver } => Self {
6510                kind: FailureKind::DaemonTooOld(daemon_ver),
6511            },
6512            CallError::NotSent(err) => Self {
6513                kind: FailureKind::NotSent(
6514                    err.downcast_ref::<NotSentSource>()
6515                        .expect("crate-built route.open failure has a typed source")
6516                        .clone(),
6517                ),
6518            },
6519            CallError::OutcomeUnknown(err) => Self {
6520                kind: FailureKind::OutcomeUnknown(
6521                    err.downcast_ref::<OutcomeUnknownSource>()
6522                        .cloned()
6523                        .unwrap_or_else(|| OutcomeUnknownSource {
6524                            message: err.to_string(),
6525                            cause: OutcomeUnknownCause::CompletionFailed,
6526                            route_reason: None,
6527                        }),
6528                ),
6529            },
6530            CallError::Module(body) => Self {
6531                kind: FailureKind::OutcomeUnknown(OutcomeUnknownSource {
6532                    message: format!(
6533                        "unexpected module error during route.open: {} ({})",
6534                        body.code, body.message
6535                    ),
6536                    cause: OutcomeUnknownCause::CompletionFailed,
6537                    route_reason: None,
6538                }),
6539            },
6540            error @ CallError::RouteDead(_) => CallError::outcome_unknown(
6541                format!("unexpected established-route error during route.open: {error}"),
6542                OutcomeUnknownCause::CompletionFailed,
6543            )
6544            .into(),
6545            CallError::SubscriptionBackpressure(err) => Self {
6546                kind: FailureKind::OutcomeUnknown(OutcomeUnknownSource {
6547                    message: err.to_string(),
6548                    cause: OutcomeUnknownCause::CompletionFailed,
6549                    route_reason: None,
6550                }),
6551            },
6552            CallError::StaleRouteHandle(handle) => {
6553                CallError::not_sent(format!("stale route handle: {handle:?}")).into()
6554            }
6555            error @ (CallError::CapabilityUnprovided { .. }
6556            | CallError::CapabilityAmbiguous { .. }
6557            | CallError::InvalidCapabilityIdentifier { .. }) => {
6558                CallError::not_sent(error.to_string()).into()
6559            }
6560        }
6561    }
6562}
6563
6564#[derive(Debug, Clone)]
6565enum FailureKind {
6566    NotSent(NotSentSource),
6567    OutcomeUnknown(OutcomeUnknownSource),
6568    DaemonTooOld(String),
6569}
6570
6571#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
6572struct PendingKey {
6573    generation: u64,
6574    channel: u16,
6575    epoch: u32,
6576    corr: u64,
6577}
6578
6579struct PendingEntry {
6580    accepted: bool,
6581    send_deadline: Option<Instant>,
6582    retain_late_route_open: bool,
6583    expected_control_handle: Option<RouteHandle>,
6584    route_open_reverse_requests: Option<ReverseRequestRegistry>,
6585    route_open_module: Option<String>,
6586    retry: Option<SubscriptionRetry>,
6587    completion: PendingCompletion,
6588}
6589
6590enum PendingCompletion {
6591    Unary(oneshot::Sender<PendingResult>),
6592    Subscription {
6593        events: mpsc::Sender<Vec<u8>>,
6594        closed: oneshot::Sender<Result<(), CallError>>,
6595        ended: watch::Sender<Option<SubscriptionEnd>>,
6596        _permit: Arc<RoutePermit>,
6597        priority: Priority,
6598    },
6599}
6600
6601enum StreamDataDelivery {
6602    NotSubscription,
6603    Full,
6604    Closed,
6605}
6606
6607impl PendingEntry {
6608    fn unary(
6609        tx: oneshot::Sender<PendingResult>,
6610        retain_late_route_open: bool,
6611        expected_control_handle: Option<RouteHandle>,
6612        route_open_reverse_requests: Option<ReverseRequestRegistry>,
6613    ) -> Self {
6614        Self {
6615            accepted: false,
6616            send_deadline: None,
6617            retain_late_route_open,
6618            expected_control_handle,
6619            route_open_reverse_requests,
6620            route_open_module: None,
6621            retry: None,
6622            completion: PendingCompletion::Unary(tx),
6623        }
6624    }
6625
6626    fn subscription(
6627        events: mpsc::Sender<Vec<u8>>,
6628        closed: oneshot::Sender<Result<(), CallError>>,
6629        ended: watch::Sender<Option<SubscriptionEnd>>,
6630        permit: Arc<RoutePermit>,
6631        priority: Priority,
6632    ) -> Self {
6633        Self {
6634            accepted: false,
6635            send_deadline: None,
6636            retain_late_route_open: false,
6637            expected_control_handle: None,
6638            route_open_reverse_requests: None,
6639            route_open_module: None,
6640            retry: None,
6641            completion: PendingCompletion::Subscription {
6642                events,
6643                closed,
6644                ended,
6645                _permit: permit,
6646                priority,
6647            },
6648        }
6649    }
6650
6651    fn completion_is_closed(&self) -> bool {
6652        match &self.completion {
6653            PendingCompletion::Unary(tx) => tx.is_closed(),
6654            PendingCompletion::Subscription { closed, .. } => closed.is_closed(),
6655        }
6656    }
6657
6658    fn is_subscription(&self) -> bool {
6659        matches!(&self.completion, PendingCompletion::Subscription { .. })
6660    }
6661
6662    fn subscription_priority(&self) -> Option<Priority> {
6663        match &self.completion {
6664            PendingCompletion::Subscription { priority, .. } => Some(*priority),
6665            PendingCompletion::Unary(_) => None,
6666        }
6667    }
6668
6669    fn try_send_stream_data(&self, body: Vec<u8>) -> Result<(), StreamDataDelivery> {
6670        let PendingCompletion::Subscription { events, .. } = &self.completion else {
6671            return Err(StreamDataDelivery::NotSubscription);
6672        };
6673        events.try_send(body).map_err(|err| match err {
6674            mpsc::error::TrySendError::Full(_) => StreamDataDelivery::Full,
6675            mpsc::error::TrySendError::Closed(_) => StreamDataDelivery::Closed,
6676        })
6677    }
6678
6679    fn settle_failure(self, reason: String) {
6680        if let Some(retry) = &self.retry {
6681            retry.position.stop.cancel();
6682        }
6683        let err = classify_failure(self.accepted, reason, OutcomeUnknownCause::ConsumerClosed);
6684        match self.completion {
6685            PendingCompletion::Unary(tx) => {
6686                let _ = tx.send(PendingResult::CallError(err));
6687            }
6688            PendingCompletion::Subscription { closed, ended, .. } => {
6689                let _ = ended.send(Some(SubscriptionEnd::RouteClosed {
6690                    reason: RouteEndReason::ClosedByCaller,
6691                }));
6692                let _ = closed.send(Err(err));
6693            }
6694        }
6695    }
6696
6697    fn settle_call_error(self, err: CallError) {
6698        if let Some(retry) = &self.retry {
6699            retry.position.stop.cancel();
6700        }
6701        match self.completion {
6702            PendingCompletion::Unary(tx) => {
6703                let _ = tx.send(PendingResult::CallError(err));
6704            }
6705            PendingCompletion::Subscription { closed, ended, .. } => {
6706                let end = if let Some(reason) = err.close_reason() {
6707                    match reason {
6708                        RouteEndReason::ConnectionLost => SubscriptionEnd::ConnectionLost,
6709                        reason => SubscriptionEnd::RouteClosed {
6710                            reason: reason.clone(),
6711                        },
6712                    }
6713                } else if matches!(err, CallError::SubscriptionBackpressure(_)) {
6714                    SubscriptionEnd::Backpressure
6715                } else {
6716                    SubscriptionEnd::ConnectionLost
6717                };
6718                let _ = ended.send(Some(end));
6719                let _ = closed.send(Err(err));
6720            }
6721        }
6722    }
6723
6724    fn settle_subscription_result(self, result: Result<(), CallError>) {
6725        if let Some(retry) = &self.retry {
6726            retry.position.stop.cancel();
6727        }
6728        match self.completion {
6729            PendingCompletion::Subscription { closed, ended, .. } => {
6730                let _ = ended.send(Some(SubscriptionEnd::Cancelled));
6731                let _ = closed.send(result);
6732            }
6733            PendingCompletion::Unary(tx) => {
6734                let _ = tx.send(PendingResult::Failure {
6735                    accepted: self.accepted,
6736                    reason: "subscription cancel matched a unary request".to_string(),
6737                });
6738            }
6739        }
6740    }
6741}
6742
6743struct PendingRegistration {
6744    shared: Arc<Shared>,
6745    key: PendingKey,
6746    active: bool,
6747    retain_on_drop: bool,
6748    unary_cancel: Option<Arc<UnaryCancel>>,
6749}
6750
6751impl PendingRegistration {
6752    fn new(shared: Arc<Shared>, key: PendingKey, retain_on_drop: bool) -> Self {
6753        Self {
6754            shared,
6755            key,
6756            active: true,
6757            retain_on_drop,
6758            unary_cancel: None,
6759        }
6760    }
6761
6762    fn remove_pending(&mut self) -> Option<bool> {
6763        if !self.active {
6764            return None;
6765        }
6766        self.active = false;
6767        self.shared
6768            .lock_inner()
6769            .remove_pending(&self.key)
6770            .map(|entry| entry.accepted)
6771    }
6772
6773    fn disarm(&mut self) {
6774        self.active = false;
6775    }
6776}
6777
6778impl Drop for PendingRegistration {
6779    fn drop(&mut self) {
6780        if self.retain_on_drop {
6781            self.disarm();
6782        } else {
6783            let _ = self.remove_pending();
6784        }
6785    }
6786}
6787
6788enum PendingResult {
6789    Terminal(PendingTerminal),
6790    CallError(CallError),
6791    Failure { accepted: bool, reason: String },
6792}
6793
6794impl PendingResult {
6795    fn into_call_result(self) -> Result<TerminalFrame, CallError> {
6796        match self {
6797            Self::Terminal(terminal) => Ok(terminal.into_terminal_frame()),
6798            Self::CallError(err) => Err(err),
6799            Self::Failure { accepted, reason } => Err(classify_failure(
6800                accepted,
6801                reason,
6802                OutcomeUnknownCause::CompletionFailed,
6803            )),
6804        }
6805    }
6806}
6807
6808enum PendingTerminal {
6809    Response {
6810        generation: u64,
6811        body: Vec<u8>,
6812        flags: Flags,
6813    },
6814    Error {
6815        body: ErrorBody,
6816        flags: Flags,
6817    },
6818    StreamEnd,
6819}
6820
6821impl PendingTerminal {
6822    fn into_terminal_frame(self) -> TerminalFrame {
6823        match self {
6824            Self::Response {
6825                generation,
6826                body,
6827                flags,
6828            } => TerminalFrame::Response {
6829                generation,
6830                body,
6831                flags,
6832            },
6833            Self::Error { body, flags } => TerminalFrame::Error { body, flags },
6834            Self::StreamEnd => TerminalFrame::StreamEnd,
6835        }
6836    }
6837}
6838
6839#[derive(Debug)]
6840enum TerminalFrame {
6841    Response {
6842        generation: u64,
6843        body: Vec<u8>,
6844        flags: Flags,
6845    },
6846    Error {
6847        body: ErrorBody,
6848        flags: Flags,
6849    },
6850    StreamEnd,
6851}
6852
6853struct WriteCommand {
6854    frame: Frame,
6855    pending: Option<PendingKey>,
6856}
6857
6858trait ConsumerStream: AsyncRead + AsyncWrite + Unpin + Send {}
6859impl<T: AsyncRead + AsyncWrite + Unpin + Send> ConsumerStream for T {}
6860
6861struct OpenedConnection {
6862    stream: Box<dyn ConsumerStream>,
6863    daemon_origin_trusted: bool,
6864    daemon_ver: String,
6865}
6866
6867async fn open_connection(
6868    path: &Path,
6869    deadline: Duration,
6870    transport: ConsumerTransport,
6871    operator_candidates: Option<&[PathBuf]>,
6872) -> Result<OpenedConnection, ConsumerError> {
6873    let path = operator_candidates
6874        .map(crate::operator_app::owned_candidate)
6875        .unwrap_or(path);
6876    if transport == ConsumerTransport::Local {
6877        let read =
6878            connection_file::read_for_client_with_local_endpoint(path).map_err(|source| {
6879                ConsumerError::ConnectionFile {
6880                    path: path.to_path_buf(),
6881                    source,
6882                }
6883            })?;
6884        let endpoint = read
6885            .local_endpoint
6886            .ok_or_else(|| ConsumerError::NoEndpoint {
6887                path: path.to_path_buf(),
6888            })?;
6889        let label = match &endpoint {
6890            connection_file::LocalEndpoint::Unix { path } => path.display().to_string(),
6891            connection_file::LocalEndpoint::Pipe { name } => name.clone(),
6892            _ => "unsupported local endpoint".to_owned(),
6893        };
6894        let mut stream =
6895            connect_local(&endpoint)
6896                .await
6897                .map_err(|source| ConsumerError::Connect {
6898                    path: path.to_path_buf(),
6899                    endpoint: label.clone(),
6900                    source,
6901                })?;
6902        authenticate_client(&mut stream, &read.info, deadline)
6903            .await
6904            .map_err(|source| ConsumerError::Auth {
6905                path: path.to_path_buf(),
6906                endpoint: label,
6907                source,
6908            })?;
6909        crate::registration::bind_consumer(&mut stream, deadline)
6910            .await
6911            .map_err(ConsumerError::claim)?;
6912        return Ok(OpenedConnection {
6913            stream,
6914            daemon_origin_trusted: trusts_daemon_origin(&read.info.daemon_ver),
6915            daemon_ver: read.info.daemon_ver,
6916        });
6917    }
6918    let conn =
6919        connection_file::read_for_client(path).map_err(|source| ConsumerError::ConnectionFile {
6920            path: path.to_path_buf(),
6921            source,
6922        })?;
6923    open_connection_with_info(path, &conn, deadline).await
6924}
6925
6926async fn connect_local(
6927    endpoint: &connection_file::LocalEndpoint,
6928) -> io::Result<Box<dyn ConsumerStream>> {
6929    match endpoint {
6930        #[cfg(unix)]
6931        connection_file::LocalEndpoint::Unix { path } => {
6932            Ok(Box::new(tokio::net::UnixStream::connect(path).await?))
6933        }
6934        #[cfg(windows)]
6935        connection_file::LocalEndpoint::Pipe { name } => Ok(Box::new(
6936            tokio::net::windows::named_pipe::ClientOptions::new().open(name)?,
6937        )),
6938        _ => Err(io::Error::new(
6939            io::ErrorKind::Unsupported,
6940            "unsupported local endpoint kind",
6941        )),
6942    }
6943}
6944
6945async fn open_connection_with_info(
6946    path: &Path,
6947    conn: &connection_file::ConnectionInfo,
6948    deadline: Duration,
6949) -> Result<OpenedConnection, ConsumerError> {
6950    let endpoint = conn
6951        .endpoints
6952        .first()
6953        .ok_or_else(|| ConsumerError::NoEndpoint {
6954            path: path.to_path_buf(),
6955        })?;
6956    let endpoint_label = format!("{}:{}", endpoint.host, endpoint.port);
6957    let mut stream = TcpStream::connect(&endpoint_label)
6958        .await
6959        .map_err(|source| ConsumerError::Connect {
6960            path: path.to_path_buf(),
6961            endpoint: endpoint_label.clone(),
6962            source,
6963        })?;
6964    // Consumers send a request and wait for its reply, so there is no following
6965    // write for Nagle to coalesce with -- it can only hold the request back until
6966    // an ACK returns. Both ends of the hop must disable it for either to help.
6967    //
6968    // Dropped rather than logged for the same reason as the module path: no logging
6969    // dependency here, and a socket too broken to take the option fails the
6970    // handshake on the next line with a typed error.
6971    let _ = stream.set_nodelay(true);
6972    authenticate_client(&mut stream, conn, deadline)
6973        .await
6974        .map_err(|source| ConsumerError::Auth {
6975            path: path.to_path_buf(),
6976            endpoint: endpoint_label,
6977            source,
6978        })?;
6979    crate::registration::bind_consumer(&mut stream, deadline)
6980        .await
6981        .map_err(ConsumerError::claim)?;
6982    Ok(OpenedConnection {
6983        stream: Box::new(stream),
6984        daemon_origin_trusted: trusts_daemon_origin(&conn.daemon_ver),
6985        daemon_ver: conn.daemon_ver.clone(),
6986    })
6987}
6988
6989fn dispatch_reverse_request(shared: &Arc<Shared>, frame: Frame, handle: RouteHandle) {
6990    let method = serde_json::from_slice::<serde_json::Value>(&frame.body)
6991        .ok()
6992        .and_then(|body| body.get("method")?.as_str().map(str::to_string));
6993    let method_family = method
6994        .as_deref()
6995        .and_then(|method| method.split('/').next())
6996        .filter(|family| !family.is_empty())
6997        .map(str::to_string);
6998    let handler = method_family.as_deref().and_then(|family| {
6999        route_reverse_request_registry(handle.reverse_request_registry_id())
7000            .ok()?
7001            .handler(family)
7002    });
7003    let generation = handle.connection_token();
7004    let shared = Arc::clone(shared);
7005
7006    tokio::spawn(async move {
7007        let (frame_type, body) = if let (Some(handler), Some(method)) = (handler, method) {
7008            let request_body = frame.body.clone();
7009            let corr = frame.header.corr;
7010            match tokio::spawn(async move {
7011                handler(request_body, ReverseRequestContext { corr, method }).await
7012            })
7013            .await
7014            {
7015                Ok(Ok(body)) => (FrameType::Response, body),
7016                Ok(Err(err)) => (
7017                    FrameType::Error,
7018                    serde_json::to_vec(&ErrorBody::new(REVERSE_REQUEST_UNHANDLED, err.to_string()))
7019                        .unwrap_or_default(),
7020                ),
7021                Err(err) => (
7022                    FrameType::Error,
7023                    serde_json::to_vec(&ErrorBody::new(
7024                        REVERSE_REQUEST_UNHANDLED,
7025                        join_error_message(err),
7026                    ))
7027                    .unwrap_or_default(),
7028                ),
7029            }
7030        } else {
7031            let message = method_family.map_or_else(
7032                || "reverse request has no valid method".to_string(),
7033                |family| format!("no reverse-request handler is registered for {family}"),
7034            );
7035            (
7036                FrameType::Error,
7037                serde_json::to_vec(&ErrorBody::new(REVERSE_REQUEST_UNHANDLED, message))
7038                    .unwrap_or_default(),
7039            )
7040        };
7041
7042        if shared.ingress_handle(generation, handle.channel, handle.epoch) != Some(handle) {
7043            return;
7044        }
7045        let reply = match Frame::build_with_version(
7046            frame.header.ver,
7047            frame_type,
7048            Flags::new(false, Priority::Interactive, false),
7049            handle.channel,
7050            handle.epoch,
7051            frame.header.corr,
7052            body,
7053        ) {
7054            Ok(reply) => reply,
7055            Err(_) => return,
7056        };
7057        let writer = shared.lock_inner().writer.clone();
7058        if let Some(writer) = writer {
7059            let _ = writer
7060                .send(WriteCommand {
7061                    frame: reply,
7062                    pending: None,
7063                })
7064                .await;
7065        }
7066    });
7067}
7068
7069fn join_error_message(error: tokio::task::JoinError) -> String {
7070    if !error.is_panic() {
7071        return error.to_string();
7072    }
7073    let payload = error.into_panic();
7074    if let Some(message) = payload.downcast_ref::<String>() {
7075        return message.clone();
7076    }
7077    if let Some(message) = payload.downcast_ref::<&str>() {
7078        return (*message).to_string();
7079    }
7080    "reverse-request handler panicked".to_string()
7081}
7082
7083async fn reader_loop<R: AsyncRead + Unpin>(shared: Arc<Shared>, mut reader: R, generation: u64) {
7084    loop {
7085        match read_frame(&mut reader).await {
7086            Ok(Some(frame)) => {
7087                if !dispatch_frame(&shared, generation, frame).await {
7088                    return;
7089                }
7090            }
7091            Ok(None) => {
7092                shared.handle_generation_drop(generation, "subc connection closed".to_string());
7093                return;
7094            }
7095            Err(err) => {
7096                shared.handle_generation_drop(generation, err.to_string());
7097                return;
7098            }
7099        }
7100    }
7101}
7102
7103async fn dispatch_frame(shared: &Arc<Shared>, generation: u64, frame: Frame) -> bool {
7104    if !shared.record_inbound_if_current(generation) {
7105        return false;
7106    }
7107    if frame.header.channel != 0
7108        && !shared.validate_ingress_handle(generation, frame.header.channel, frame.header.epoch)
7109    {
7110        return true;
7111    }
7112
7113    if frame.header.ty == FrameType::Request && frame.header.channel != 0 {
7114        if let Some(handle) =
7115            shared.ingress_handle(generation, frame.header.channel, frame.header.epoch)
7116        {
7117            dispatch_reverse_request(shared, frame, handle);
7118        }
7119        return true;
7120    }
7121
7122    let key = PendingKey {
7123        generation,
7124        channel: frame.header.channel,
7125        epoch: frame.header.epoch,
7126        corr: frame.header.corr,
7127    };
7128
7129    if frame.header.channel == 0 && frame.header.ty == FrameType::Response {
7130        if let Some(expected) = shared.pending_expected_control_handle(key) {
7131            let echoes_expected = matches!(
7132                serde_json::from_slice::<ClientControlResponse>(&frame.body),
7133                Ok(ClientControlResponse::RoutePoll {
7134                    route_channel,
7135                    route_epoch,
7136                    ..
7137                }) if route_channel == expected.channel && route_epoch == expected.epoch
7138            );
7139            if !echoes_expected {
7140                shared.count_dropped_route_frame();
7141                return true;
7142            }
7143        }
7144    }
7145
7146    // A route.open handle is published before its waiter is resolved. The socket reader
7147    // cannot consume a following same-route frame until this synchronous install finishes.
7148    if frame.header.channel == 0
7149        && frame.header.ty == FrameType::Response
7150        && shared.pending_expects_route_open(key)
7151    {
7152        if let Ok((
7153            ClientControlResponse::RouteOpen {
7154                route_channel,
7155                route_epoch,
7156                ..
7157            },
7158            authority,
7159        )) = decode_route_open_response(&frame.body)
7160        {
7161            let reverse_requests = shared
7162                .pending_route_open_reverse_requests(key)
7163                .unwrap_or_default();
7164            let module = shared
7165                .lock_inner()
7166                .pending
7167                .get(&key)
7168                .and_then(|entry| entry.route_open_module.clone());
7169            let handle =
7170                RouteHandle::new_consumer(route_channel, route_epoch, generation, reverse_requests);
7171            shared.install_ingress_handle(handle);
7172            if let Some(target) = authority.target {
7173                let mut inner = shared.lock_inner();
7174                if inner.route_epochs.get(&handle.channel) == Some(&handle) {
7175                    inner.route_targets.insert(handle, target);
7176                }
7177            }
7178            if let Some(module) = module {
7179                shared
7180                    .lock_inner()
7181                    .route_modules
7182                    .insert(route_channel, module);
7183            }
7184        }
7185    }
7186
7187    match frame.header.ty {
7188        FrameType::Response => shared.settle_pending(
7189            key,
7190            PendingTerminal::Response {
7191                generation,
7192                body: frame.body,
7193                flags: frame.header.flags,
7194            },
7195        ),
7196        FrameType::Error => {
7197            let body =
7198                serde_json::from_slice::<ErrorBody>(&frame.body).unwrap_or_else(|err| ErrorBody {
7199                    code: "invalid_error_body".to_string(),
7200                    message: err.to_string(),
7201                    detail: None,
7202                });
7203            shared.settle_pending(
7204                key,
7205                PendingTerminal::Error {
7206                    body,
7207                    flags: frame.header.flags,
7208                },
7209            );
7210        }
7211        FrameType::StreamEnd => shared.settle_pending(key, PendingTerminal::StreamEnd),
7212        FrameType::StreamData => shared.route_stream_data(key, frame.body),
7213        FrameType::Push if frame.header.channel == 0 => {
7214            shared.control_push(&frame.body);
7215        }
7216        FrameType::Push => shared.route_push(
7217            RouteHandle::new(frame.header.channel, frame.header.epoch, generation),
7218            frame.body,
7219        ),
7220        FrameType::Goodbye if frame.header.channel == 0 => {
7221            shared.handle_generation_drop(generation, "subc sent GOODBYE".to_string());
7222            return false;
7223        }
7224        FrameType::Goodbye => {
7225            let handle = RouteHandle::new(frame.header.channel, frame.header.epoch, generation);
7226            let close_reason = shared.lock_inner().route_end(handle.channel);
7227            shared.invalidate_routes_for_handle(handle);
7228            let pending = {
7229                let mut inner = shared.lock_inner();
7230                drain_pending_handle(&mut inner.pending, handle, true)
7231            };
7232            settle_route_pending_entries(pending, "route closed by subc".to_string(), close_reason);
7233        }
7234        FrameType::Ping if frame.header.channel == 0 => {
7235            if let Ok(pong) = Frame::build_with_version(
7236                frame.header.ver,
7237                FrameType::Pong,
7238                frame.header.flags,
7239                0,
7240                0,
7241                frame.header.corr,
7242                Vec::new(),
7243            ) {
7244                let writer = shared.lock_inner().writer.clone();
7245                if let Some(writer) = writer {
7246                    let _ = writer
7247                        .send(WriteCommand {
7248                            frame: pong,
7249                            pending: None,
7250                        })
7251                        .await;
7252                }
7253            }
7254        }
7255        _ => {}
7256    }
7257    true
7258}
7259
7260impl Shared {
7261    /// Stamp after holding the same state lock that guards generation changes, so a
7262    /// late frame from an older reader can never vouch for a newly installed socket.
7263    ///
7264    /// PLACEMENT IS LOAD-BEARING: the single caller sits on the frame-read
7265    /// return, the one point every inbound frame passes before demux -- which
7266    /// is why one stamp suffices. A future fast path or drain-and-dispatch
7267    /// refactor that hands frames onward without crossing that point makes the
7268    /// stamp skippable, and the liveness watermark quietly stops meaning "the
7269    /// link delivered bytes": the cheapest correctness property in this file
7270    /// and the easiest to lose in a refactor.
7271    fn record_inbound_if_current(&self, generation: u64) -> bool {
7272        let inner = self.lock_inner();
7273        if inner.closed || inner.generation != generation || inner.writer.is_none() {
7274            return false;
7275        }
7276        self.last_inbound_ms
7277            .store(epoch_millis(), Ordering::Release);
7278        true
7279    }
7280
7281    fn generation_is_current(&self, generation: u64) -> bool {
7282        let inner = self.lock_inner();
7283        !inner.closed && inner.generation == generation && inner.writer.is_some()
7284    }
7285
7286    fn pending_expected_control_handle(&self, key: PendingKey) -> Option<RouteHandle> {
7287        self.lock_inner()
7288            .pending
7289            .get(&key)
7290            .and_then(|entry| entry.expected_control_handle)
7291    }
7292
7293    fn count_dropped_route_frame(&self) {
7294        let mut inner = self.lock_inner();
7295        inner.dropped_route_frames = inner.dropped_route_frames.saturating_add(1);
7296    }
7297
7298    fn pending_expects_route_open(&self, key: PendingKey) -> bool {
7299        self.lock_inner()
7300            .pending
7301            .get(&key)
7302            .is_some_and(|entry| entry.retain_late_route_open)
7303    }
7304
7305    fn pending_route_open_reverse_requests(
7306        &self,
7307        key: PendingKey,
7308    ) -> Option<ReverseRequestRegistry> {
7309        self.lock_inner()
7310            .pending
7311            .get(&key)
7312            .and_then(|entry| entry.route_open_reverse_requests.clone())
7313    }
7314
7315    fn ingress_handle(&self, generation: u64, channel: u16, epoch: u32) -> Option<RouteHandle> {
7316        let inner = self.lock_inner();
7317        let handle = inner.route_epochs.get(&channel).copied()?;
7318        (handle.connection_token() == generation && handle.epoch == epoch).then_some(handle)
7319    }
7320
7321    fn validate_ingress_handle(&self, generation: u64, channel: u16, epoch: u32) -> bool {
7322        let mut inner = self.lock_inner();
7323        let expected = RouteHandle::new(channel, epoch, generation);
7324        if inner.route_epochs.get(&channel) == Some(&expected) {
7325            true
7326        } else {
7327            inner.dropped_route_frames = inner.dropped_route_frames.saturating_add(1);
7328            false
7329        }
7330    }
7331
7332    fn install_ingress_handle(&self, handle: RouteHandle) {
7333        let mut inner = self.lock_inner();
7334        if !inner.closed && inner.generation == handle.connection_token() && inner.writer.is_some()
7335        {
7336            inner.route_end_reasons.remove(&handle.channel);
7337            inner.legacy_channel_reasons.remove(&handle.channel);
7338            inner.route_modules.remove(&handle.channel);
7339            if let Some(previous) = inner.route_epochs.insert(handle.channel, handle) {
7340                inner.route_targets.remove(&previous);
7341                if previous.reverse_request_registry_id() != handle.reverse_request_registry_id() {
7342                    release_reverse_request_registry(previous);
7343                }
7344            }
7345        }
7346    }
7347
7348    fn invalidate_routes_for_handle(&self, handle: RouteHandle) {
7349        let removed = {
7350            let mut inner = self.lock_inner();
7351            if inner.route_epochs.get(&handle.channel) != Some(&handle) {
7352                return;
7353            }
7354            inner.release_wire_slots(handle);
7355            let installed = inner.route_epochs.remove(&handle.channel).unwrap();
7356            inner.route_targets.remove(&handle);
7357            inner.retired_routes.remove(&handle);
7358            inner.retirement_goodbyes.remove(&handle);
7359            inner.push_event_receivers.remove(&handle);
7360            release_reverse_request_registry(installed);
7361            inner
7362                .remove_route_by_handle(handle)
7363                .into_iter()
7364                .collect::<Vec<_>>()
7365        };
7366        for route in removed {
7367            route.close();
7368        }
7369    }
7370}
7371
7372async fn retirement_goodbye_loop(shared: Arc<Shared>, generation: u64, notify: Arc<Notify>) {
7373    loop {
7374        let notified = notify.notified();
7375        let next = {
7376            let inner = shared.lock_inner();
7377            if inner.closed || inner.generation != generation || inner.writer.is_none() {
7378                return;
7379            }
7380            inner
7381                .retirement_queue
7382                .front()
7383                .map(|handle| (*handle, inner.writer.as_ref().unwrap().clone()))
7384        };
7385        let Some((handle, writer)) = next else {
7386            notified.await;
7387            continue;
7388        };
7389        let Ok(permit) = writer.reserve().await else {
7390            shared.handle_generation_drop(
7391                generation,
7392                "writer closed before retirement GOODBYE".into(),
7393            );
7394            return;
7395        };
7396        let mut inner = shared.lock_inner();
7397        if inner.closed || inner.generation != generation || inner.writer.is_none() {
7398            return;
7399        }
7400        if inner.retirement_queue.front() != Some(&handle) {
7401            continue;
7402        }
7403        inner.retirement_queue.pop_front();
7404        inner.retirement_goodbyes.remove(&handle);
7405        if inner.route_epochs.get(&handle.channel) == Some(&handle) {
7406            let frame = Frame::build(
7407                FrameType::Goodbye,
7408                Flags::new(false, Priority::Interactive, false),
7409                handle.channel,
7410                handle.epoch,
7411                0,
7412                Vec::new(),
7413            )
7414            .expect("header-only route GOODBYE is valid");
7415            // Queue admission and uninstallation share the lock. No new route
7416            // can claim this channel between those operations.
7417            permit.send(WriteCommand {
7418                frame,
7419                pending: None,
7420            });
7421        }
7422        inner.reap_retired_route(handle);
7423    }
7424}
7425
7426async fn writer_loop<W>(
7427    shared: Arc<Shared>,
7428    writer: W,
7429    mut rx: mpsc::Receiver<WriteCommand>,
7430    generation: u64,
7431) where
7432    W: AsyncWrite + Unpin,
7433{
7434    let mut writer = BufWriter::new(writer);
7435    while let Some(command) = rx.recv().await {
7436        if let Some(key) = command.pending {
7437            if !shared.mark_pending_accepted(key) {
7438                continue;
7439            }
7440        }
7441        if let Err(err) = write_frame(&mut writer, &command.frame).await {
7442            shared.handle_generation_drop_with_cause(
7443                generation,
7444                err.to_string(),
7445                OutcomeUnknownCause::WriterClosed,
7446            );
7447            return;
7448        }
7449        while let Ok(command) = rx.try_recv() {
7450            if let Some(key) = command.pending {
7451                if !shared.mark_pending_accepted(key) {
7452                    continue;
7453                }
7454            }
7455            if let Err(err) = write_frame(&mut writer, &command.frame).await {
7456                shared.handle_generation_drop_with_cause(
7457                    generation,
7458                    err.to_string(),
7459                    OutcomeUnknownCause::WriterClosed,
7460                );
7461                return;
7462            }
7463        }
7464        if let Err(err) = writer.flush().await.map_err(FrameIoError::Io) {
7465            shared.handle_generation_drop_with_cause(
7466                generation,
7467                err.to_string(),
7468                OutcomeUnknownCause::WriterClosed,
7469            );
7470            return;
7471        }
7472    }
7473}
7474
7475impl Shared {
7476    fn implicit_consumer_identity(&self) -> Option<ConsumerIdentity> {
7477        // Operator-app connections must not even consult the launch environment:
7478        // the nonce accessor can consume an inherited credential descriptor.
7479        if self.identity_from_environment && !self.claim_bound {
7480            consumer_identity_from_env()
7481        } else {
7482            None
7483        }
7484    }
7485
7486    fn activity_read_body(&self, request: impl serde::Serialize) -> Result<Vec<u8>, CallError> {
7487        #[derive(serde::Serialize)]
7488        struct ReadRequest<T> {
7489            #[serde(flatten)]
7490            request: T,
7491            #[serde(skip_serializing_if = "Option::is_none")]
7492            consumer_identity: Option<ConsumerIdentity>,
7493        }
7494        serde_json::to_vec(&ReadRequest {
7495            request,
7496            consumer_identity: self.implicit_consumer_identity(),
7497        })
7498        .map_err(|err| CallError::not_sent(format!("failed to encode activity read: {err}")))
7499    }
7500
7501    fn route_open_consumer_identity(
7502        &self,
7503        opts: &CallOptions,
7504    ) -> Result<Option<ConsumerIdentity>, CallError> {
7505        if self.claim_bound && opts.consumer_identity.is_some() {
7506            // Legacy nonce identities cannot describe a claim-bound connection.
7507            return Err(CallError::not_sent(
7508                "consumer identity conflicts with connection binding",
7509            ));
7510        }
7511        Ok(opts
7512            .consumer_identity
7513            .clone()
7514            .or_else(|| self.implicit_consumer_identity()))
7515    }
7516
7517    fn close_route_consumer_identity(
7518        &self,
7519        opts: &CloseRouteOptions,
7520    ) -> Result<Option<ConsumerIdentity>, CallError> {
7521        if self.claim_bound && opts.consumer_identity.is_some() {
7522            return Err(CallError::not_sent(
7523                "consumer identity conflicts with connection binding",
7524            ));
7525        }
7526        Ok(opts
7527            .consumer_identity
7528            .clone()
7529            .or_else(|| self.implicit_consumer_identity()))
7530    }
7531}
7532
7533fn route_open_consumer_capabilities(opts: &CallOptions) -> Option<Vec<String>> {
7534    opts.reverse_requests.seal();
7535    let mut capabilities = opts.reverse_requests.capabilities();
7536    capabilities.extend(opts.consumer_capabilities());
7537    capabilities.sort();
7538    capabilities.dedup();
7539    (!capabilities.is_empty()).then_some(capabilities)
7540}
7541
7542/// The role versions a route is opened and keyed with. An empty map declares
7543/// nothing, and the daemon forwards it as no field at all, so it is folded
7544/// into `None` here: otherwise `Some({})` and `None` would key two routes the
7545/// provider cannot tell apart.
7546fn route_open_role_versions(
7547    role_versions: Option<&BTreeMap<String, String>>,
7548) -> Option<BTreeMap<String, String>> {
7549    role_versions
7550        .filter(|role_versions| !role_versions.is_empty())
7551        .cloned()
7552}
7553
7554fn close_route_consumer_capabilities(opts: &CloseRouteOptions) -> Option<Vec<String>> {
7555    opts.reverse_requests.seal();
7556    let mut capabilities = opts.reverse_requests.capabilities();
7557    capabilities.extend(opts.consumer_capabilities());
7558    capabilities.sort();
7559    capabilities.dedup();
7560    (!capabilities.is_empty()).then_some(capabilities)
7561}
7562
7563fn consumer_identity_from_env() -> Option<ConsumerIdentity> {
7564    let module_id = std::env::var(SUBC_MODULE_ID_ENV)
7565        .ok()
7566        .filter(|value| !value.is_empty())?;
7567    // Through the process's one cached accessor, never a second read of the
7568    // descriptor. An accessor error (for example a process a module spawned,
7569    // which inherits the descriptor variable but not the pipe) opens the
7570    // route without identity: it never falls back to the environment copy,
7571    // because presenting the module's nonce is exactly what such a process
7572    // must no longer be able to do.
7573    let launch_nonce = crate::launch_nonce()
7574        .ok()
7575        .flatten()
7576        .map(|nonce| nonce.value().to_string())?;
7577    Some(ConsumerIdentity {
7578        module_id,
7579        launch_nonce,
7580    })
7581}
7582
7583fn validate_capability_for_resolution(capability: &str) -> Result<(), CallError> {
7584    if is_valid_capability_identifier(capability) {
7585        Ok(())
7586    } else {
7587        Err(CallError::InvalidCapabilityIdentifier {
7588            capability: capability.to_string(),
7589        })
7590    }
7591}
7592
7593fn capability_claimants(catalog: &CatalogList, capability: &str) -> Vec<String> {
7594    let mut claimants = catalog
7595        .modules
7596        .iter()
7597        .filter(|module| {
7598            module.capabilities.as_ref().is_some_and(|capabilities| {
7599                capabilities
7600                    .provides
7601                    .iter()
7602                    .any(|claim| claim == capability)
7603            })
7604        })
7605        .map(|module| module.module_id.clone())
7606        .collect::<Vec<_>>();
7607    claimants.sort();
7608    claimants
7609}
7610
7611fn epoch_millis() -> u64 {
7612    u64::try_from(
7613        SystemTime::now()
7614            .duration_since(UNIX_EPOCH)
7615            .unwrap_or_default()
7616            .as_millis(),
7617    )
7618    .unwrap_or(u64::MAX)
7619}
7620
7621/// Reclassify a route-open failure seen by a managed `call` or `subscribe`.
7622///
7623/// `ensure_route` reports the route.open control request's own outcome, which
7624/// is `OutcomeUnknown` when that request was written but its reply did not
7625/// arrive before the deadline: the daemon may or may not have opened the
7626/// channel. The caller's request body, however, is only written after a route
7627/// is in hand, so when no route came back the body provably never left the
7628/// client. From the caller's point of view that is `NotSent`, and reporting
7629/// `OutcomeUnknown` would wrongly tell it a non-idempotent operation might
7630/// have run. A route.open reply that arrives after its waiter gave up is still
7631/// cleaned up: `settle_pending` sends that channel a GOODBYE instead of caching
7632/// it, so reporting `NotSent` here leaves no route open behind.
7633/// A uniform value in [0, 1) for retry jitter. Jitter needs spread, not
7634/// unpredictability, so this hashes a counter with std's randomly keyed hasher
7635/// instead of taking a dependency on a random-number crate.
7636fn default_random_unit() -> f64 {
7637    use std::hash::{BuildHasher, RandomState};
7638    static COUNTER: AtomicU64 = AtomicU64::new(0);
7639    let bits = RandomState::new().hash_one(COUNTER.fetch_add(1, Ordering::Relaxed));
7640    // The top 53 bits fill an f64 mantissa exactly.
7641    (bits >> 11) as f64 / (1u64 << 53) as f64
7642}
7643
7644fn request_not_sent_after_route_open_failure(err: CallError) -> CallError {
7645    match err {
7646        CallError::OutcomeUnknown(source) => CallError::not_sent_with_cause(
7647            format!("request not sent: route.open did not complete ({source})"),
7648            NotSentCause::RouteOpenAbandoned,
7649        ),
7650        other => other,
7651    }
7652}
7653
7654fn classify_failure(
7655    accepted: bool,
7656    reason: impl Into<String>,
7657    cause: OutcomeUnknownCause,
7658) -> CallError {
7659    classify_failure_with_not_sent_cause(accepted, reason, cause, NotSentCause::WriterRejected)
7660}
7661
7662fn classify_failure_with_not_sent_cause(
7663    accepted: bool,
7664    reason: impl Into<String>,
7665    cause: OutcomeUnknownCause,
7666    not_sent_cause: NotSentCause,
7667) -> CallError {
7668    if accepted {
7669        CallError::outcome_unknown(reason, cause)
7670    } else {
7671        CallError::not_sent_with_cause(reason, not_sent_cause)
7672    }
7673}
7674
7675fn settle_route_pending_entries(
7676    entries: Vec<PendingEntry>,
7677    message: String,
7678    reason: impl Into<RouteEnd>,
7679) {
7680    let reason = reason.into();
7681    let cause = if reason.reason == RouteEndReason::ConnectionLost {
7682        OutcomeUnknownCause::ConnectionFailed
7683    } else {
7684        OutcomeUnknownCause::RouteEnded
7685    };
7686    settle_route_pending_entries_with_cause(entries, message, reason, cause);
7687}
7688
7689fn settle_route_pending_entries_with_cause(
7690    entries: Vec<PendingEntry>,
7691    message: String,
7692    reason: impl Into<RouteEnd>,
7693    cause: OutcomeUnknownCause,
7694) {
7695    let reason = reason.into();
7696    for entry in entries {
7697        let err = if entry.accepted {
7698            CallError::outcome_unknown_source(OutcomeUnknownSource {
7699                message: message.clone(),
7700                cause,
7701                route_reason: Some(reason.clone()),
7702            })
7703        } else {
7704            CallError::NotSent(Box::new(NotSentSource {
7705                message: message.clone(),
7706                cause: NotSentCause::WriterRejected,
7707                never_forwarded: true,
7708                route_reason: Some(reason.clone()),
7709                refusal: None,
7710            }))
7711        };
7712        entry.settle_call_error(err);
7713    }
7714}
7715
7716fn settle_pending_entries(entries: Vec<PendingEntry>, reason: String) {
7717    for entry in entries {
7718        entry.settle_failure(reason.clone());
7719    }
7720}
7721
7722fn drain_pending_generation(
7723    pending: &mut HashMap<PendingKey, PendingEntry>,
7724    generation: u64,
7725) -> Vec<PendingEntry> {
7726    let keys = pending
7727        .keys()
7728        .copied()
7729        .filter(|key| key.generation == generation)
7730        .collect::<Vec<_>>();
7731    keys.into_iter()
7732        .filter_map(|key| pending.remove(&key))
7733        .collect()
7734}
7735
7736fn drain_pending_handle(
7737    pending: &mut HashMap<PendingKey, PendingEntry>,
7738    handle: RouteHandle,
7739    include_subscriptions: bool,
7740) -> Vec<PendingEntry> {
7741    let keys = pending
7742        .iter()
7743        .filter_map(|(key, entry)| {
7744            (key.generation == handle.connection_token()
7745                && key.channel == handle.channel
7746                && key.epoch == handle.epoch
7747                && (include_subscriptions || !entry.is_subscription()))
7748            .then_some(*key)
7749        })
7750        .collect::<Vec<_>>();
7751    keys.into_iter()
7752        .filter_map(|key| pending.remove(&key))
7753        .collect()
7754}
7755
7756fn fail_openings(openings: Vec<Vec<OpeningWaiter>>, failure: SharedCallFailure) {
7757    for waiters in openings {
7758        for waiter in waiters {
7759            let _ = waiter.send(Err(failure.clone()));
7760        }
7761    }
7762}
7763
7764fn emit_callbacks(callbacks: Vec<Callback>, state: ConnectionState) {
7765    for callback in callbacks {
7766        if let Ok(callback) = callback.lock() {
7767            callback(state.clone());
7768        }
7769    }
7770}
7771
7772/// The route-open retry predicate, defined once in `subc_protocol::error_codes`
7773/// so consumers with their own connection layer share it rather than copy it.
7774pub fn is_retryable_route_open_code(code: &str) -> bool {
7775    error_codes::is_retryable_route_open(code)
7776}
7777
7778/// Whether a data-plane ERROR answering a managed call's request is the
7779/// daemon's drain refusal, `module_reloading`, which the call may resend once
7780/// after reopening the route.
7781///
7782/// On an established route the daemon answers `module_reloading` only when the
7783/// module's endpoint is draining and the request could not take a route
7784/// credit, and it answers BEFORE forwarding (`ForwardBackend::handle_bound` in
7785/// subc-daemon's `router.rs`), so the module never received the request and a
7786/// resend cannot run it twice. The protocol documents that guarantee on
7787/// `error_codes::MODULE_RELOADING`.
7788///
7789/// Kept apart from `error_codes::is_established_route_dead` on purpose. That
7790/// shared predicate decides route DEATH, and other consumers map it to their
7791/// own custody, provider or suspect verdicts; adding a drain code there would
7792/// change those verdicts on a protocol bump. Here the code only earns the same
7793/// remedy (evict, reopen, resend once) inside this client's unary call path.
7794fn is_data_plane_drain_refusal(code: &str) -> bool {
7795    code == error_codes::MODULE_RELOADING
7796}
7797
7798// 0.37.15 is the first daemon that marks its own errors and strips the bit from module frames.
7799const DAEMON_ORIGIN_MIN_VERSION: (u64, u64, u64) = (0, 37, 15);
7800
7801/// Whether a connected daemon strips forged `DAEMON_ORIGIN` flags from module
7802/// frames: only exact numeric `major.minor.patch` versions at least 0.37.15.
7803/// Unknown versions, including pre-release and build suffixes, fail closed.
7804///
7805/// Pass the version from the same `ConnectionInfo` used by a successful
7806/// `authenticate_client` handshake. That handshake checks the daemon id against
7807/// the file, but its HMAC does not cover the version itself. Do not re-read the
7808/// file to classify a connection that is already authenticated.
7809pub fn trusts_daemon_origin(daemon_ver: &str) -> bool {
7810    daemon_version_at_least(daemon_ver, DAEMON_ORIGIN_MIN_VERSION)
7811}
7812
7813fn daemon_version_at_least(daemon_ver: &str, minimum: (u64, u64, u64)) -> bool {
7814    let mut components = daemon_ver.split('.');
7815    let mut next = || {
7816        let component = components.next()?;
7817        if component.is_empty() || !component.bytes().all(|byte| byte.is_ascii_digit()) {
7818            return None;
7819        }
7820        component.parse::<u64>().ok()
7821    };
7822    let version = (next(), next(), next());
7823    match version {
7824        (Some(major), Some(minor), Some(patch)) if components.next().is_none() => {
7825            (major, minor, patch) >= minimum
7826        }
7827        _ => false,
7828    }
7829}
7830
7831/// Whether an Error frame proves that its request was never forwarded.
7832///
7833/// This covers only `module_reloading`, `unknown_channel` and
7834/// `stale_route_epoch` with `DAEMON_ORIGIN`, when `daemon_origin_trusted` came
7835/// from [`trusts_daemon_origin`] for this connection's authenticated daemon
7836/// (0.37.15 or later). It proves only this attempt, not any earlier attempts of
7837/// a call. For managed calls use [`CallError::never_forwarded`] instead.
7838/// Unmarked errors and untrusted daemon versions never prove non-delivery.
7839/// This helper cannot see route negotiation and does not classify `route_busy`;
7840/// SDK-managed requests on opted-in routes handle that refusal internally.
7841pub fn is_daemon_refusal_before_forward(
7842    daemon_origin_trusted: bool,
7843    flags: Flags,
7844    code: &str,
7845) -> bool {
7846    daemon_origin_trusted
7847        && flags.is_daemon_origin()
7848        && matches!(
7849            code,
7850            error_codes::MODULE_RELOADING
7851                | error_codes::UNKNOWN_CHANNEL
7852                | error_codes::STALE_ROUTE_EPOCH
7853        )
7854}
7855
7856/// Whether `handle` names a route installed on the current connection. Channel 0 is the
7857/// connection's own control channel: it is never installed as a route and is current for
7858/// as long as the connection is, so a held channel-0 request (the spawn stream) can be
7859/// cancelled like a route subscription.
7860fn route_is_installed(inner: &Inner, handle: RouteHandle) -> bool {
7861    handle.channel == 0 || inner.route_epochs.get(&handle.channel) == Some(&handle)
7862}
7863
7864fn is_retryable_catalog_transport_error(err: &CallError) -> bool {
7865    matches!(err, CallError::NotSent(_) | CallError::OutcomeUnknown(_))
7866}
7867
7868fn is_reconnect_transient(err: &ConsumerError) -> bool {
7869    if let ConsumerError::Connect { source, .. } = err {
7870        if let Some(claim) = source
7871            .get_ref()
7872            .and_then(|source| source.downcast_ref::<crate::ClaimError>())
7873        {
7874            return matches!(claim, crate::ClaimError::Refused { code } if error_codes::is_retryable_claim(code));
7875        }
7876    }
7877    match err {
7878        ConsumerError::Connect { source, .. } => matches!(
7879            source.kind(),
7880            io::ErrorKind::ConnectionRefused
7881                | io::ErrorKind::ConnectionReset
7882                | io::ErrorKind::ConnectionAborted
7883                | io::ErrorKind::TimedOut
7884                | io::ErrorKind::NotConnected
7885                | io::ErrorKind::AddrNotAvailable
7886        ),
7887        ConsumerError::ConnectionFile { source, .. } => match source {
7888            ConnectionFileError::Io { source, .. } => source.kind() == io::ErrorKind::NotFound,
7889            _ => false,
7890        },
7891        // Auth failure is transient during reconnect: the daemon rotates its key
7892        // on every restart, and with a fixed port a client racing the restart can
7893        // read the pre-rotation connection file yet still connect — the proof
7894        // mismatch then means "stale key mid-rotation", not "impostor". Each
7895        // retry re-reads the connection file (open_connection), so the next
7896        // attempt picks up the rotated key, and server-proves-first protects
7897        // every attempt. First-connect auth failures stay permanent: connect()
7898        // surfaces them directly without entering the reconnect classifier.
7899        ConsumerError::Auth { .. } => true,
7900        ConsumerError::Discovery { .. }
7901        | ConsumerError::NoEndpoint { .. }
7902        | ConsumerError::Closed => false,
7903    }
7904}
7905
7906impl From<FrameBuildError> for CallError {
7907    fn from(err: FrameBuildError) -> Self {
7908        Self::not_sent(err.to_string())
7909    }
7910}
7911
7912#[cfg(test)]
7913mod local_transport_tests;
7914
7915#[cfg(test)]
7916mod tests {
7917    use super::*;
7918
7919    mod busy_refusals_tests;
7920    mod not_sent_tests;
7921    mod route_close_tests;
7922    mod route_deadline_tests;
7923
7924    #[derive(Clone)]
7925    struct InstrumentedWriter {
7926        state: Arc<InstrumentedWriterState>,
7927        fail_flush: bool,
7928    }
7929
7930    #[derive(Default)]
7931    struct InstrumentedWriterState {
7932        bytes: Mutex<Vec<u8>>,
7933        flushes: std::sync::atomic::AtomicUsize,
7934    }
7935
7936    impl InstrumentedWriter {
7937        fn new(fail_flush: bool) -> Self {
7938            Self {
7939                state: Arc::new(InstrumentedWriterState::default()),
7940                fail_flush,
7941            }
7942        }
7943
7944        fn bytes(&self) -> Vec<u8> {
7945            self.state
7946                .bytes
7947                .lock()
7948                .unwrap_or_else(|poisoned| poisoned.into_inner())
7949                .clone()
7950        }
7951
7952        fn flush_count(&self) -> usize {
7953            self.state.flushes.load(Ordering::SeqCst)
7954        }
7955    }
7956
7957    impl AsyncWrite for InstrumentedWriter {
7958        fn poll_write(
7959            self: Pin<&mut Self>,
7960            _cx: &mut Context<'_>,
7961            buf: &[u8],
7962        ) -> Poll<io::Result<usize>> {
7963            self.state
7964                .bytes
7965                .lock()
7966                .unwrap_or_else(|poisoned| poisoned.into_inner())
7967                .extend_from_slice(buf);
7968            Poll::Ready(Ok(buf.len()))
7969        }
7970
7971        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
7972            self.state.flushes.fetch_add(1, Ordering::SeqCst);
7973            if self.fail_flush {
7974                Poll::Ready(Err(io::Error::new(
7975                    io::ErrorKind::BrokenPipe,
7976                    "instrumented flush failure",
7977                )))
7978            } else {
7979                Poll::Ready(Ok(()))
7980            }
7981        }
7982
7983        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
7984            Poll::Ready(Ok(()))
7985        }
7986    }
7987
7988    fn writer_test_shared() -> Arc<Shared> {
7989        Arc::new(reader_skew_tests::legacy_shared(
7990            PathBuf::from("/tmp/does-not-exist"),
7991            ConsumerOptions {
7992                reconnect_backoff: RetryBackoff {
7993                    max_attempts: 1,
7994                    ..RetryBackoff::default()
7995                },
7996                ..ConsumerOptions::default()
7997            },
7998        ))
7999    }
8000
8001    fn reverse_test_shared(
8002        reverse_requests: ReverseRequestRegistry,
8003    ) -> (Arc<Shared>, mpsc::Receiver<WriteCommand>, RouteHandle) {
8004        let shared = writer_test_shared();
8005        let (writer, receiver) = mpsc::channel(16);
8006        let handle = RouteHandle::new_consumer(17, 3, 1, reverse_requests);
8007        {
8008            let mut inner = shared.lock_inner();
8009            inner.writer = Some(writer);
8010            inner.daemon_ver = "0.39.0".into();
8011            inner.route_epochs.insert(handle.channel, handle);
8012        }
8013        (shared, receiver, handle)
8014    }
8015
8016    fn reverse_request_frame(handle: RouteHandle, corr: u64, body: Vec<u8>) -> Frame {
8017        Frame::build(
8018            FrameType::Request,
8019            Flags::new(false, Priority::Interactive, false),
8020            handle.channel,
8021            handle.epoch,
8022            corr,
8023            body,
8024        )
8025        .unwrap()
8026    }
8027
8028    #[tokio::test]
8029    async fn binary_reply_request_preserves_flagged_non_utf8_bytes() {
8030        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
8031        let consumer = SubcConsumer {
8032            shared: Arc::clone(&shared),
8033        };
8034        shared
8035            .install_one_shot_route(RouteState {
8036                handle,
8037                sem: Arc::new(Semaphore::new(1)),
8038                watch_sem: None,
8039                opted_in: false,
8040            })
8041            .unwrap();
8042        let request = tokio::spawn(async move {
8043            consumer
8044                .request(&handle, b"bytes".to_vec(), CallOptions::default())
8045                .await
8046        });
8047        let command = receiver.recv().await.unwrap();
8048        let bytes = vec![0, 0xff, 0x80, b'{'];
8049        let frame = Frame::build(
8050            FrameType::Response,
8051            Flags::new(true, Priority::Interactive, false),
8052            handle.channel,
8053            handle.epoch,
8054            command.frame.header.corr,
8055            bytes.clone(),
8056        )
8057        .unwrap();
8058        assert!(dispatch_frame(&shared, 1, frame).await);
8059        assert_eq!(request.await.unwrap().unwrap(), bytes);
8060    }
8061
8062    async fn capture_route_open(
8063        reverse_requests: ReverseRequestRegistry,
8064    ) -> (serde_json::Value, RouteHandle) {
8065        capture_route_open_with_options(CallOptions {
8066            reverse_requests,
8067            ..CallOptions::default()
8068        })
8069        .await
8070    }
8071
8072    async fn capture_route_open_with_options(
8073        opts: CallOptions,
8074    ) -> (serde_json::Value, RouteHandle) {
8075        let shared = writer_test_shared();
8076        let (writer, mut receiver) = mpsc::channel(4);
8077        shared.lock_inner().writer = Some(writer);
8078        shared.lock_inner().daemon_ver = "0.39.0".into();
8079        let consumer = SubcConsumer {
8080            shared: Arc::clone(&shared),
8081        };
8082        let task = tokio::spawn(async move {
8083            consumer
8084                .open_route(
8085                    RouteTarget::ToolProvider {
8086                        module_id: "reverse-provider".to_string(),
8087                    },
8088                    BindIdentity::new("test".to_string(), "reverse".to_string()),
8089                    opts,
8090                )
8091                .await
8092        });
8093        let command = receiver.recv().await.expect("route.open frame");
8094        let request = serde_json::from_slice(&command.frame.body).unwrap();
8095        let response_body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
8096            request_window: None,
8097            watch_window: None,
8098            route_channel: 17,
8099            route_epoch: 3,
8100        })
8101        .unwrap();
8102        assert!(
8103            dispatch_frame(
8104                &shared,
8105                1,
8106                response_frame(0, 0, command.frame.header.corr, response_body),
8107            )
8108            .await
8109        );
8110        let handle = task.await.unwrap().unwrap();
8111        (request, handle)
8112    }
8113
8114    /// Keep held subscriptions marked for drain accounting without marking ordinary requests.
8115    #[tokio::test]
8116    async fn held_subscriptions_set_the_flag_but_ordinary_requests_do_not() {
8117        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
8118        let call_shared = Arc::clone(&shared);
8119        let call = tokio::spawn(async move {
8120            call_shared
8121                .send_request(RequestSend {
8122                    binary: false,
8123                    expected_handle: Some(handle),
8124                    channel: handle.channel,
8125                    epoch: handle.epoch,
8126                    body: b"ordinary".to_vec(),
8127                    priority: Priority::Interactive,
8128                    admission_class: AdmissionClass::Normal,
8129                    deadline: Instant::now() + Duration::from_secs(1),
8130                    retain_late_route_open: false,
8131                    route_open_reverse_requests: None,
8132                })
8133                .await
8134        });
8135        let ordinary = receiver.recv().await.unwrap();
8136        assert_eq!(ordinary.frame.header.encode()[6] & FLAG_SUBSCRIPTION, 0);
8137        assert!(
8138            dispatch_frame(
8139                &shared,
8140                1,
8141                response_frame(
8142                    handle.channel,
8143                    handle.epoch,
8144                    ordinary.frame.header.corr,
8145                    Vec::new()
8146                ),
8147            )
8148            .await
8149        );
8150        assert!(call.await.unwrap().is_ok());
8151
8152        let permit = Arc::new(Semaphore::new(1)).acquire_owned().await.unwrap();
8153        let subscription = Arc::clone(&shared)
8154            .send_subscription(SubscriptionSend {
8155                expected_handle: Some(handle),
8156                channel: handle.channel,
8157                epoch: handle.epoch,
8158                body: b"held".to_vec(),
8159                priority: Priority::Interactive,
8160                admission_class: AdmissionClass::Normal,
8161                event_buffer: 1,
8162                deadline: Instant::now() + Duration::from_secs(1),
8163                permit: RoutePermit::legacy(permit),
8164            })
8165            .await
8166            .unwrap();
8167        let held = receiver.recv().await.unwrap();
8168        assert_ne!(
8169            held.frame.header.encode()[6] & FLAG_SUBSCRIPTION,
8170            0,
8171            "a held-open subscription must be marked for drain accounting"
8172        );
8173        drop(subscription);
8174        release_reverse_request_registry(handle);
8175    }
8176
8177    #[tokio::test]
8178    async fn registered_handlers_derive_route_open_consumer_capabilities() {
8179        let registry = ReverseRequestRegistry::new();
8180        registry
8181            .on_request("elicitation", |_body, _ctx| async { Vec::new() })
8182            .unwrap();
8183        let (request, handle) = capture_route_open(registry).await;
8184        assert_eq!(
8185            request.get("consumer_capabilities"),
8186            Some(&serde_json::json!(["elicitation"]))
8187        );
8188        release_reverse_request_registry(handle);
8189    }
8190
8191    #[tokio::test]
8192    async fn declared_consumer_capabilities_merge_with_handler_families_on_route_open() {
8193        let registry = ReverseRequestRegistry::new();
8194        registry
8195            .on_request("elicitation", |_body, _ctx| async { Vec::new() })
8196            .unwrap();
8197        let opts = CallOptions {
8198            reverse_requests: registry,
8199            ..CallOptions::default()
8200        }
8201        .with_consumer_capability("tool-result/v1")
8202        .unwrap()
8203        .with_consumer_capability("elicitation")
8204        .unwrap()
8205        .with_consumer_capability("tool-result/v1")
8206        .unwrap();
8207
8208        let (request, handle) = capture_route_open_with_options(opts).await;
8209        assert_eq!(
8210            request.get("consumer_capabilities"),
8211            Some(&serde_json::json!(["elicitation", "tool-result/v1"]))
8212        );
8213        release_reverse_request_registry(handle);
8214    }
8215
8216    #[test]
8217    fn invalid_consumer_capability_declarations_are_rejected_before_route_open() {
8218        let (shared, mut receiver) = {
8219            let shared = writer_test_shared();
8220            let (writer, receiver) = mpsc::channel(4);
8221            shared.lock_inner().writer = Some(writer);
8222            shared.lock_inner().daemon_ver = "0.39.0".into();
8223            (shared, receiver)
8224        };
8225        let too_long = "x".repeat(65);
8226        for invalid in [
8227            String::new(),
8228            "content v1".to_string(),
8229            "content\tv1".to_string(),
8230            "content\nv1".to_string(),
8231            "cöntent/v1".to_string(),
8232            "content/\u{7f}v1".to_string(),
8233            too_long,
8234        ] {
8235            let error = CallOptions::default()
8236                .with_consumer_capability(invalid.clone())
8237                .expect_err("invalid declarations must not produce route options");
8238            assert_eq!(error.capability(), invalid);
8239            assert!(
8240                receiver.try_recv().is_err(),
8241                "invalid declaration {invalid:?} must be rejected before any frame is queued"
8242            );
8243        }
8244        let close_error = CloseRouteOptions::default()
8245            .with_consumer_capability("bad value")
8246            .expect_err("close-route declarations use the same validation");
8247        assert_eq!(close_error.capability(), "bad value");
8248        let call_options = CallOptions::default()
8249            .with_consumer_capability("tool-result/v1")
8250            .unwrap();
8251        assert_eq!(
8252            call_options.consumer_capabilities(),
8253            vec!["tool-result/v1".to_string()]
8254        );
8255        let close_options = CloseRouteOptions::default()
8256            .with_consumer_capability("tool-result/v1")
8257            .unwrap();
8258        assert_eq!(
8259            close_options.consumer_capabilities(),
8260            vec!["tool-result/v1".to_string()]
8261        );
8262        shared.close_sync("test complete");
8263    }
8264
8265    #[tokio::test]
8266    async fn no_handlers_omit_consumer_capabilities_from_route_open() {
8267        let (request, handle) = capture_route_open(ReverseRequestRegistry::new()).await;
8268        assert!(!request
8269            .as_object()
8270            .unwrap()
8271            .contains_key("consumer_capabilities"));
8272        release_reverse_request_registry(handle);
8273    }
8274
8275    #[tokio::test]
8276    async fn reverse_request_without_handler_returns_typed_error_instead_of_silence() {
8277        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
8278        let body = serde_json::to_vec(&serde_json::json!({
8279            "jsonrpc": "2.0",
8280            "id": 1,
8281            "method": "elicitation/create",
8282            "params": {}
8283        }))
8284        .unwrap();
8285        assert!(dispatch_frame(&shared, 1, reverse_request_frame(handle, 800, body)).await);
8286        let reply = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
8287            .await
8288            .unwrap()
8289            .unwrap()
8290            .frame;
8291        assert_eq!(reply.header.ty, FrameType::Error);
8292        assert_eq!(reply.header.corr, 800);
8293        let error: ErrorBody = serde_json::from_slice(&reply.body).unwrap();
8294        assert_eq!(error.code, REVERSE_REQUEST_UNHANDLED);
8295        release_reverse_request_registry(handle);
8296    }
8297
8298    #[tokio::test]
8299    async fn reverse_request_round_trip_preserves_raw_body_corr_and_response() {
8300        let registry = ReverseRequestRegistry::new();
8301        let seen = Arc::new(Mutex::new(None));
8302        let seen_by_handler = Arc::clone(&seen);
8303        let response = br#"{"jsonrpc":"2.0","id":9,"result":{"accepted":true}}"#.to_vec();
8304        let expected_response = response.clone();
8305        registry
8306            .on_request("elicitation", move |body, ctx| {
8307                *seen_by_handler
8308                    .lock()
8309                    .unwrap_or_else(|poisoned| poisoned.into_inner()) =
8310                    Some((body, ctx.corr, ctx.method));
8311                let response = response.clone();
8312                async move { response }
8313            })
8314            .unwrap();
8315        let (shared, mut receiver, handle) = reverse_test_shared(registry);
8316        let request_body =
8317            br#"{"jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"z":1,"a":2}}"#
8318                .to_vec();
8319        assert!(
8320            dispatch_frame(
8321                &shared,
8322                1,
8323                reverse_request_frame(handle, 801, request_body.clone()),
8324            )
8325            .await
8326        );
8327        let reply = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
8328            .await
8329            .unwrap()
8330            .unwrap()
8331            .frame;
8332        assert_eq!(reply.header.ty, FrameType::Response);
8333        assert_eq!(reply.header.corr, 801);
8334        assert_eq!(reply.body, expected_response);
8335        assert_eq!(
8336            seen.lock()
8337                .unwrap_or_else(|poisoned| poisoned.into_inner())
8338                .clone(),
8339            Some((request_body, 801, "elicitation/create".to_string()))
8340        );
8341        release_reverse_request_registry(handle);
8342    }
8343
8344    #[tokio::test]
8345    async fn panicking_reverse_handler_returns_typed_refusal_and_sibling_request_resolves() {
8346        let registry = ReverseRequestRegistry::new();
8347        registry
8348            .on_request("sampling", |_body, _ctx| async move {
8349                panic!("person prompt exploded");
8350            })
8351            .unwrap();
8352        let (shared, mut receiver, handle) = reverse_test_shared(registry);
8353        let sibling_shared = Arc::clone(&shared);
8354        let sibling = tokio::spawn(async move {
8355            sibling_shared
8356                .send_request(RequestSend {
8357                    binary: false,
8358                    expected_handle: Some(handle),
8359                    channel: handle.channel,
8360                    epoch: handle.epoch,
8361                    body: b"sibling".to_vec(),
8362                    priority: Priority::Interactive,
8363                    admission_class: AdmissionClass::Normal,
8364                    deadline: Instant::now() + Duration::from_secs(1),
8365                    retain_late_route_open: false,
8366                    route_open_reverse_requests: None,
8367                })
8368                .await
8369        });
8370        let sibling_request = receiver.recv().await.unwrap();
8371        let reverse_body = serde_json::to_vec(&serde_json::json!({
8372            "method": "sampling/createMessage",
8373            "params": {}
8374        }))
8375        .unwrap();
8376        assert!(
8377            dispatch_frame(&shared, 1, reverse_request_frame(handle, 802, reverse_body),).await
8378        );
8379        assert!(
8380            dispatch_frame(
8381                &shared,
8382                1,
8383                response_frame(
8384                    handle.channel,
8385                    handle.epoch,
8386                    sibling_request.frame.header.corr,
8387                    b"ok".to_vec(),
8388                ),
8389            )
8390            .await
8391        );
8392        assert!(matches!(
8393            sibling.await.unwrap().unwrap(),
8394            TerminalFrame::Response { body, .. } if body == b"ok"
8395        ));
8396        let refusal = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
8397            .await
8398            .unwrap()
8399            .unwrap()
8400            .frame;
8401        assert_eq!(refusal.header.ty, FrameType::Error);
8402        let error: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
8403        assert_eq!(error.code, REVERSE_REQUEST_UNHANDLED);
8404        assert!(error.message.contains("person prompt exploded"));
8405        assert!(shared.generation_is_current(1));
8406        release_reverse_request_registry(handle);
8407    }
8408
8409    fn reservation_stand_in(
8410        credit: usize,
8411        capacity: usize,
8412    ) -> (
8413        Arc<Shared>,
8414        SubcConsumer,
8415        mpsc::Receiver<WriteCommand>,
8416        RouteHandle,
8417        Arc<Semaphore>,
8418    ) {
8419        let shared = writer_test_shared();
8420        let (writer, rx) = mpsc::channel(capacity);
8421        shared.lock_inner().writer = Some(writer);
8422        shared.lock_inner().daemon_ver = "0.39.0".into();
8423        let handle = RouteHandle::new(5, 3, 1);
8424        let sem = Arc::new(Semaphore::new(credit));
8425        shared
8426            .install_one_shot_route(RouteState {
8427                handle,
8428                sem: Arc::clone(&sem),
8429                watch_sem: None,
8430                opted_in: false,
8431            })
8432            .unwrap();
8433        let consumer = SubcConsumer {
8434            shared: Arc::clone(&shared),
8435        };
8436        (shared, consumer, rx, handle, sem)
8437    }
8438
8439    #[tokio::test]
8440    async fn reservation_send_is_synchronous_and_uses_prevalidated_body() {
8441        let oversized = vec![0; subc_protocol::MAX_FRAME_BODY_LEN as usize + 1];
8442        assert!(matches!(
8443            RequestBody::new(oversized),
8444            Err(CallError::NotSent(_))
8445        ));
8446        let body = RequestBody::new(b"valid".to_vec()).unwrap();
8447        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8448        let reserved = consumer
8449            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8450            .await
8451            .unwrap();
8452        let corr = reserved.correlation_id();
8453        assert_eq!(shared.lock_inner().writer.as_ref().unwrap().capacity(), 0);
8454        assert!(rx.try_recv().is_err());
8455
8456        // A concrete tuple proves send returns without awaiting. Inspect the
8457        // writer queue before running the writer or polling PendingReply.
8458        let (sent_corr, reply): (CorrelationId, PendingReply) =
8459            reserved.send(body, CallOptions::default());
8460        assert_eq!(sent_corr, corr);
8461        let command = rx.try_recv().expect("send must enqueue without yielding");
8462        assert_eq!(command.frame.body, b"valid");
8463        assert_eq!(command.frame.header.corr, corr);
8464        assert_eq!(sem.available_permits(), 0);
8465        assert!(shared.mark_pending_accepted(command.pending.unwrap()));
8466        dispatch_frame(
8467            &shared,
8468            1,
8469            response_frame(handle.channel, handle.epoch, corr, b"reply".to_vec()),
8470        )
8471        .await;
8472        assert_eq!(reply.await.unwrap(), b"reply");
8473        assert_eq!(sem.available_permits(), 1);
8474        consumer.close().await;
8475    }
8476
8477    #[tokio::test]
8478    async fn pending_reply_classifies_established_route_error() {
8479        for (body, route_dead) in established_route_errors() {
8480            let (shared, consumer, mut rx, handle, _) = reservation_stand_in(1, 1);
8481            let reserved = consumer
8482                .reserve(&handle, Instant::now() + Duration::from_secs(1))
8483                .await
8484                .unwrap();
8485            let (_, reply) = reserved.send(
8486                RequestBody::new(b"request".to_vec()).unwrap(),
8487                CallOptions::default(),
8488            );
8489            let request = rx.recv().await.unwrap().frame;
8490            assert!(dispatch_frame(&shared, 1, route_error(&request, &body, route_dead)).await);
8491            let error = reply.await.unwrap_err();
8492            assert_eq!(error.is_route_dead(), route_dead, "{error:?}");
8493            assert_eq!(error.code(), Some(body.code.as_str()));
8494            match error {
8495                CallError::RouteDead(received) if route_dead => assert_eq!(*received, body),
8496                CallError::Module(received) if !route_dead => assert_eq!(received, body),
8497                other => panic!("unexpected call error: {other:?}"),
8498            }
8499        }
8500    }
8501
8502    #[tokio::test]
8503    async fn reservation_drop_releases_route_credit_and_writer_capacity_without_sending() {
8504        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8505        let deadline = Instant::now() + Duration::from_secs(1);
8506        let first = consumer.reserve(&handle, deadline).await.unwrap();
8507        let second = consumer.reserve(&handle, deadline);
8508        tokio::pin!(second);
8509        assert_pending(second.as_mut()).await;
8510        assert_eq!(sem.available_permits(), 0);
8511        drop(first);
8512        let second = timeout_at(deadline, second).await.unwrap().unwrap();
8513        drop(second);
8514        assert_eq!(sem.available_permits(), 1);
8515        assert_eq!(shared.lock_inner().writer.as_ref().unwrap().capacity(), 1);
8516        assert!(shared.lock_inner().pending.is_empty());
8517        assert!(rx.try_recv().is_err());
8518        consumer.close().await;
8519    }
8520
8521    #[tokio::test]
8522    async fn reservation_route_closed_before_send_matches_an_ordinary_unwritten_request() {
8523        let (shared, consumer, mut rx, handle, _) = reservation_stand_in(2, 4);
8524        let reserved = consumer
8525            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8526            .await
8527            .unwrap();
8528        let ordinary = consumer.request(&handle, b"ordinary".to_vec(), CallOptions::default());
8529        tokio::pin!(ordinary);
8530        assert_pending(ordinary.as_mut()).await;
8531        let ordinary_command = rx.try_recv().unwrap();
8532        assert_eq!(ordinary_command.frame.body, b"ordinary");
8533        consumer
8534            .close_handle(&handle, CloseRouteOptions::default())
8535            .await
8536            .unwrap();
8537        let (_, reply) = reserved.send(
8538            RequestBody::new(b"reserved".to_vec()).unwrap(),
8539            CallOptions::default(),
8540        );
8541        let ordinary_error = ordinary.await.unwrap_err();
8542        let reserved_error = reply.await.unwrap_err();
8543        assert!(matches!(reserved_error, CallError::NotSent(_)));
8544        assert_eq!(
8545            reserved_error.close_reason(),
8546            Some(&RouteEndReason::ClosedByCaller)
8547        );
8548        assert_eq!(reserved_error.to_string(), ordinary_error.to_string());
8549        assert_eq!(reserved_error.close_reason(), ordinary_error.close_reason());
8550
8551        rx.close();
8552        let writer = InstrumentedWriter::new(false);
8553        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8554        let bytes = writer.bytes();
8555        let mut bytes = bytes.as_slice();
8556        let frame = read_frame(&mut bytes).await.unwrap().unwrap();
8557        assert_eq!(frame.header.ty, FrameType::Goodbye);
8558        assert!(
8559            bytes.is_empty(),
8560            "the closed route's reserved request must not be written"
8561        );
8562        consumer.close().await;
8563    }
8564
8565    #[tokio::test]
8566    async fn reservation_connection_loss_after_send_preserves_existing_errors() {
8567        for written in [false, true] {
8568            let (shared, consumer, rx, handle, sem) = reservation_stand_in(1, 1);
8569            let reserved = consumer
8570                .reserve(&handle, Instant::now() + Duration::from_secs(1))
8571                .await
8572                .unwrap();
8573            let (_, reply) = reserved.send(
8574                RequestBody::new(b"request".to_vec()).unwrap(),
8575                CallOptions::default(),
8576            );
8577            let writer = InstrumentedWriter::new(written);
8578            if !written {
8579                shared.handle_generation_drop(1, "connection lost before dequeue".to_string());
8580            }
8581            writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8582            let err = reply.await.unwrap_err();
8583            assert_eq!(err.close_reason(), Some(&RouteEndReason::ConnectionLost));
8584            if written {
8585                // `outcome_cause` answers only for `OutcomeUnknown`, so this also
8586                // checks the variant without adding a spelling the
8587                // outcome_unknown_inventory test would have to count.
8588                assert_eq!(err.outcome_cause(), Some(OutcomeUnknownCause::WriterClosed));
8589                assert!(!writer.bytes().is_empty());
8590            } else {
8591                assert!(matches!(err, CallError::NotSent(_)));
8592                assert!(writer.bytes().is_empty());
8593            }
8594            assert_eq!(sem.available_permits(), 1);
8595            consumer.close().await;
8596        }
8597    }
8598
8599    #[tokio::test]
8600    async fn reservation_correlations_are_unique_and_match_frames_written_out_of_order() {
8601        let (shared, consumer, mut rx, handle, _) = reservation_stand_in(3, 3);
8602        let deadline = Instant::now() + Duration::from_secs(1);
8603        let first = consumer.reserve(&handle, deadline).await.unwrap();
8604        let second = consumer.reserve(&handle, deadline).await.unwrap();
8605        let third = consumer.reserve(&handle, deadline).await.unwrap();
8606        let ids = [
8607            first.correlation_id(),
8608            second.correlation_id(),
8609            third.correlation_id(),
8610        ];
8611        assert_eq!(ids.into_iter().collect::<HashSet<_>>().len(), 3);
8612        let opts = CallOptions {
8613            priority: Priority::Background,
8614            admission_class: AdmissionClass::Expedite,
8615            ..CallOptions::default()
8616        };
8617        let mut replies = Vec::new();
8618        for (reserved, expected_id, body) in [
8619            (third, ids[2], "third"),
8620            (first, ids[0], "first"),
8621            (second, ids[1], "second"),
8622        ] {
8623            let (corr, reply) = reserved.send(
8624                RequestBody::new(body.as_bytes().to_vec()).unwrap(),
8625                opts.clone(),
8626            );
8627            assert_eq!(corr, expected_id);
8628            replies.push((corr, body, reply));
8629        }
8630        rx.close();
8631        let writer = InstrumentedWriter::new(false);
8632        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8633        let bytes = writer.bytes();
8634        let mut bytes = bytes.as_slice();
8635        for (corr, body, reply) in replies {
8636            let frame = read_frame(&mut bytes).await.unwrap().unwrap();
8637            assert_eq!(frame.header.ty, FrameType::Request);
8638            assert_eq!(frame.header.corr, corr);
8639            assert_eq!(frame.header.channel, handle.channel);
8640            assert_eq!(frame.header.epoch, handle.epoch);
8641            assert_eq!(
8642                frame.header.flags,
8643                Flags::new(false, Priority::Background, false)
8644                    .with_admission_class(AdmissionClass::Expedite)
8645            );
8646            assert_eq!(frame.body, body.as_bytes());
8647            dispatch_frame(
8648                &shared,
8649                1,
8650                response_frame(handle.channel, handle.epoch, corr, body.as_bytes().to_vec()),
8651            )
8652            .await;
8653            assert_eq!(reply.await.unwrap(), body.as_bytes());
8654        }
8655        assert!(bytes.is_empty());
8656        consumer.close().await;
8657    }
8658
8659    #[tokio::test(start_paused = true)]
8660    async fn reservation_deadline_before_send_prevents_writing_without_polling_reply() {
8661        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8662        let reserved = consumer
8663            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8664            .await
8665            .unwrap();
8666        tokio::time::advance(Duration::from_secs(2)).await;
8667        let (_, reply) = reserved.send(
8668            RequestBody::new(b"expired".to_vec()).unwrap(),
8669            CallOptions::default(),
8670        );
8671        rx.close();
8672        let writer = InstrumentedWriter::new(false);
8673        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8674        assert!(writer.bytes().is_empty());
8675        assert!(matches!(reply.await, Err(CallError::NotSent(_))));
8676        assert_eq!(sem.available_permits(), 1);
8677        consumer.close().await;
8678    }
8679
8680    #[tokio::test(start_paused = true)]
8681    async fn reservation_deadline_bounds_writer_capacity_and_releases_credit() {
8682        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(2, 1);
8683        let first = consumer
8684            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8685            .await
8686            .unwrap();
8687        let second = consumer
8688            .reserve(&handle, Instant::now() + Duration::from_millis(25))
8689            .await;
8690        assert!(matches!(second, Err(CallError::NotSent(_))));
8691        assert_eq!(sem.available_permits(), 1);
8692        drop(first);
8693        assert_eq!(sem.available_permits(), 2);
8694        assert!(shared.lock_inner().pending.is_empty());
8695        assert!(rx.try_recv().is_err());
8696        consumer.close().await;
8697    }
8698
8699    #[tokio::test]
8700    async fn reservation_reconnect_during_writer_capacity_wait_fails_promptly_without_writing() {
8701        let (shared, consumer, mut old_rx, handle, sem) = reservation_stand_in(1, 1);
8702        let old_writer = shared.lock_inner().writer.clone().unwrap();
8703        let held_capacity = old_writer.reserve_owned().await.unwrap();
8704        let reserve = consumer.reserve(&handle, Instant::now() + Duration::from_secs(60));
8705        tokio::pin!(reserve);
8706        assert_pending(reserve.as_mut()).await;
8707        assert_eq!(sem.available_permits(), 0);
8708
8709        let mut replacement_rx = drop_and_replace_test_transport(&shared);
8710        assert_ne!(shared.lock_inner().generation, handle.connection_token());
8711        drop(held_capacity);
8712        let result = std::future::poll_fn(|cx| Poll::Ready(reserve.as_mut().poll(cx))).await;
8713        assert!(matches!(
8714            result,
8715            Poll::Ready(Err(CallError::StaleRouteHandle(stale))) if stale == handle
8716        ));
8717        assert!(shared.lock_inner().pending.is_empty());
8718        assert_eq!(sem.available_permits(), 1);
8719        assert!(old_rx.try_recv().is_err());
8720        assert!(replacement_rx.try_recv().is_err());
8721
8722        old_rx.close();
8723        replacement_rx.close();
8724        let writer = InstrumentedWriter::new(false);
8725        writer_loop(
8726            Arc::clone(&shared),
8727            writer.clone(),
8728            old_rx,
8729            handle.connection_token(),
8730        )
8731        .await;
8732        let generation = shared.lock_inner().generation;
8733        writer_loop(
8734            Arc::clone(&shared),
8735            writer.clone(),
8736            replacement_rx,
8737            generation,
8738        )
8739        .await;
8740        assert!(writer.bytes().is_empty());
8741        consumer.close().await;
8742    }
8743
8744    #[tokio::test]
8745    async fn reservation_reply_drop_cleans_up_without_polling() {
8746        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8747        let reserved = consumer
8748            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8749            .await
8750            .unwrap();
8751        let (_, reply) = reserved.send(
8752            RequestBody::new(b"request".to_vec()).unwrap(),
8753            CallOptions::default(),
8754        );
8755        drop(reply);
8756        assert!(shared.lock_inner().pending.is_empty());
8757        assert_eq!(sem.available_permits(), 1);
8758        rx.close();
8759        let writer = InstrumentedWriter::new(false);
8760        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8761        assert!(writer.bytes().is_empty());
8762        consumer.close().await;
8763    }
8764
8765    #[tokio::test]
8766    async fn writer_batches_ready_frames_into_one_flush() {
8767        const FRAME_COUNT: usize = 8;
8768
8769        let shared = writer_test_shared();
8770        let (live_writer, _live_rx) = mpsc::channel(1);
8771        let (tx, rx) = mpsc::channel(FRAME_COUNT + 1);
8772        let instrumented = InstrumentedWriter::new(false);
8773        let observer = instrumented.clone();
8774        let mut expected = Vec::with_capacity(FRAME_COUNT);
8775        let mut keys = Vec::with_capacity(FRAME_COUNT);
8776
8777        {
8778            let mut inner = shared.lock_inner();
8779            inner.writer = Some(live_writer);
8780            inner.daemon_ver = "0.39.0".into();
8781            for index in 0..FRAME_COUNT {
8782                let corr = index as u64 + 1;
8783                let frame = response_frame(7, 1, corr, vec![index as u8; index + 1]);
8784                let key = PendingKey {
8785                    generation: 1,
8786                    channel: 7,
8787                    epoch: 1,
8788                    corr,
8789                };
8790                let (pending_tx, _pending_rx) = oneshot::channel();
8791                inner
8792                    .pending
8793                    .insert(key, PendingEntry::unary(pending_tx, false, None, None));
8794                expected.push(frame.clone());
8795                keys.push(key);
8796                tx.try_send(WriteCommand {
8797                    frame,
8798                    pending: Some(key),
8799                })
8800                .expect("the burst should fit in the writer queue");
8801                if index == 0 {
8802                    tx.try_send(WriteCommand {
8803                        frame: response_frame(7, 1, 999, b"skip".to_vec()),
8804                        pending: Some(PendingKey {
8805                            generation: 1,
8806                            channel: 7,
8807                            epoch: 1,
8808                            corr: 999,
8809                        }),
8810                    })
8811                    .expect("the skipped command should fit in the writer queue");
8812                }
8813            }
8814        }
8815        drop(tx);
8816
8817        writer_loop(Arc::clone(&shared), instrumented, rx, 1).await;
8818
8819        {
8820            let inner = shared.lock_inner();
8821            for key in keys {
8822                assert!(
8823                    inner.pending.get(&key).is_some_and(|entry| entry.accepted),
8824                    "every written command must be marked accepted"
8825                );
8826            }
8827        }
8828
8829        let mut wire = std::io::Cursor::new(observer.bytes());
8830        for expected_frame in expected {
8831            let actual = read_frame(&mut wire)
8832                .await
8833                .expect("the emitted frame should decode")
8834                .expect("the emitted frame should be present");
8835            assert_eq!(actual, expected_frame);
8836        }
8837        assert!(
8838            read_frame(&mut wire)
8839                .await
8840                .expect("the end of the emitted burst should be clean")
8841                .is_none(),
8842            "the writer must not emit extra frames"
8843        );
8844
8845        let flush_count = observer.flush_count();
8846        assert_eq!(
8847            flush_count, 1,
8848            "a ready burst must be coalesced into one flush"
8849        );
8850        shared.close_sync("test complete");
8851    }
8852
8853    #[tokio::test]
8854    async fn writer_flush_failure_drops_generation_and_preserves_acceptance_classification() {
8855        let shared = writer_test_shared();
8856        let (live_writer, _live_rx) = mpsc::channel(1);
8857        let accepted_key = PendingKey {
8858            generation: 1,
8859            channel: 3,
8860            epoch: 1,
8861            corr: 1,
8862        };
8863        let not_sent_key = PendingKey {
8864            corr: 2,
8865            ..accepted_key
8866        };
8867        let (accepted_tx, accepted_rx) = oneshot::channel();
8868        let (not_sent_tx, not_sent_rx) = oneshot::channel();
8869        {
8870            let mut inner = shared.lock_inner();
8871            inner.writer = Some(live_writer);
8872            inner.daemon_ver = "0.39.0".into();
8873            inner.pending.insert(
8874                accepted_key,
8875                PendingEntry::unary(accepted_tx, false, None, None),
8876            );
8877            inner.pending.insert(
8878                not_sent_key,
8879                PendingEntry::unary(not_sent_tx, false, None, None),
8880            );
8881        }
8882
8883        let (tx, rx) = mpsc::channel(1);
8884        tx.send(WriteCommand {
8885            frame: response_frame(3, 1, accepted_key.corr, b"accepted".to_vec()),
8886            pending: Some(accepted_key),
8887        })
8888        .await
8889        .unwrap();
8890        drop(tx);
8891
8892        writer_loop(Arc::clone(&shared), InstrumentedWriter::new(true), rx, 1).await;
8893
8894        assert!(
8895            shared.lock_inner().writer.is_none(),
8896            "a flush failure must drop the active generation"
8897        );
8898        let accepted_error = accepted_rx
8899            .await
8900            .expect("the accepted request should be settled")
8901            .into_call_result()
8902            .unwrap_err();
8903        assert!(matches!(accepted_error, CallError::OutcomeUnknown(_)));
8904        assert_eq!(
8905            accepted_error.outcome_cause(),
8906            Some(OutcomeUnknownCause::WriterClosed)
8907        );
8908        let not_sent_error = not_sent_rx
8909            .await
8910            .expect("the unwritten request should be settled")
8911            .into_call_result()
8912            .unwrap_err();
8913        assert!(matches!(not_sent_error, CallError::NotSent(_)));
8914        assert_eq!(not_sent_error.outcome_cause(), None);
8915        shared.close_sync("test complete");
8916    }
8917
8918    #[tokio::test]
8919    async fn consumer_close_attaches_outcome_cause_to_pending_call() {
8920        let shared = writer_test_shared();
8921        let (writer, _writer_rx) = mpsc::channel(1);
8922        shared.lock_inner().writer = Some(writer);
8923        shared.lock_inner().daemon_ver = "0.39.0".into();
8924        let (tx, rx) = oneshot::channel();
8925        let mut entry = PendingEntry::unary(tx, false, None, None);
8926        entry.accepted = true;
8927        shared.lock_inner().pending.insert(
8928            PendingKey {
8929                generation: 1,
8930                channel: 3,
8931                epoch: 1,
8932                corr: 1,
8933            },
8934            entry,
8935        );
8936        let consumer = SubcConsumer { shared };
8937        consumer.close().await;
8938        let err = rx.await.unwrap().into_call_result().unwrap_err();
8939        assert_eq!(
8940            err.outcome_cause(),
8941            Some(OutcomeUnknownCause::ConsumerClosed)
8942        );
8943        assert_eq!(err.to_string(), "request outcome unknown: consumer closed");
8944        assert_eq!(err.close_reason(), None);
8945    }
8946
8947    #[tokio::test]
8948    async fn subscription_completion_drop_attaches_outcome_cause() {
8949        let (tx, rx) = oneshot::channel();
8950        let closed = SubscriptionClosed { rx };
8951        drop(tx);
8952        let err = closed.await.unwrap_err();
8953        assert_eq!(
8954            err.outcome_cause(),
8955            Some(OutcomeUnknownCause::CompletionFailed)
8956        );
8957        assert_eq!(
8958            err.to_string(),
8959            "request outcome unknown: subscription closed result channel dropped"
8960        );
8961    }
8962
8963    #[test]
8964    fn reconnect_classifier_treats_auth_failure_as_transient() {
8965        // Key rotation across a daemon restart on the fixed port: a client racing
8966        // the restart reads the pre-rotation file, connects, and fails the proof.
8967        // That must be retryable — each retry re-reads the file, so the next
8968        // attempt picks up the rotated key. Treating it as a permanent impostor
8969        // verdict would turn every daemon restart into a permanent client wedge.
8970        let auth = ConsumerError::Auth {
8971            path: PathBuf::from("/tmp/subc-connection.json"),
8972            endpoint: "127.0.0.1:8757".to_string(),
8973            source: subc_transport::AuthError::InvalidServerProof,
8974        };
8975        assert!(is_reconnect_transient(&auth), "rotation race must retry");
8976
8977        // Absent file mid-restart stays transient; malformed file stays permanent.
8978        let absent = ConsumerError::ConnectionFile {
8979            path: PathBuf::from("/tmp/subc-connection.json"),
8980            source: ConnectionFileError::Io {
8981                op: "read",
8982                path: PathBuf::from("/tmp/subc-connection.json"),
8983                source: io::Error::new(io::ErrorKind::NotFound, "gone"),
8984            },
8985        };
8986        assert!(is_reconnect_transient(&absent));
8987    }
8988
8989    #[tokio::test]
8990    async fn newer_drop_supersedes_reconnect_and_ignores_stale_completion() {
8991        let shared = Arc::new(reader_skew_tests::legacy_shared(
8992            PathBuf::from("/tmp/does-not-exist"),
8993            ConsumerOptions::default(),
8994        ));
8995        let stale_task = tokio::spawn(std::future::pending::<()>());
8996        {
8997            let mut inner = shared.lock_inner();
8998            inner.generation = 2;
8999            inner.reconnect = ReconnectState::Background {
9000                generation: 1,
9001                task: stale_task,
9002            };
9003        }
9004
9005        assert!(shared.spawn_reconnect(2));
9006        assert!(matches!(
9007            &shared.lock_inner().reconnect,
9008            ReconnectState::Background { generation, .. } if *generation == 2
9009        ));
9010
9011        shared.finish_background_reconnect(1);
9012        assert!(matches!(
9013            &shared.lock_inner().reconnect,
9014            ReconnectState::Background { generation, .. } if *generation == 2
9015        ));
9016        shared.close_sync("test complete");
9017    }
9018
9019    #[test]
9020    fn retryable_route_open_codes_are_code_specific() {
9021        for code in [
9022            "module_reloading",
9023            "module_warming",
9024            "target_unavailable",
9025            "module_timeout",
9026        ] {
9027            assert!(is_retryable_route_open_code(code), "{code} should retry");
9028        }
9029        // "No module of this id is registered or supervised here" is a typo or
9030        // an undeployed peer: the daemon reports a configured-but-late target
9031        // with module_warming/target_unavailable, so retrying unknown_module
9032        // in place only papers over an unsupervised module's HELLO race.
9033        assert!(
9034            !is_retryable_route_open_code(error_codes::UNKNOWN_MODULE),
9035            "unknown_module is terminal"
9036        );
9037        assert!(!is_retryable_route_open_code(error_codes::MODULE_REMOVED));
9038        assert!(!is_retryable_route_open_code("invalid_project_root"));
9039        assert!(!is_retryable_route_open_code("route_rejected"));
9040        assert!(
9041            !is_retryable_route_open_code("capability_forbidden"),
9042            "a capability policy refusal must not enter the route.open retry set"
9043        );
9044    }
9045
9046    #[test]
9047    fn two_routes_record_distinct_reasons_and_reuse_clears_channel() {
9048        let shared = Arc::new(reader_skew_tests::legacy_shared(
9049            PathBuf::new(),
9050            ConsumerOptions::default(),
9051        ));
9052        let (writer, _rx) = mpsc::channel(8);
9053        shared.lock_inner().writer = Some(writer);
9054        shared.lock_inner().daemon_ver = "0.39.0".into();
9055        shared.install_ingress_handle(RouteHandle::new(7, 1, 1));
9056        shared.install_ingress_handle(RouteHandle::new(9, 1, 1));
9057        {
9058            let mut inner = shared.lock_inner();
9059            inner.route_modules.insert(7, "provider".into());
9060            inner.route_modules.insert(9, "provider".into());
9061        }
9062        shared.control_push(br#"{"op":"route.closed","module_id":"provider","channels":[7],"reason":"scope_ended"}"#);
9063        shared.control_push(
9064            br#"{"op":"route.closing","module_id":"provider","channels":[9],"reason":"restart"}"#,
9065        );
9066        shared.control_push(
9067            br#"{"op":"route.closing","module_id":"provider","channels":[7],"reason":"crash"}"#,
9068        );
9069        assert_eq!(
9070            shared.lock_inner().route_end_reason(7),
9071            RouteEndReason::Daemon(RouteCloseReason::ScopeEnded)
9072        );
9073        assert_eq!(
9074            shared.lock_inner().route_end_reason(9),
9075            RouteEndReason::Daemon(RouteCloseReason::Restart)
9076        );
9077        shared.control_push(
9078            br#"{"op":"route.closed","module_id":"provider","channels":[9],"reason":"crash"}"#,
9079        );
9080        assert_eq!(
9081            shared.lock_inner().route_end_reason(9),
9082            RouteEndReason::Daemon(RouteCloseReason::Crash)
9083        );
9084        shared.control_push(br#"{"op":"route.closed","module_id":"provider","reason":"disable"}"#);
9085        shared.install_ingress_handle(RouteHandle::new(7, 2, 1));
9086        assert_eq!(
9087            shared.lock_inner().route_end_reason(7),
9088            RouteEndReason::Unknown
9089        );
9090        assert_eq!(shared.lock_inner().route_end(7).terminal, None);
9091    }
9092
9093    #[test]
9094    fn legacy_route_push_falls_back_only_when_channels_are_absent() {
9095        let shared = reader_skew_tests::legacy_shared(PathBuf::new(), ConsumerOptions::default());
9096        shared
9097            .lock_inner()
9098            .route_modules
9099            .insert(7, "provider".into());
9100        shared.control_push(
9101            br#"{"op":"route.closed","module_id":"provider","channels":[],"reason":"crash"}"#,
9102        );
9103        assert_eq!(
9104            shared.lock_inner().route_end_reason(7),
9105            RouteEndReason::Unknown
9106        );
9107        shared.control_push(br#"{"op":"route.closing","module_id":"provider","reason":"restart"}"#);
9108        assert_eq!(
9109            shared.lock_inner().route_end_reason(7),
9110            RouteEndReason::Daemon(RouteCloseReason::Restart)
9111        );
9112        shared.control_push(br#"{"op":"route.closed","module_id":"provider","reason":"crash"}"#);
9113        assert_eq!(
9114            shared.lock_inner().route_end_reason(7),
9115            RouteEndReason::Daemon(RouteCloseReason::Crash)
9116        );
9117    }
9118
9119    #[tokio::test]
9120    async fn sdk_teardown_paths_attach_caller_and_connection_loss_reasons() {
9121        for local in [true, false] {
9122            let shared = Arc::new(reader_skew_tests::legacy_shared(
9123                PathBuf::new(),
9124                ConsumerOptions::default(),
9125            ));
9126            let (writer, _writer_rx) = mpsc::channel(8);
9127            shared.lock_inner().writer = Some(writer);
9128            shared.lock_inner().daemon_ver = "0.39.0".into();
9129            let handle = RouteHandle::new(7, 1, 1);
9130            shared.install_ingress_handle(handle);
9131            let (tx, rx) = oneshot::channel();
9132            let mut entry = PendingEntry::unary(tx, false, None, None);
9133            entry.accepted = true;
9134            shared.lock_inner().pending.insert(
9135                PendingKey {
9136                    generation: 1,
9137                    channel: 7,
9138                    epoch: 1,
9139                    corr: 1,
9140                },
9141                entry,
9142            );
9143            if local {
9144                shared
9145                    .close_handle(handle, &CloseRouteOptions::default())
9146                    .await
9147                    .unwrap();
9148            } else {
9149                shared.handle_generation_drop(1, "connection gone".into());
9150            }
9151            let err = rx.await.unwrap().into_call_result().err().unwrap();
9152            assert!(matches!(err, CallError::OutcomeUnknown(_)));
9153            assert_eq!(
9154                err.outcome_cause(),
9155                Some(if local {
9156                    OutcomeUnknownCause::RouteEnded
9157                } else {
9158                    OutcomeUnknownCause::ConnectionFailed
9159                })
9160            );
9161            let shared_failure = SharedCallFailure::from(err);
9162            let err = shared_failure.into_call_error();
9163            assert_eq!(
9164                err.close_reason(),
9165                Some(&if local {
9166                    RouteEndReason::ClosedByCaller
9167                } else {
9168                    RouteEndReason::ConnectionLost
9169                })
9170            );
9171            shared.close_sync("test complete");
9172        }
9173    }
9174
9175    #[tokio::test]
9176    async fn route_end_reasons_preserve_pending_retry_classes() {
9177        for reason in [
9178            RouteEndReason::ClosedByCaller,
9179            RouteEndReason::ConnectionLost,
9180            RouteEndReason::Daemon(RouteCloseReason::ScopeEnded),
9181            RouteEndReason::Unknown,
9182        ] {
9183            for accepted in [false, true] {
9184                let (tx, rx) = oneshot::channel();
9185                let mut entry = PendingEntry::unary(tx, false, None, None);
9186                entry.accepted = accepted;
9187                settle_route_pending_entries(vec![entry], "route ended".into(), reason.clone());
9188                let err = rx.await.unwrap().into_call_result().err().unwrap();
9189                assert_eq!(err.close_reason(), Some(&reason));
9190                assert_eq!(err.terminal(), None);
9191                assert_eq!(matches!(err, CallError::OutcomeUnknown(_)), accepted);
9192                assert_eq!(matches!(err, CallError::NotSent(_)), !accepted);
9193            }
9194        }
9195    }
9196
9197    #[test]
9198    fn route_closing_does_not_supply_or_overwrite_a_terminal_verdict() {
9199        let shared = Shared::new(PathBuf::new(), ConsumerOptions::default());
9200        shared.control_push(
9201            br#"{"op":"route.closing","channels":[7],"reason":"restart","terminal":true}"#,
9202        );
9203        assert_eq!(shared.lock_inner().route_end(7).terminal, None);
9204        shared.control_push(
9205            br#"{"op":"route.closed","channels":[7],"reason":"restart","terminal":false}"#,
9206        );
9207        shared.control_push(
9208            br#"{"op":"route.closing","channels":[7],"reason":"restart","terminal":true}"#,
9209        );
9210        assert_eq!(shared.lock_inner().route_end(7).terminal, Some(false));
9211        assert_eq!(CallError::not_sent("not a route end").terminal(), None);
9212    }
9213
9214    #[test]
9215    fn route_close_reason_classifier_accepts_capability_denied_and_fails_closed_for_unknown() {
9216        assert_eq!(
9217            RouteCloseReason::from_wire("capability_denied"),
9218            RouteCloseReason::CapabilityDenied
9219        );
9220        assert_eq!(
9221            RouteCloseReason::from_wire("capability_denied").disposition(),
9222            RouteCloseDisposition::MustNotReopen
9223        );
9224        assert_eq!(
9225            RouteCloseReason::from_wire("future_policy_reason").disposition(),
9226            RouteCloseDisposition::MustNotReopen,
9227            "an unknown close reason must receive the strictest handling"
9228        );
9229        assert_eq!(
9230            RouteCloseReason::from_wire("reload").disposition(),
9231            RouteCloseDisposition::MayReopen,
9232            "control proves the classifier can distinguish a conservative default"
9233        );
9234    }
9235
9236    #[tokio::test]
9237    async fn module_removed_fails_fast_while_module_reloading_retries_at_the_same_route_open_call_site(
9238    ) {
9239        // Serves rejections with `code` until the caller settles, returning
9240        // (attempts_served, result). The retryable arm must keep retrying past
9241        // any attempt count until the DEADLINE binds — the attempt cap in the
9242        // options below is deliberately tiny so a regression that re-couples
9243        // attempts into the retry condition (the 3.1s-effective-budget defect)
9244        // stops the loop at 2 and fails the `> 2` assertion by name.
9245        async fn reject_route_open_attempts(code: &str, deadline: Duration) -> (usize, CallError) {
9246            let shared = Arc::new(reader_skew_tests::legacy_shared(
9247                PathBuf::from("/tmp/does-not-exist"),
9248                ConsumerOptions::default(),
9249            ));
9250            let (writer, mut receiver) = mpsc::channel(4);
9251            {
9252                let mut inner = shared.lock_inner();
9253                inner.writer = Some(writer);
9254                inner.daemon_ver = "0.39.0".into();
9255            }
9256            let consumer = SubcConsumer {
9257                shared: Arc::clone(&shared),
9258            };
9259            let target = RouteTarget::ToolProvider {
9260                module_id: "retry-polarity".to_string(),
9261            };
9262            let identity = BindIdentity::new("test".to_string(), code.to_string());
9263            let options = CallOptions {
9264                timeout: Duration::from_secs(2),
9265                route_retry: RetryBackoff {
9266                    base: Duration::ZERO,
9267                    cap: Duration::ZERO,
9268                    max_attempts: 2,
9269                },
9270                route_retry_deadline: deadline,
9271                ..CallOptions::default()
9272            };
9273            let mut task =
9274                tokio::spawn(async move { consumer.open_route(target, identity, options).await });
9275
9276            let mut attempts = 0usize;
9277            let result = loop {
9278                tokio::select! {
9279                    command = receiver.recv() => {
9280                        // The consumer tears the writer down when the open
9281                        // settles, so a closed channel here means the task is
9282                        // finishing — join it rather than treating the race as
9283                        // a broken harness.
9284                        let Some(command) = command else {
9285                            break task.await.unwrap().expect_err("route.open must reject");
9286                        };
9287                        attempts += 1;
9288                        let body =
9289                            serde_json::to_vec(&ErrorBody::new(code, "test rejection")).unwrap();
9290                        assert!(
9291                            dispatch_frame(
9292                                &shared,
9293                                1,
9294                                Frame::build(
9295                                    FrameType::Error,
9296                                    Flags::new(false, Priority::Interactive, false),
9297                                    0,
9298                                    0,
9299                                    command.frame.header.corr,
9300                                    body,
9301                                )
9302                                .unwrap(),
9303                            )
9304                            .await
9305                        );
9306                    }
9307                    joined = &mut task => {
9308                        break joined.unwrap().expect_err("route.open must reject");
9309                    }
9310                }
9311            };
9312            assert!(
9313                receiver.try_recv().is_err(),
9314                "a settled route.open must not queue another attempt"
9315            );
9316            (attempts, result)
9317        }
9318
9319        let (reloading_attempts, reloading) =
9320            reject_route_open_attempts(error_codes::MODULE_RELOADING, Duration::from_millis(150))
9321                .await;
9322        assert!(matches!(reloading, CallError::NotSent(_)));
9323        assert!(
9324            reloading_attempts > 2,
9325            "reloading retries must run until the deadline, not an attempt cap \
9326             (served {reloading_attempts} attempts against max_attempts=2)"
9327        );
9328
9329        let (removed_attempts, removed) =
9330            reject_route_open_attempts(error_codes::MODULE_REMOVED, Duration::from_millis(150))
9331                .await;
9332        assert!(matches!(removed, CallError::NotSent(_)));
9333        assert_eq!(
9334            removed_attempts, 1,
9335            "terminal codes settle on the first answer"
9336        );
9337    }
9338
9339    /// splitmix64 over a counter: a seeded stand-in for the consumer's random
9340    /// source, so jittered delays are reproducible.
9341    fn seeded_random(seed: u64) -> Box<dyn Fn() -> f64 + Send + Sync> {
9342        let state = AtomicU64::new(seed);
9343        Box::new(move || {
9344            let mut z = state
9345                .fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed)
9346                .wrapping_add(0x9E37_79B9_7F4A_7C15);
9347            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
9348            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
9349            z ^= z >> 31;
9350            (z >> 11) as f64 / (1u64 << 53) as f64
9351        })
9352    }
9353
9354    /// A consumer wired to an in-memory writer, standing in for a daemon that
9355    /// the test answers by hand.
9356    fn route_open_stand_in(
9357        random_unit: Box<dyn Fn() -> f64 + Send + Sync>,
9358    ) -> (Arc<Shared>, Arc<SubcConsumer>, mpsc::Receiver<WriteCommand>) {
9359        let mut shared = reader_skew_tests::legacy_shared(
9360            PathBuf::from("/tmp/does-not-exist"),
9361            ConsumerOptions::default(),
9362        );
9363        shared.random_unit = random_unit;
9364        let shared = Arc::new(shared);
9365        let (writer, receiver) = mpsc::channel(64);
9366        shared.lock_inner().writer = Some(writer);
9367        shared.lock_inner().daemon_ver = "0.39.0".into();
9368        let consumer = Arc::new(SubcConsumer {
9369            shared: Arc::clone(&shared),
9370        });
9371        (shared, consumer, receiver)
9372    }
9373
9374    fn restart_target(module_id: &str) -> RouteTarget {
9375        RouteTarget::ToolProvider {
9376            module_id: module_id.to_string(),
9377        }
9378    }
9379
9380    fn restart_identity() -> BindIdentity {
9381        BindIdentity::new("test".to_string(), "restart".to_string())
9382    }
9383
9384    /// The daemon's answer to one route.open: accept it on `channel`, or refuse
9385    /// it with `refusal`.
9386    fn route_open_answer(corr: u64, channel: u16, refusal: Option<ErrorBody>) -> Frame {
9387        match refusal {
9388            None => response_frame(
9389                0,
9390                0,
9391                corr,
9392                serde_json::to_vec(&ClientControlResponse::RouteOpen {
9393                    request_window: None,
9394                    watch_window: None,
9395                    route_channel: channel,
9396                    route_epoch: 1,
9397                })
9398                .unwrap(),
9399            ),
9400            Some(body) => Frame::build(
9401                FrameType::Error,
9402                Flags::new(false, Priority::Interactive, false),
9403                0,
9404                0,
9405                corr,
9406                serde_json::to_vec(&body).unwrap(),
9407            )
9408            .unwrap(),
9409        }
9410    }
9411
9412    /// Answer every route.open the consumer writes, as `answer` decides from the
9413    /// open's target module, until `task` finishes.
9414    async fn answer_route_opens<T>(
9415        shared: &Arc<Shared>,
9416        receiver: &mut mpsc::Receiver<WriteCommand>,
9417        task: &mut JoinHandle<T>,
9418        mut answer: impl FnMut(&str) -> Option<ErrorBody>,
9419    ) -> T {
9420        let mut next_channel = 40u16;
9421        loop {
9422            tokio::select! {
9423                command = receiver.recv() => {
9424                    let Some(command) = command else {
9425                        return (&mut *task).await.unwrap();
9426                    };
9427                    let request: serde_json::Value =
9428                        serde_json::from_slice(&command.frame.body).unwrap();
9429                    let module_id = request["target"]["module_id"].as_str().unwrap().to_string();
9430                    next_channel += 1;
9431                    let frame = route_open_answer(
9432                        command.frame.header.corr,
9433                        next_channel,
9434                        answer(&module_id),
9435                    );
9436                    assert!(dispatch_frame(shared, 1, frame).await);
9437                }
9438                joined = &mut *task => return joined.unwrap(),
9439            }
9440        }
9441    }
9442
9443    fn reloading() -> ErrorBody {
9444        ErrorBody::new(error_codes::MODULE_RELOADING, "module is reloading")
9445    }
9446
9447    fn drain_call<'a>(
9448        consumer: &'a SubcConsumer,
9449        body: &'static [u8],
9450    ) -> impl Future<Output = Result<Vec<u8>, CallError>> + 'a {
9451        consumer.call(
9452            restart_target("plexus"),
9453            restart_identity(),
9454            body.to_vec(),
9455            CallOptions {
9456                timeout: Duration::from_secs(5),
9457                ..CallOptions::default()
9458            },
9459        )
9460    }
9461
9462    async fn refuse_during_drain(shared: &Arc<Shared>, request: &Frame) {
9463        let frame = Frame::build(
9464            FrameType::Error,
9465            request.header.flags,
9466            request.header.channel,
9467            request.header.epoch,
9468            request.header.corr,
9469            serde_json::to_vec(&reloading()).unwrap(),
9470        )
9471        .unwrap();
9472        assert!(dispatch_frame(shared, 1, frame).await);
9473    }
9474
9475    async fn reply_to_drain_call(shared: &Arc<Shared>, request: Frame) {
9476        assert_eq!(request.header.ty, FrameType::Request);
9477        assert!(
9478            dispatch_frame(
9479                shared,
9480                1,
9481                response_frame(
9482                    request.header.channel,
9483                    request.header.epoch,
9484                    request.header.corr,
9485                    request.body,
9486                ),
9487            )
9488            .await
9489        );
9490    }
9491
9492    #[tokio::test(start_paused = true)]
9493    async fn shared_route_drain_delivers_both_refusals_and_resends_both_calls() {
9494        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9495        let (_, old) = open_answered(
9496            &shared,
9497            &consumer,
9498            &mut receiver,
9499            None,
9500            41,
9501            "initial shared route",
9502        )
9503        .await;
9504        let mut seed = Box::pin(drain_call(&consumer, b"seed"));
9505        assert_pending(seed.as_mut()).await;
9506        reply_to_drain_call(&shared, receiver.recv().await.unwrap().frame).await;
9507        assert_eq!(seed.await.unwrap(), b"seed");
9508        shared.control_push(
9509            &serde_json::to_vec(&serde_json::json!({
9510                "op": "route.closing", "module_id": "plexus",
9511                "channels": [old.channel], "terminal": false
9512            }))
9513            .unwrap(),
9514        );
9515        let mut first = Box::pin(drain_call(&consumer, b"first"));
9516        let mut second = Box::pin(drain_call(&consumer, b"second"));
9517        assert_pending(first.as_mut()).await;
9518        assert_pending(second.as_mut()).await;
9519        let first_command = receiver.recv().await.unwrap();
9520        let second_command = receiver.recv().await.unwrap();
9521        // Observing a frame at the daemon means the real writer accepted it.
9522        assert!(shared.mark_pending_accepted(first_command.pending.unwrap()));
9523        assert!(shared.mark_pending_accepted(second_command.pending.unwrap()));
9524        let first_request = first_command.frame;
9525        let second_request = second_command.frame;
9526        assert_eq!(first_request.header.channel, old.channel);
9527        assert_eq!(second_request.header.channel, old.channel);
9528
9529        refuse_during_drain(&shared, &first_request).await;
9530        assert_pending(first.as_mut()).await;
9531        // Holding route.open unanswered is the barrier: the first call has
9532        // invalidated the old route before its sibling's refusal arrives.
9533        let (open_corr, _) = next_route_open(&mut receiver, "replacement route barrier").await;
9534        refuse_during_drain(&shared, &second_request).await;
9535        for (ty, channel, epoch, corr) in [
9536            (FrameType::Goodbye, old.channel, old.epoch, 0),
9537            (FrameType::Ping, 0, 0, 991),
9538        ] {
9539            let frame = Frame::build(
9540                ty,
9541                Flags::new(false, Priority::Interactive, false),
9542                channel,
9543                epoch,
9544                corr,
9545                Vec::new(),
9546            )
9547            .unwrap();
9548            assert!(dispatch_frame(&shared, 1, frame).await);
9549        }
9550        // The same dispatcher used by the socket reader emits Pong only after
9551        // processing the second refusal and the old-route GOODBYE.
9552        let pong = receiver.recv().await.unwrap().frame;
9553        assert_eq!(pong.header.ty, FrameType::Pong);
9554        assert_eq!(pong.header.corr, 991);
9555        assert_pending(second.as_mut()).await;
9556        assert!(dispatch_frame(&shared, 1, route_open_answer(open_corr, 42, None)).await);
9557        assert_pending(first.as_mut()).await;
9558        assert_pending(second.as_mut()).await;
9559        while let Ok(command) = receiver.try_recv() {
9560            assert_eq!(command.frame.header.channel, 42);
9561            reply_to_drain_call(&shared, command.frame).await;
9562        }
9563        assert_eq!(first.await.expect("first call resends"), b"first");
9564        assert_eq!(
9565            second.await.expect("second refusal must not time out"),
9566            b"second"
9567        );
9568        assert!(shared.lock_inner().pending.is_empty());
9569    }
9570
9571    #[tokio::test(start_paused = true)]
9572    async fn shared_route_drain_preserves_unrefused_reply_without_resending() {
9573        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9574        let (_, old) = open_answered(
9575            &shared,
9576            &consumer,
9577            &mut receiver,
9578            None,
9579            41,
9580            "initial shared route",
9581        )
9582        .await;
9583        let mut first = Box::pin(drain_call(&consumer, b"refused"));
9584        let mut second = Box::pin(drain_call(&consumer, b"executing"));
9585        assert_pending(first.as_mut()).await;
9586        assert_pending(second.as_mut()).await;
9587        let first_request = receiver.recv().await.unwrap().frame;
9588        let second_request = receiver.recv().await.unwrap().frame;
9589        let executing_corr = second_request.header.corr;
9590        assert_eq!(second_request.header.channel, old.channel);
9591        let mut executing_requests = 1;
9592
9593        refuse_during_drain(&shared, &first_request).await;
9594        assert_pending(first.as_mut()).await;
9595        let (open_corr, _) = next_route_open(&mut receiver, "replacement route barrier").await;
9596        assert_pending(second.as_mut()).await;
9597        assert!(dispatch_frame(&shared, 1, route_open_answer(open_corr, 42, None)).await);
9598        assert_pending(first.as_mut()).await;
9599        assert_pending(second.as_mut()).await;
9600        while let Ok(command) = receiver.try_recv() {
9601            assert_eq!(command.frame.header.ty, FrameType::Request);
9602            // Managed resends allocate a new corr; count the logical request's
9603            // body as well so an unsafe resend cannot hide behind a new corr.
9604            if command.frame.header.corr == executing_corr || command.frame.body == b"executing" {
9605                executing_requests += 1;
9606            }
9607            reply_to_drain_call(&shared, command.frame).await;
9608        }
9609        reply_to_drain_call(&shared, second_request).await;
9610        assert_eq!(first.await.expect("refused call resends"), b"refused");
9611        assert_eq!(
9612            second.await.expect("real old-route reply arrives"),
9613            b"executing"
9614        );
9615        assert_eq!(executing_requests, 1, "unrefused call must never resend");
9616    }
9617
9618    #[tokio::test(start_paused = true)]
9619    async fn invalidated_route_ingress_is_uninstalled_after_last_pending_settles() {
9620        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9621        let (_, old) = open_answered(
9622            &shared,
9623            &consumer,
9624            &mut receiver,
9625            None,
9626            41,
9627            "initial shared route",
9628        )
9629        .await;
9630        let mut first = Box::pin(drain_call(&consumer, b"first"));
9631        let mut second = Box::pin(drain_call(&consumer, b"second"));
9632        assert_pending(first.as_mut()).await;
9633        assert_pending(second.as_mut()).await;
9634        let first_request = receiver.recv().await.unwrap().frame;
9635        let second_request = receiver.recv().await.unwrap().frame;
9636        refuse_during_drain(&shared, &first_request).await;
9637        assert_pending(first.as_mut()).await;
9638        let _ = next_route_open(&mut receiver, "replacement route barrier").await;
9639        assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), Some(old));
9640        assert!(route_reverse_request_registry(old.reverse_request_registry_id()).is_ok());
9641        reply_to_drain_call(&shared, second_request).await;
9642        assert_eq!(second.await.unwrap(), b"second");
9643        assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), None);
9644        assert!(shared.lock_inner().retired_routes.is_empty());
9645        assert!(route_reverse_request_registry(old.reverse_request_registry_id()).is_err());
9646        drop(first);
9647    }
9648
9649    #[tokio::test(start_paused = true)]
9650    async fn invalidated_route_ingress_cleans_up_on_drop_deadline_goodbye_and_disconnect() {
9651        for ending in ["drop", "deadline", "goodbye", "disconnect"] {
9652            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9653            let (_, old) = open_answered(
9654                &shared,
9655                &consumer,
9656                &mut receiver,
9657                None,
9658                41,
9659                "initial shared route",
9660            )
9661            .await;
9662            let mut first = Box::pin(drain_call(&consumer, b"refused"));
9663            let mut second = Box::pin(drain_call(&consumer, b"executing"));
9664            assert_pending(first.as_mut()).await;
9665            assert_pending(second.as_mut()).await;
9666            let first_request = receiver.recv().await.unwrap().frame;
9667            let second_command = receiver.recv().await.unwrap();
9668            assert!(shared.mark_pending_accepted(second_command.pending.unwrap()));
9669            refuse_during_drain(&shared, &first_request).await;
9670            assert_pending(first.as_mut()).await;
9671            let _ = next_route_open(&mut receiver, "replacement route barrier").await;
9672            match ending {
9673                "drop" => drop(second),
9674                "deadline" => {
9675                    assert_eq!(
9676                        second.await.unwrap_err().outcome_cause(),
9677                        Some(OutcomeUnknownCause::Deadline)
9678                    );
9679                }
9680                "goodbye" => {
9681                    let frame = Frame::build(
9682                        FrameType::Goodbye,
9683                        Flags::new(false, Priority::Interactive, false),
9684                        old.channel,
9685                        old.epoch,
9686                        0,
9687                        Vec::new(),
9688                    )
9689                    .unwrap();
9690                    assert!(dispatch_frame(&shared, 1, frame).await);
9691                    assert_eq!(
9692                        second.await.unwrap_err().outcome_cause(),
9693                        Some(OutcomeUnknownCause::RouteEnded)
9694                    );
9695                }
9696                "disconnect" => {
9697                    shared.handle_generation_drop(1, "test disconnect".into());
9698                    assert_eq!(
9699                        second.await.unwrap_err().outcome_cause(),
9700                        Some(OutcomeUnknownCause::ConnectionFailed)
9701                    );
9702                }
9703                _ => unreachable!(),
9704            }
9705            assert_eq!(
9706                shared.ingress_handle(1, old.channel, old.epoch),
9707                None,
9708                "{ending}"
9709            );
9710            assert!(shared.lock_inner().retired_routes.is_empty(), "{ending}");
9711            assert!(
9712                route_reverse_request_registry(old.reverse_request_registry_id()).is_err(),
9713                "{ending}"
9714            );
9715            drop(first);
9716        }
9717    }
9718
9719    #[tokio::test(start_paused = true)]
9720    async fn invalidated_route_subscription_cancel_and_overflow_uninstall_ingress() {
9721        for overflow in [false, true] {
9722            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9723            let (_, old) = open_answered(
9724                &shared,
9725                &consumer,
9726                &mut receiver,
9727                None,
9728                41,
9729                "initial shared route",
9730            )
9731            .await;
9732            let mut subscription = consumer
9733                .subscribe_route(&old, b"watch".to_vec(), SubscribeOptions::default())
9734                .await
9735                .unwrap();
9736            let request = receiver.recv().await.unwrap().frame;
9737            let mut call = Box::pin(drain_call(&consumer, b"refused"));
9738            assert_pending(call.as_mut()).await;
9739            let refused = receiver.recv().await.unwrap().frame;
9740            refuse_during_drain(&shared, &refused).await;
9741            assert_pending(call.as_mut()).await;
9742            let _ = next_route_open(&mut receiver, "replacement route barrier").await;
9743            assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), Some(old));
9744            assert!(matches!(
9745                consumer
9746                    .request(&old, b"new".to_vec(), CallOptions::default())
9747                    .await,
9748                Err(CallError::StaleRouteHandle(_))
9749            ));
9750            if overflow {
9751                for _ in 0..=DEFAULT_SUBSCRIPTION_EVENT_BUFFER {
9752                    assert!(
9753                        dispatch_frame(
9754                            &shared,
9755                            1,
9756                            watch_terminal(&request, FrameType::StreamData, vec![1])
9757                        )
9758                        .await
9759                    );
9760                }
9761                assert_eq!(subscription.ended().await, SubscriptionEnd::Backpressure);
9762            } else {
9763                subscription.unsubscribe().unwrap();
9764                assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
9765            }
9766            assert_eq!(
9767                receiver.recv().await.unwrap().frame.header.ty,
9768                FrameType::Cancel
9769            );
9770            assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), None);
9771            assert!(shared.lock_inner().retired_routes.is_empty());
9772            drop(call);
9773        }
9774    }
9775
9776    #[tokio::test(start_paused = true)]
9777    async fn route_open_stops_after_one_refusal_when_the_module_is_not_expected_back() {
9778        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9779        let refusal = ErrorBody::new(error_codes::TARGET_UNAVAILABLE, "module is disabled")
9780            .with_detail(serde_json::json!({"state": "disabled", "expected_back": false}));
9781        let mut task = tokio::spawn(async move {
9782            consumer
9783                .open_route(
9784                    restart_target("disabled"),
9785                    restart_identity(),
9786                    CallOptions::default(),
9787                )
9788                .await
9789        });
9790        let mut opens = 0;
9791        let result = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9792            opens += 1;
9793            (opens == 1).then(|| refusal.clone())
9794        })
9795        .await;
9796
9797        assert_eq!(opens, 1, "the daemon said the target would not recover");
9798        assert_eq!(result.unwrap_err().route_open_refusal(), Some(&refusal));
9799    }
9800
9801    #[tokio::test(start_paused = true)]
9802    async fn route_open_retries_when_expected_back_is_true_or_absent() {
9803        for expected_back in [Some(true), None] {
9804            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9805            let mut refusal = ErrorBody::new(error_codes::TARGET_UNAVAILABLE, "module is stopped");
9806            refusal.detail = expected_back.map(|value| serde_json::json!({"expected_back": value}));
9807            let mut task = tokio::spawn(async move {
9808                consumer
9809                    .open_route(
9810                        restart_target("stopped"),
9811                        restart_identity(),
9812                        CallOptions::default(),
9813                    )
9814                    .await
9815            });
9816            let mut opens = 0;
9817            let result = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9818                opens += 1;
9819                (opens == 1).then(|| refusal.clone())
9820            })
9821            .await;
9822
9823            assert!(result.is_ok(), "{expected_back:?}: {result:?}");
9824            assert_eq!(opens, 2, "{expected_back:?}");
9825        }
9826    }
9827
9828    #[tokio::test(start_paused = true)]
9829    async fn the_default_retry_deadline_outlasts_a_60s_restart_and_the_open_succeeds() {
9830        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9831        let started = Instant::now();
9832        // A call deadline past the retry deadline, so the retry deadline is
9833        // the one under test.
9834        let options = CallOptions {
9835            timeout: Duration::from_secs(120),
9836            ..CallOptions::default()
9837        };
9838        let mut task = tokio::spawn(async move {
9839            consumer
9840                .open_route(restart_target("restarting"), restart_identity(), options)
9841                .await
9842        });
9843        let opened = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9844            (started.elapsed() < Duration::from_secs(60)).then(reloading)
9845        })
9846        .await;
9847        let handle =
9848            opened.unwrap_or_else(|err| panic!("the open must survive the restart: {err}"));
9849        assert!(handle.channel > 40);
9850        assert!(started.elapsed() >= Duration::from_secs(60));
9851    }
9852
9853    #[tokio::test(start_paused = true)]
9854    async fn a_call_timeout_shorter_than_the_retry_deadline_ends_the_retries_at_the_call_timeout() {
9855        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(2));
9856        let started = Instant::now();
9857        let options = CallOptions {
9858            timeout: Duration::from_secs(10),
9859            ..CallOptions::default()
9860        };
9861        let mut task = tokio::spawn(async move {
9862            consumer
9863                .open_route(restart_target("restarting"), restart_identity(), options)
9864                .await
9865        });
9866        let err = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9867            (started.elapsed() < Duration::from_secs(60)).then(reloading)
9868        })
9869        .await
9870        .expect_err("the call timeout must end the retries before the module is back");
9871        let elapsed = started.elapsed();
9872        assert!(matches!(err, CallError::NotSent(_)), "got {err:?}");
9873        assert!(
9874            elapsed >= Duration::from_secs(9) && elapsed <= Duration::from_secs(10),
9875            "the retries must stop at the 10s call timeout, stopped after {elapsed:?}"
9876        );
9877    }
9878
9879    #[tokio::test(start_paused = true)]
9880    async fn two_routes_refused_together_retry_at_different_jittered_times() {
9881        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(42));
9882        let started = Instant::now();
9883        let mut task = tokio::spawn(async move {
9884            let alpha = consumer.open_route(
9885                restart_target("alpha"),
9886                restart_identity(),
9887                CallOptions::default(),
9888            );
9889            let beta = consumer.open_route(
9890                restart_target("beta"),
9891                restart_identity(),
9892                CallOptions::default(),
9893            );
9894            let (alpha, beta) = tokio::join!(alpha, beta);
9895            (alpha.is_ok(), beta.is_ok())
9896        });
9897        let mut first_open = HashMap::<String, Duration>::new();
9898        let mut retried_at = HashMap::<String, Duration>::new();
9899        let opened = answer_route_opens(&shared, &mut receiver, &mut task, |module_id| {
9900            let at = started.elapsed();
9901            if first_open.contains_key(module_id) {
9902                retried_at.insert(module_id.to_string(), at);
9903                None
9904            } else {
9905                first_open.insert(module_id.to_string(), at);
9906                Some(reloading())
9907            }
9908        })
9909        .await;
9910        assert_eq!(opened, (true, true));
9911        assert_eq!(first_open["alpha"], first_open["beta"], "refused together");
9912        // Equal jitter keeps half of the 100ms base delay and randomizes the rest.
9913        for at in retried_at.values() {
9914            assert!(
9915                *at >= Duration::from_millis(50) && *at <= Duration::from_millis(100),
9916                "retry at {at:?} is outside the jitter window"
9917            );
9918        }
9919        assert_ne!(
9920            retried_at["alpha"], retried_at["beta"],
9921            "routes refused together must not retry in lock step"
9922        );
9923    }
9924
9925    #[tokio::test(start_paused = true)]
9926    async fn twenty_concurrent_opens_never_have_more_than_eight_outstanding_at_the_daemon() {
9927        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(3));
9928        let mut task = tokio::spawn(async move {
9929            let mut opens = tokio::task::JoinSet::new();
9930            for i in 0..20 {
9931                let consumer = Arc::clone(&consumer);
9932                opens.spawn(async move {
9933                    consumer
9934                        .open_route(
9935                            restart_target(&format!("module-{i}")),
9936                            restart_identity(),
9937                            CallOptions::default(),
9938                        )
9939                        .await
9940                });
9941            }
9942            let mut opened = 0usize;
9943            while let Some(result) = opens.join_next().await {
9944                result.unwrap().unwrap();
9945                opened += 1;
9946            }
9947            opened
9948        });
9949        // Hold every open until the consumer has gone quiet, so everything it
9950        // is willing to send at once is outstanding together; then answer them.
9951        let mut held = Vec::new();
9952        let mut max_outstanding = 0usize;
9953        let mut next_channel = 40u16;
9954        let opened = loop {
9955            tokio::select! {
9956                command = receiver.recv() => {
9957                    // The writer closes when the last consumer handle drops,
9958                    // which means every open has settled.
9959                    let Some(command) = command else {
9960                        break (&mut task).await.unwrap();
9961                    };
9962                    held.push(command.frame.header.corr);
9963                    max_outstanding = max_outstanding.max(held.len());
9964                }
9965                () = sleep(Duration::from_millis(25)), if !held.is_empty() => {
9966                    for corr in held.drain(..) {
9967                        next_channel += 1;
9968                        assert!(dispatch_frame(&shared, 1, route_open_answer(corr, next_channel, None)).await);
9969                    }
9970                }
9971                joined = &mut task => break joined.unwrap(),
9972            }
9973        };
9974        assert_eq!(opened, 20);
9975        assert_eq!(max_outstanding, MAX_ROUTE_OPENS_IN_FLIGHT);
9976    }
9977
9978    #[tokio::test(start_paused = true)]
9979    async fn an_exhausted_deadline_names_module_reloading_not_the_later_admission_pressure() {
9980        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(4));
9981        let options = CallOptions {
9982            route_retry_deadline: Duration::from_secs(5),
9983            ..CallOptions::default()
9984        };
9985        let mut task = tokio::spawn(async move {
9986            consumer
9987                .open_route(restart_target("restarting"), restart_identity(), options)
9988                .await
9989        });
9990        let mut opens = 0usize;
9991        let err = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9992            opens += 1;
9993            Some(if opens <= 2 {
9994                reloading().with_detail(serde_json::json!({ "reason": "restart" }))
9995            } else {
9996                ErrorBody::new(
9997                    error_codes::TARGET_UNAVAILABLE,
9998                    "connection already has 8 route.open binds in flight (limit 8); retry after one settles",
9999                )
10000            })
10001        })
10002        .await
10003        .expect_err("the module never comes back");
10004        assert!(opens > 2);
10005        assert!(matches!(err, CallError::NotSent(_)), "got {err:?}");
10006        assert_eq!(
10007            err.route_open_refusal().map(|body| body.code.as_str()),
10008            Some(error_codes::MODULE_RELOADING)
10009        );
10010        let message = err.to_string();
10011        assert!(
10012            message.starts_with(
10013                "request not sent: route.open failed for target tool_provider:restarting: \
10014                 module_reloading (reason restart) (module is reloading); \
10015                 the most recent refusal was target_unavailable"
10016            ),
10017            "got {message}"
10018        );
10019    }
10020
10021    #[tokio::test]
10022    async fn close_route_flips_inflight_opening_so_a_racing_open_discards() {
10023        // The load-bearing close-beats-reopen guard, in isolation: a close that lands
10024        // while a route.open is in flight (channel not yet cached) must flip the
10025        // opening's `closed` flag, so the lead opener re-checks it before installing and
10026        // GOODBYEs the channel it opened instead of caching it.
10027        let shared = Arc::new(reader_skew_tests::legacy_shared(
10028            PathBuf::from("/tmp/does-not-exist"),
10029            ConsumerOptions::default(),
10030        ));
10031        let key = RouteKey::new(
10032            &RouteTarget::ToolProvider {
10033                module_id: "m".into(),
10034            },
10035            &BindIdentity::new("h", "s"),
10036            None,
10037            None,
10038        );
10039        // Simulate an in-flight lead open: an openings entry exists, not yet closed,
10040        // with no cached route (channel hasn't been installed yet).
10041        shared.lock_inner().openings.insert(
10042            key.clone(),
10043            Opening {
10044                waiters: Vec::new(),
10045                closed: false,
10046            },
10047        );
10048
10049        // close_route with no cached route is an idempotent no-op on routes, but MUST
10050        // flip the in-flight opening's flag so the racing open discards.
10051        shared
10052            .close_route(&key, &CloseRouteOptions::default())
10053            .await;
10054        assert!(
10055            shared
10056                .lock_inner()
10057                .openings
10058                .get(&key)
10059                .is_some_and(|o| o.closed),
10060            "close_route must flip the in-flight opening's closed flag (close-beats-reopen)"
10061        );
10062
10063        // And closing a key with neither a route nor an in-flight open is a no-op.
10064        let absent = RouteKey::new(
10065            &RouteTarget::ToolProvider {
10066                module_id: "absent".into(),
10067            },
10068            &BindIdentity::new("h", "s"),
10069            None,
10070            None,
10071        );
10072        shared
10073            .close_route(&absent, &CloseRouteOptions::default())
10074            .await;
10075    }
10076
10077    #[test]
10078    fn route_key_is_structured() {
10079        let target = RouteTarget::InternalService {
10080            module_id: "a\0b".into(),
10081            service_id: "svc".into(),
10082        };
10083        let identity = BindIdentity::new("h", "s");
10084        let key = RouteKey::new(&target, &identity, None, None);
10085        assert!(matches!(key.target, RouteTargetKey::InternalService { .. }));
10086    }
10087
10088    async fn assert_pending(mut future: Pin<&mut (impl Future + ?Sized)>) {
10089        assert!(
10090            std::future::poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx).is_pending())).await
10091        );
10092    }
10093
10094    /// Replace only the transport, leaving the actual generation-drop cleanup in use.
10095    fn drop_and_replace_test_transport(shared: &Arc<Shared>) -> mpsc::Receiver<WriteCommand> {
10096        let generation = shared.lock_inner().generation;
10097        // Keep the background supervisor from touching a real connection file.
10098        shared.lock_inner().reconnect = ReconnectState::Inline { generation };
10099        shared.handle_generation_drop(generation, "test connection drop".into());
10100        let (writer, receiver) = mpsc::channel(64);
10101        let mut inner = shared.lock_inner();
10102        inner.generation += 1;
10103        inner.epoch += 1;
10104        inner.next_corr = Some(1);
10105        inner.writer = Some(writer);
10106        inner.daemon_ver = "0.39.0".into();
10107        inner.reconnect = ReconnectState::Idle;
10108        receiver
10109    }
10110
10111    #[tokio::test(start_paused = true)]
10112    async fn route_open_single_flight_survives_generation_drop_during_backoff() {
10113        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
10114        let opts = CallOptions::default();
10115        let opener = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10116        tokio::pin!(opener);
10117        assert_pending(opener.as_mut()).await;
10118        let first = receiver.try_recv().unwrap();
10119        assert!(
10120            dispatch_frame(
10121                &shared,
10122                1,
10123                route_open_answer(first.frame.header.corr, 0, Some(reloading())),
10124            )
10125            .await
10126        );
10127        assert_pending(opener.as_mut()).await;
10128
10129        // A caller already waiting and one arriving after the drop must both stay
10130        // behind the same lead opener, including its unfinished retry backoff.
10131        let waiting = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10132        tokio::pin!(waiting);
10133        assert_pending(waiting.as_mut()).await;
10134        let mut receiver = drop_and_replace_test_transport(&shared);
10135        assert_pending(waiting.as_mut()).await;
10136        let arriving = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10137        tokio::pin!(arriving);
10138        assert_pending(arriving.as_mut()).await;
10139        assert!(
10140            receiver.try_recv().is_err(),
10141            "a second opener bypassed the backoff"
10142        );
10143
10144        tokio::time::advance(opts.route_retry.base).await;
10145        assert_pending(opener.as_mut()).await;
10146        let retry = receiver.try_recv().unwrap();
10147        assert!(
10148            dispatch_frame(
10149                &shared,
10150                2,
10151                route_open_answer(retry.frame.header.corr, 42, None),
10152            )
10153            .await
10154        );
10155        let handle = opener.await.unwrap();
10156        assert_eq!(waiting.await.unwrap(), handle);
10157        assert_eq!(arriving.await.unwrap(), handle);
10158        assert!(
10159            receiver.try_recv().is_err(),
10160            "more than one retry was emitted"
10161        );
10162        let inner = shared.lock_inner();
10163        assert!(inner.openings.is_empty());
10164        assert_eq!(inner.routes.len(), 1);
10165        assert_eq!(inner.route_epochs.len(), 1);
10166    }
10167
10168    #[tokio::test(start_paused = true)]
10169    async fn close_route_during_backoff_survives_generation_drop() {
10170        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
10171        let opts = CallOptions::default();
10172        let opener = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10173        tokio::pin!(opener);
10174        assert_pending(opener.as_mut()).await;
10175        let first = receiver.try_recv().unwrap();
10176        assert!(
10177            dispatch_frame(
10178                &shared,
10179                1,
10180                route_open_answer(first.frame.header.corr, 0, Some(reloading())),
10181            )
10182            .await
10183        );
10184        assert_pending(opener.as_mut()).await;
10185        consumer
10186            .close_route(
10187                restart_target("m"),
10188                restart_identity(),
10189                CloseRouteOptions::default(),
10190            )
10191            .await;
10192        let mut receiver = drop_and_replace_test_transport(&shared);
10193        tokio::time::advance(opts.route_retry.base).await;
10194        assert_pending(opener.as_mut()).await;
10195        let retry = receiver.try_recv().unwrap();
10196        assert!(
10197            dispatch_frame(
10198                &shared,
10199                2,
10200                route_open_answer(retry.frame.header.corr, 42, None),
10201            )
10202            .await
10203        );
10204        let err = opener.await.expect_err("close must win over the retry");
10205        assert!(matches!(err, CallError::NotSent(_)));
10206        let goodbye = receiver
10207            .try_recv()
10208            .expect("discarded route must get GOODBYE");
10209        assert_eq!(goodbye.frame.header.ty, FrameType::Goodbye);
10210        assert_eq!(goodbye.frame.header.channel, 42);
10211        assert!(receiver.try_recv().is_err());
10212        let inner = shared.lock_inner();
10213        assert!(inner.routes.is_empty());
10214        assert!(inner.route_epochs.is_empty());
10215        assert!(inner.openings.is_empty());
10216    }
10217
10218    fn route_teardown_stand_in() -> (
10219        Arc<Shared>,
10220        SubcConsumer,
10221        mpsc::Receiver<WriteCommand>,
10222        tokio::io::DuplexStream,
10223        RouteKey,
10224        RouteState,
10225    ) {
10226        let shared = writer_test_shared();
10227        let (stream, peer) = tokio::io::duplex(1024);
10228        shared
10229            .install_initial(OpenedConnection {
10230                stream: Box::new(stream),
10231                daemon_origin_trusted: true,
10232                daemon_ver: "0.39.0".into(),
10233            })
10234            .unwrap();
10235        let (writer, rx) = mpsc::channel(1);
10236        writer
10237            .try_send(WriteCommand {
10238                frame: response_frame(0, 0, 99, b"filler".to_vec()),
10239                pending: None,
10240            })
10241            .unwrap();
10242        let key = RouteKey::new(&restart_target("teardown"), &restart_identity(), None, None);
10243        let route = RouteState {
10244            handle: RouteHandle::new(17, 23, 1),
10245            sem: Arc::new(Semaphore::new(1)),
10246            watch_sem: None,
10247            opted_in: false,
10248        };
10249        {
10250            let mut inner = shared.lock_inner();
10251            inner.writer = Some(writer);
10252            inner.cache_route(key.clone(), route.clone());
10253        }
10254        let consumer = SubcConsumer {
10255            shared: Arc::clone(&shared),
10256        };
10257        (shared, consumer, rx, peer, key, route)
10258    }
10259
10260    async fn assert_reopened_request_after_goodbye(
10261        shared: &Arc<Shared>,
10262        consumer: &SubcConsumer,
10263        rx: &mut mpsc::Receiver<WriteCommand>,
10264        old: RouteHandle,
10265    ) {
10266        let reopened = RouteHandle::new(old.channel, old.epoch + 1, old.connection_token());
10267        shared
10268            .install_one_shot_route(RouteState {
10269                handle: reopened,
10270                sem: Arc::new(Semaphore::new(1)),
10271                watch_sem: None,
10272                opted_in: false,
10273            })
10274            .unwrap();
10275        let request = consumer.request(&reopened, b"reopened".to_vec(), CallOptions::default());
10276        tokio::pin!(request);
10277        assert_pending(request.as_mut()).await;
10278        let command = rx.recv().await.unwrap();
10279        assert_eq!(command.frame.header.ty, FrameType::Goodbye);
10280        assert_eq!(
10281            (command.frame.header.channel, command.frame.header.epoch),
10282            (old.channel, old.epoch)
10283        );
10284        assert_pending(request.as_mut()).await;
10285        let command = rx.recv().await.unwrap();
10286        assert_eq!(command.frame.header.ty, FrameType::Request);
10287        assert_eq!(command.frame.header.channel, reopened.channel);
10288        assert_eq!(command.frame.header.epoch, reopened.epoch);
10289        dispatch_frame(
10290            shared,
10291            reopened.connection_token(),
10292            response_frame(
10293                reopened.channel,
10294                reopened.epoch,
10295                command.frame.header.corr,
10296                Vec::new(),
10297            ),
10298        )
10299        .await;
10300        request.await.unwrap();
10301    }
10302
10303    #[tokio::test]
10304    async fn route_teardown_close_waits_for_goodbye_before_channel_reuse() {
10305        for by_handle in [false, true] {
10306            let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10307            let close = async {
10308                if by_handle {
10309                    consumer
10310                        .close_handle(&route.handle, CloseRouteOptions::default())
10311                        .await
10312                        .unwrap();
10313                } else {
10314                    consumer
10315                        .close_route(
10316                            restart_target("teardown"),
10317                            restart_identity(),
10318                            CloseRouteOptions::default(),
10319                        )
10320                        .await;
10321                }
10322            };
10323            tokio::pin!(close);
10324            assert_pending(close.as_mut()).await;
10325            assert!(route.sem.is_closed());
10326            assert!(!shared.lock_inner().routes.contains_key(&key));
10327            assert_eq!(
10328                shared.lock_inner().route_epochs.get(&route.handle.channel),
10329                Some(&route.handle)
10330            );
10331            let mut reopened = route.clone();
10332            reopened.handle = RouteHandle::new(route.handle.channel, route.handle.epoch + 1, 1);
10333            assert!(shared.install_one_shot_route(reopened).is_err());
10334            assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10335            close.await;
10336            assert_reopened_request_after_goodbye(&shared, &consumer, &mut rx, route.handle).await;
10337            consumer.close().await;
10338        }
10339    }
10340
10341    #[tokio::test]
10342    async fn route_teardown_retirement_waits_for_goodbye_before_channel_reuse() {
10343        let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10344        shared.invalidate_route_with_deadline(&key, Some(route.handle), true);
10345        assert!(route.sem.is_closed());
10346        assert_eq!(
10347            shared.lock_inner().route_epochs.get(&route.handle.channel),
10348            Some(&route.handle)
10349        );
10350        let mut reopened = route.clone();
10351        reopened.handle = RouteHandle::new(route.handle.channel, route.handle.epoch + 1, 1);
10352        assert!(shared.install_one_shot_route(reopened).is_err());
10353        assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10354        tokio::time::timeout(Duration::from_secs(1), async {
10355            while shared
10356                .lock_inner()
10357                .route_epochs
10358                .contains_key(&route.handle.channel)
10359            {
10360                tokio::task::yield_now().await;
10361            }
10362        })
10363        .await
10364        .expect("retirement must queue its GOODBYE after writer capacity frees");
10365        assert_reopened_request_after_goodbye(&shared, &consumer, &mut rx, route.handle).await;
10366        consumer.close().await;
10367    }
10368
10369    #[tokio::test]
10370    async fn route_teardown_retirements_flush_in_order() {
10371        let (shared, consumer, mut rx, _peer, first_key, first) = route_teardown_stand_in();
10372        let second_key = RouteKey::new(&restart_target("second"), &restart_identity(), None, None);
10373        let mut second = first.clone();
10374        second.handle = RouteHandle::new(first.handle.channel + 1, 31, 1);
10375        shared
10376            .lock_inner()
10377            .cache_route(second_key.clone(), second.clone());
10378        shared.invalidate_route_with_deadline(&first_key, Some(first.handle), true);
10379        shared.invalidate_route_with_deadline(&second_key, Some(second.handle), true);
10380        assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10381        for handle in [first.handle, second.handle] {
10382            let command = tokio::time::timeout(Duration::from_secs(1), rx.recv())
10383                .await
10384                .unwrap()
10385                .unwrap();
10386            assert_eq!(command.frame.header.ty, FrameType::Goodbye);
10387            assert_eq!(
10388                (command.frame.header.channel, command.frame.header.epoch),
10389                (handle.channel, handle.epoch)
10390            );
10391            assert!(!shared
10392                .lock_inner()
10393                .route_epochs
10394                .contains_key(&handle.channel));
10395        }
10396        assert!(shared.lock_inner().retirement_queue.is_empty());
10397        assert!(shared.lock_inner().retirement_goodbyes.is_empty());
10398        assert!(rx.try_recv().is_err());
10399        consumer.close().await;
10400    }
10401
10402    #[tokio::test]
10403    async fn route_teardown_dead_connection_ends_writer_wait_and_discards_retirements() {
10404        for death in 0..3 {
10405            let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10406            let opts = CloseRouteOptions::default();
10407            let close = shared.close_route(&key, &opts);
10408            tokio::pin!(close);
10409            assert_pending(close.as_mut()).await;
10410            match death {
10411                0 => rx.close(),
10412                1 => shared.handle_generation_drop(1, "test connection lost".into()),
10413                _ => shared.close_sync("test connection closed"),
10414            }
10415            tokio::time::timeout(Duration::from_secs(1), close)
10416                .await
10417                .unwrap();
10418            assert!(!shared
10419                .lock_inner()
10420                .route_epochs
10421                .contains_key(&route.handle.channel));
10422            assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10423            assert!(rx.try_recv().is_err());
10424            consumer.close().await;
10425
10426            let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10427            shared.invalidate_route_with_deadline(&key, Some(route.handle), true);
10428            if death == 1 {
10429                shared.handle_generation_drop(1, "test connection lost".into());
10430            } else {
10431                consumer.close().await;
10432            }
10433            assert!(shared.lock_inner().retirement_queue.is_empty());
10434            assert!(shared.lock_inner().retirement_goodbyes.is_empty());
10435            assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10436            assert!(rx.try_recv().is_err());
10437            consumer.close().await;
10438        }
10439    }
10440
10441    #[tokio::test]
10442    async fn route_channel_index_tracks_lookup_close_and_generation_drop() {
10443        let shared = writer_test_shared();
10444        let (writer, _rx) = mpsc::channel(32);
10445        let mut expected = Vec::new();
10446        {
10447            let mut inner = shared.lock_inner();
10448            inner.writer = Some(writer);
10449            inner.daemon_ver = "0.39.0".into();
10450            for channel in 1..=8 {
10451                let key = RouteKey::new(
10452                    &RouteTarget::ToolProvider {
10453                        module_id: format!("module-{channel}"),
10454                    },
10455                    &BindIdentity::new("test", format!("session-{channel}")),
10456                    None,
10457                    None,
10458                );
10459                let route = RouteState {
10460                    handle: RouteHandle::new(channel, channel.into(), 1),
10461                    sem: Arc::new(Semaphore::new(DEFAULT_ROUTE_WINDOW)),
10462                    watch_sem: None,
10463                    opted_in: false,
10464                };
10465                inner.cache_route(key.clone(), route.clone());
10466                expected.push((key, route));
10467            }
10468        }
10469
10470        for (key, expected_route) in &expected {
10471            let resolved = shared
10472                .route_state(expected_route.handle)
10473                .expect("an indexed route handle should resolve");
10474            assert_eq!(resolved.handle, expected_route.handle);
10475            assert!(Arc::ptr_eq(&resolved.sem, &expected_route.sem));
10476
10477            let inner = shared.lock_inner();
10478            assert_eq!(
10479                inner.route_by_channel.get(&expected_route.handle.channel),
10480                Some(key)
10481            );
10482            assert_eq!(
10483                inner.route_epochs.get(&expected_route.handle.channel),
10484                Some(&expected_route.handle)
10485            );
10486            assert!(inner
10487                .routes
10488                .get(key)
10489                .is_some_and(|route| route.handle == expected_route.handle));
10490        }
10491
10492        let (closed_key, closed_route) = &expected[3];
10493        shared
10494            .close_route(closed_key, &CloseRouteOptions::default())
10495            .await;
10496        {
10497            let inner = shared.lock_inner();
10498            assert!(!inner.routes.contains_key(closed_key));
10499            assert!(!inner
10500                .route_by_channel
10501                .contains_key(&closed_route.handle.channel));
10502            assert!(!inner
10503                .route_epochs
10504                .contains_key(&closed_route.handle.channel));
10505        }
10506        assert!(matches!(
10507            shared.route_state(closed_route.handle),
10508            Err(CallError::StaleRouteHandle(handle)) if handle == closed_route.handle
10509        ));
10510
10511        shared.handle_generation_drop(1, "test generation dropped".into());
10512        {
10513            let inner = shared.lock_inner();
10514            assert!(inner.routes.is_empty());
10515            assert!(inner.route_by_channel.is_empty());
10516            assert!(inner.route_epochs.is_empty());
10517        }
10518        shared.close_sync("test complete");
10519    }
10520
10521    #[tokio::test]
10522    async fn stale_push_is_not_delivered_after_connection_generation_changes() {
10523        let shared = writer_test_shared();
10524        let old_handle = RouteHandle::new(7, 1, 1);
10525        let (writer, _writer_rx) = mpsc::channel(1);
10526        {
10527            let mut inner = shared.lock_inner();
10528            inner.writer = Some(writer);
10529            inner.daemon_ver = "0.39.0".into();
10530            inner.route_epochs.insert(old_handle.channel, old_handle);
10531        }
10532        let mut pushes = shared
10533            .register_push_events(old_handle)
10534            .expect("the old live route should accept a receiver");
10535
10536        {
10537            let mut inner = shared.lock_inner();
10538            inner.generation = 2;
10539            inner.close_routes();
10540            inner.route_epochs.clear();
10541            inner.route_modules.clear();
10542            inner.route_end_reasons.clear();
10543            inner.legacy_channel_reasons.clear();
10544        }
10545        shared.route_push(old_handle, b"stale".to_vec());
10546
10547        assert!(
10548            pushes.recv().await.is_none(),
10549            "connection teardown must end the old receiver before a stale Push can arrive"
10550        );
10551        shared.close_sync("test complete");
10552    }
10553
10554    #[test]
10555    fn route_key_canonicalizes_consumer_capabilities() {
10556        let target = RouteTarget::ToolProvider {
10557            module_id: "aft".into(),
10558        };
10559        let identity = BindIdentity::new("h", "s");
10560        let left = RouteKey::new(
10561            &target,
10562            &identity,
10563            None,
10564            Some(&["sampling".to_string(), "elicitation".to_string()]),
10565        );
10566        let right = RouteKey::new(
10567            &target,
10568            &identity,
10569            None,
10570            Some(&[
10571                "elicitation".to_string(),
10572                "sampling".to_string(),
10573                "sampling".to_string(),
10574            ]),
10575        );
10576        assert_eq!(left, right);
10577    }
10578
10579    #[tokio::test]
10580    async fn routes_with_and_without_declared_consumer_capabilities_are_kept_apart() {
10581        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(10));
10582        let (undeclared_request, undeclared) = open_answered_with(
10583            &shared,
10584            &consumer,
10585            &mut receiver,
10586            CallOptions::default(),
10587            74,
10588            "the undeclared route opens first",
10589        )
10590        .await;
10591        assert!(undeclared_request.get("consumer_capabilities").is_none());
10592
10593        let declared_opts = CallOptions::default()
10594            .with_consumer_capability("tool-result/v1")
10595            .unwrap();
10596        let (declared_request, declared) = open_answered_with(
10597            &shared,
10598            &consumer,
10599            &mut receiver,
10600            declared_opts.clone(),
10601            75,
10602            "a declared open must not reuse the undeclared route",
10603        )
10604        .await;
10605        assert_eq!(
10606            declared_request["consumer_capabilities"],
10607            serde_json::json!(["tool-result/v1"])
10608        );
10609        assert_ne!(undeclared, declared);
10610
10611        assert_eq!(
10612            consumer
10613                .open_route(restart_target("plexus"), restart_identity(), declared_opts)
10614                .await
10615                .unwrap(),
10616            declared,
10617            "the same declaration must reuse its cached route"
10618        );
10619        assert_eq!(
10620            consumer
10621                .open_route(
10622                    restart_target("plexus"),
10623                    restart_identity(),
10624                    CallOptions::default(),
10625                )
10626                .await
10627                .unwrap(),
10628            undeclared,
10629            "an undeclared open must continue to reuse only its own route"
10630        );
10631        assert!(
10632            receiver.try_recv().is_err(),
10633            "both subsequent opens are cache hits"
10634        );
10635        shared.close_sync("test complete");
10636    }
10637
10638    fn scope_selector(owner: &str, scope_ref: &str, scope_epoch: u64) -> ScopeSelector {
10639        ScopeSelector::new(
10640            subc_protocol::Principal::Reserved {
10641                module_id: owner.to_string(),
10642            },
10643            scope_ref.to_string(),
10644            Some(scope_epoch),
10645        )
10646    }
10647
10648    #[test]
10649    fn route_key_separates_scopes_by_owner_ref_and_epoch_and_from_unscoped() {
10650        let target = RouteTarget::ToolProvider {
10651            module_id: "plexus".into(),
10652        };
10653        let identity = BindIdentity::new("h", "s");
10654        let key = |scope: Option<ScopeSelector>| {
10655            RouteKey::new(&target, &identity, None, None).with_scope(scope.as_ref())
10656        };
10657        let base = key(Some(scope_selector("owner", "session-a", 1)));
10658        assert_eq!(base, key(Some(scope_selector("owner", "session-a", 1))));
10659        for (label, other) in [
10660            ("epoch", key(Some(scope_selector("owner", "session-a", 2)))),
10661            ("ref", key(Some(scope_selector("owner", "session-b", 1)))),
10662            ("owner", key(Some(scope_selector("other", "session-a", 1)))),
10663            ("unscoped", key(None)),
10664        ] {
10665            assert_ne!(base, other, "a different {label} must be a different route");
10666        }
10667        let mut no_epoch = scope_selector("owner", "session-a", 1);
10668        no_epoch.scope_epoch = None;
10669        assert_ne!(base, key(Some(no_epoch)));
10670    }
10671
10672    /// The next route.open the consumer writes, skipping any other frame
10673    /// (a GOODBYE, a cancel). Fails the test by name if none arrives, which is
10674    /// what a cache hit that should have been a miss looks like.
10675    async fn next_route_open(
10676        receiver: &mut mpsc::Receiver<WriteCommand>,
10677        why: &str,
10678    ) -> (u64, serde_json::Value) {
10679        loop {
10680            let command = tokio::time::timeout(Duration::from_secs(2), receiver.recv())
10681                .await
10682                .unwrap_or_else(|_| panic!("no route.open was sent: {why}"))
10683                .expect("writer channel open");
10684            if command.frame.header.channel != 0 || command.frame.header.ty != FrameType::Request {
10685                continue;
10686            }
10687            let request: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
10688            if request["op"] == "route.open" {
10689                return (command.frame.header.corr, request);
10690            }
10691        }
10692    }
10693
10694    /// Open a route (scoped when `scope` is set) through the stand-in daemon,
10695    /// accept its route.open on `channel`, and return the open's body and handle.
10696    async fn open_answered(
10697        shared: &Arc<Shared>,
10698        consumer: &Arc<SubcConsumer>,
10699        receiver: &mut mpsc::Receiver<WriteCommand>,
10700        scope: Option<ScopeSelector>,
10701        channel: u16,
10702        why: &str,
10703    ) -> (serde_json::Value, RouteHandle) {
10704        let consumer = Arc::clone(consumer);
10705        let task = tokio::spawn(async move {
10706            match scope {
10707                Some(scope) => {
10708                    consumer
10709                        .open_route_scoped(
10710                            restart_target("plexus"),
10711                            restart_identity(),
10712                            scope,
10713                            CallOptions::default(),
10714                        )
10715                        .await
10716                }
10717                None => {
10718                    consumer
10719                        .open_route(
10720                            restart_target("plexus"),
10721                            restart_identity(),
10722                            CallOptions::default(),
10723                        )
10724                        .await
10725                }
10726            }
10727        });
10728        let (corr, request) = next_route_open(receiver, why).await;
10729        assert!(dispatch_frame(shared, 1, route_open_answer(corr, channel, None)).await);
10730        let handle = task.await.unwrap().expect("the stand-in accepted the open");
10731        (request, handle)
10732    }
10733
10734    /// Open an unscoped `plexus` route with `opts` through the stand-in
10735    /// daemon, accept its route.open on `channel`, and return the open's body
10736    /// and handle.
10737    async fn open_answered_with(
10738        shared: &Arc<Shared>,
10739        consumer: &Arc<SubcConsumer>,
10740        receiver: &mut mpsc::Receiver<WriteCommand>,
10741        opts: CallOptions,
10742        channel: u16,
10743        why: &str,
10744    ) -> (serde_json::Value, RouteHandle) {
10745        let consumer = Arc::clone(consumer);
10746        let task = tokio::spawn(async move {
10747            consumer
10748                .open_route(restart_target("plexus"), restart_identity(), opts)
10749                .await
10750        });
10751        let (corr, request) = next_route_open(receiver, why).await;
10752        assert!(dispatch_frame(shared, 1, route_open_answer(corr, channel, None)).await);
10753        let handle = task.await.unwrap().expect("the stand-in accepted the open");
10754        (request, handle)
10755    }
10756
10757    fn with_role_versions(entries: &[(&str, &str)]) -> CallOptions {
10758        CallOptions {
10759            role_versions: Some(
10760                entries
10761                    .iter()
10762                    .map(|(role, version)| (role.to_string(), version.to_string()))
10763                    .collect(),
10764            ),
10765            ..CallOptions::default()
10766        }
10767    }
10768
10769    /// A provider picks its wire shape from the role versions at bind, so a
10770    /// legacy route and a versioned one to the same target must never be
10771    /// shared, while the same declaration again (and an empty map, which
10772    /// declares nothing) reuses the route it matches.
10773    #[tokio::test]
10774    async fn routes_differing_only_in_role_versions_are_kept_apart() {
10775        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(9));
10776        let (legacy_request, legacy) = open_answered_with(
10777            &shared,
10778            &consumer,
10779            &mut receiver,
10780            CallOptions::default(),
10781            71,
10782            "first, legacy open",
10783        )
10784        .await;
10785        assert!(
10786            legacy_request.get("role_versions").is_none(),
10787            "{legacy_request}"
10788        );
10789
10790        let (v1_request, v1) = open_answered_with(
10791            &shared,
10792            &consumer,
10793            &mut receiver,
10794            with_role_versions(&[("tool-provider", "v1")]),
10795            72,
10796            "a v1 open must not reuse the legacy route",
10797        )
10798        .await;
10799        assert_eq!(
10800            v1_request["role_versions"],
10801            serde_json::json!({ "tool-provider": "v1" })
10802        );
10803        assert_ne!(legacy, v1);
10804
10805        let (v2_request, v2) = open_answered_with(
10806            &shared,
10807            &consumer,
10808            &mut receiver,
10809            with_role_versions(&[("tool-provider", "v2")]),
10810            73,
10811            "a v2 open must not reuse the v1 route",
10812        )
10813        .await;
10814        assert_eq!(
10815            v2_request["role_versions"],
10816            serde_json::json!({ "tool-provider": "v2" })
10817        );
10818        assert!(![legacy, v1].contains(&v2));
10819
10820        let open = |opts: CallOptions| {
10821            let consumer = Arc::clone(&consumer);
10822            async move {
10823                consumer
10824                    .open_route(restart_target("plexus"), restart_identity(), opts)
10825                    .await
10826                    .unwrap()
10827            }
10828        };
10829        assert_eq!(
10830            open(with_role_versions(&[("tool-provider", "v1")])).await,
10831            v1
10832        );
10833        assert_eq!(open(CallOptions::default()).await, legacy);
10834        assert_eq!(
10835            open(CallOptions {
10836                role_versions: Some(BTreeMap::new()),
10837                ..CallOptions::default()
10838            })
10839            .await,
10840            legacy,
10841            "an empty map declares nothing and reuses the legacy route"
10842        );
10843        assert!(
10844            receiver.try_recv().is_err(),
10845            "a cache hit must not send a route.open"
10846        );
10847        shared.close_sync("test complete");
10848    }
10849
10850    #[tokio::test]
10851    async fn scoped_routes_are_cached_per_owner_ref_and_epoch_and_apart_from_unscoped() {
10852        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(8));
10853        let selector = scope_selector("owner", "session-a", 1);
10854        let (request, first) = open_answered(
10855            &shared,
10856            &consumer,
10857            &mut receiver,
10858            Some(selector.clone()),
10859            61,
10860            "first scoped open",
10861        )
10862        .await;
10863        assert_eq!(request["scope"], serde_json::to_value(&selector).unwrap());
10864
10865        // The same selector again is a cache hit: no route.open, same handle.
10866        let again = consumer
10867            .open_route_scoped(
10868                restart_target("plexus"),
10869                restart_identity(),
10870                selector,
10871                CallOptions::default(),
10872            )
10873            .await
10874            .unwrap();
10875        assert_eq!(again, first);
10876        assert!(
10877            receiver.try_recv().is_err(),
10878            "a cache hit must not send a route.open"
10879        );
10880
10881        let mut handles = vec![first];
10882        for (channel, scope, why) in [
10883            (
10884                62,
10885                Some(scope_selector("owner", "session-a", 2)),
10886                "another epoch of the same scope must open its own route",
10887            ),
10888            (
10889                63,
10890                Some(scope_selector("owner", "session-b", 1)),
10891                "another scope ref must open its own route",
10892            ),
10893            (
10894                64,
10895                Some(scope_selector("other-owner", "session-a", 1)),
10896                "another owner's scope must open its own route",
10897            ),
10898            (65, None, "an unscoped open must not reuse a scoped route"),
10899        ] {
10900            let expected_scope = scope
10901                .as_ref()
10902                .map(|scope| serde_json::to_value(scope).unwrap());
10903            let (request, handle) =
10904                open_answered(&shared, &consumer, &mut receiver, scope, channel, why).await;
10905            assert_eq!(
10906                request.get("scope").cloned(),
10907                expected_scope,
10908                "the route.open must carry exactly the requested scope: {why}"
10909            );
10910            assert!(!handles.contains(&handle), "{why}");
10911            handles.push(handle);
10912        }
10913        shared.close_sync("test complete");
10914    }
10915
10916    #[tokio::test]
10917    async fn a_dropped_scoped_route_reopens_with_the_same_selector() {
10918        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(7));
10919        let selector = scope_selector("owner", "session-a", 3);
10920        let (first_request, first) = open_answered(
10921            &shared,
10922            &consumer,
10923            &mut receiver,
10924            Some(selector.clone()),
10925            51,
10926            "first scoped open",
10927        )
10928        .await;
10929
10930        // The daemon ends the route, as it does when the provider restarts.
10931        let goodbye = Frame::build(
10932            FrameType::Goodbye,
10933            Flags::new(false, Priority::Interactive, false),
10934            first.channel,
10935            first.epoch,
10936            0,
10937            Vec::new(),
10938        )
10939        .unwrap();
10940        assert!(dispatch_frame(&shared, 1, goodbye).await);
10941        assert!(matches!(
10942            shared.route_state(first),
10943            Err(CallError::StaleRouteHandle(_))
10944        ));
10945
10946        let (second_request, second) = open_answered(
10947            &shared,
10948            &consumer,
10949            &mut receiver,
10950            Some(selector.clone()),
10951            52,
10952            "the reopen after the route dropped",
10953        )
10954        .await;
10955        assert_eq!(
10956            first_request["scope"],
10957            serde_json::to_value(&selector).unwrap()
10958        );
10959        assert_eq!(second_request["scope"], first_request["scope"]);
10960        assert_ne!(second, first);
10961        shared.close_sync("test complete");
10962    }
10963
10964    /// Refuse every scoped route.open with `code` until the open settles, and
10965    /// return how many attempts were served and the error the caller got.
10966    async fn refuse_scoped_opens(code: &str) -> (usize, CallError) {
10967        refuse_scoped_operation(code, "open").await
10968    }
10969
10970    async fn refuse_scoped_operation(code: &str, operation: &str) -> (usize, CallError) {
10971        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(9));
10972        let selector = scope_selector("owner", "session-a", 1);
10973        let options = CallOptions {
10974            scope: Some(selector.clone()),
10975            timeout: Duration::from_secs(2),
10976            route_retry: RetryBackoff {
10977                base: Duration::ZERO,
10978                cap: Duration::ZERO,
10979                max_attempts: 2,
10980            },
10981            route_retry_deadline: Duration::from_millis(150),
10982            ..CallOptions::default()
10983        };
10984        let operation = operation.to_string();
10985        let mut task = tokio::spawn(async move {
10986            match operation.as_str() {
10987                "call" => consumer
10988                    .call(
10989                        restart_target("plexus"),
10990                        restart_identity(),
10991                        b"{}".to_vec(),
10992                        options,
10993                    )
10994                    .await
10995                    .map(|_| ()),
10996                "subscribe" => consumer
10997                    .subscribe(
10998                        restart_target("plexus"),
10999                        restart_identity(),
11000                        b"{}".to_vec(),
11001                        SubscribeOptions {
11002                            scope: options.scope,
11003                            route_open_timeout: options.timeout,
11004                            route_retry: options.route_retry,
11005                            route_retry_deadline: options.route_retry_deadline,
11006                            ..SubscribeOptions::default()
11007                        },
11008                    )
11009                    .await
11010                    .map(|_| ()),
11011                "open" => consumer
11012                    .open_route_scoped(
11013                        restart_target("plexus"),
11014                        restart_identity(),
11015                        scope_selector("owner", "session-a", 1),
11016                        options,
11017                    )
11018                    .await
11019                    .map(|_| ()),
11020                _ => unreachable!(),
11021            }
11022        });
11023        let mut attempts = 0usize;
11024        let err = loop {
11025            tokio::select! {
11026                command = receiver.recv() => {
11027                    let Some(command) = command else {
11028                        break task.await.unwrap().expect_err("route.open must be refused");
11029                    };
11030                    let open: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
11031                    assert_eq!(open["scope"], serde_json::to_value(&selector).unwrap());
11032                    attempts += 1;
11033                    let frame = route_open_answer(
11034                        command.frame.header.corr,
11035                        0,
11036                        Some(ErrorBody::new(code, "test refusal")),
11037                    );
11038                    assert!(dispatch_frame(&shared, 1, frame).await);
11039                }
11040                joined = &mut task => {
11041                    break joined.unwrap().expect_err("route.open must be refused");
11042                }
11043            }
11044        };
11045        shared.close_sync("test complete");
11046        (attempts, err)
11047    }
11048
11049    #[tokio::test]
11050    async fn scoped_managed_operations_retry_only_transient_scope_refusals() {
11051        for operation in ["call", "subscribe"] {
11052            for (code, retryable) in [
11053                (error_codes::SCOPE_NOT_SYNCED, true),
11054                (error_codes::SCOPE_CHANGED, true),
11055                (error_codes::SCOPE_ENDED, false),
11056                (error_codes::SCOPE_NOT_LIVE, false),
11057                (error_codes::SCOPE_EPOCH_REQUIRED, false),
11058                (error_codes::SCOPE_NOT_CARRIER, false),
11059            ] {
11060                let (attempts, err) = refuse_scoped_operation(code, operation).await;
11061                if retryable {
11062                    assert!(attempts > 1, "{operation}: {code} must be retried");
11063                } else {
11064                    assert_eq!(attempts, 1, "{operation}: {code} must be terminal");
11065                }
11066                assert!(matches!(err, CallError::NotSent(_)), "{operation}: {err}");
11067                assert_eq!(err.never_forwarded(), Some(true));
11068                assert_eq!(err.route_open_refusal().unwrap().code, code);
11069            }
11070        }
11071    }
11072
11073    #[tokio::test]
11074    async fn scoped_open_retries_not_synced_and_changed_and_ends_on_the_terminal_scope_codes() {
11075        for code in [error_codes::SCOPE_NOT_SYNCED, error_codes::SCOPE_CHANGED] {
11076            let (attempts, err) = refuse_scoped_opens(code).await;
11077            assert!(attempts > 1, "{code} must be retried, served {attempts}");
11078            assert_eq!(
11079                err.route_open_refusal().map(|body| body.code.as_str()),
11080                Some(code)
11081            );
11082        }
11083        for code in [
11084            error_codes::SCOPE_ENDED,
11085            error_codes::SCOPE_NOT_LIVE,
11086            error_codes::SCOPE_EPOCH_REQUIRED,
11087            error_codes::SCOPE_NOT_CARRIER,
11088        ] {
11089            let (attempts, err) = refuse_scoped_opens(code).await;
11090            assert_eq!(attempts, 1, "{code} is terminal and must not be retried");
11091            assert!(matches!(err, CallError::NotSent(_)));
11092            assert_eq!(
11093                err.route_open_refusal().map(|body| body.code.as_str()),
11094                Some(code)
11095            );
11096        }
11097    }
11098
11099    /// The daemon refuses the first route.open with `module_warming`, then the
11100    /// retry is written and accepted but never answered, so the retry deadline
11101    /// expires while that attempt is still waiting. The caller must still get
11102    /// the refusal it already received, as `NotSent`, rather than the bare
11103    /// "timed out at its deadline" of the unanswered attempt. A busy daemon
11104    /// that answers the final retry a few milliseconds late hits this path.
11105    #[tokio::test]
11106    async fn refusal_survives_a_retry_still_in_flight_at_the_deadline() {
11107        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(11));
11108        let options = CallOptions {
11109            timeout: Duration::from_secs(5),
11110            route_retry: RetryBackoff {
11111                base: Duration::ZERO,
11112                cap: Duration::ZERO,
11113                max_attempts: 2,
11114            },
11115            route_retry_deadline: Duration::from_millis(300),
11116            ..CallOptions::default()
11117        };
11118        let mut task = tokio::spawn(async move {
11119            consumer
11120                .open_route(restart_target("warming"), restart_identity(), options)
11121                .await
11122        });
11123        let generation = shared.lock_inner().generation;
11124        let refusal = ErrorBody {
11125            code: error_codes::MODULE_WARMING.to_string(),
11126            message: "warming is not ready".to_string(),
11127            detail: Some(serde_json::json!({"reason": "required_capability_unprovided"})),
11128        };
11129        let mut attempts = 0usize;
11130        let mut held = false;
11131        let err = loop {
11132            tokio::select! {
11133                command = receiver.recv() => {
11134                    let Some(command) = command else {
11135                        break task.await.unwrap().expect_err("route.open must fail");
11136                    };
11137                    if command.frame.header.ty != FrameType::Request {
11138                        continue;
11139                    }
11140                    attempts += 1;
11141                    if attempts == 1 {
11142                        let frame = route_open_answer(
11143                            command.frame.header.corr,
11144                            0,
11145                            Some(refusal.clone()),
11146                        );
11147                        assert!(dispatch_frame(&shared, generation, frame).await);
11148                    } else {
11149                        // What the writer task does once the frame is on the
11150                        // socket: from here a timeout is OutcomeUnknown.
11151                        held = shared.mark_pending_accepted(
11152                            command.pending.expect("a route.open is a pending request"),
11153                        );
11154                    }
11155                }
11156                joined = &mut task => {
11157                    break joined.unwrap().expect_err("route.open must fail");
11158                }
11159            }
11160        };
11161        shared.close_sync("test complete");
11162        assert_eq!(
11163            attempts, 2,
11164            "one refused attempt, then one held past the deadline"
11165        );
11166        assert!(
11167            held,
11168            "the second attempt must be accepted and left unanswered"
11169        );
11170        assert!(
11171            err.is_not_sent(),
11172            "a refused route never delivered the request: {err}"
11173        );
11174        let body = err
11175            .route_open_refusal()
11176            .unwrap_or_else(|| panic!("the refusal must survive the deadline: {err}"));
11177        assert_eq!(body.code, error_codes::MODULE_WARMING);
11178        assert_eq!(body.detail, refusal.detail);
11179    }
11180
11181    #[test]
11182    fn every_scope_close_reason_must_not_reopen() {
11183        for reason in [
11184            subc_protocol::RouteCloseReason::ScopeEnded,
11185            subc_protocol::RouteCloseReason::ScopeCarrierRemoved,
11186            subc_protocol::RouteCloseReason::ScopeDelegationChanged,
11187            subc_protocol::RouteCloseReason::ScopeParentEnded,
11188        ] {
11189            let wire = serde_json::to_value(reason).unwrap();
11190            let wire = wire.as_str().expect("a close reason is a string");
11191            assert!(wire.starts_with("scope_"), "{wire}");
11192            assert_eq!(
11193                RouteCloseReason::from_wire(wire).disposition(),
11194                RouteCloseDisposition::MustNotReopen,
11195                "a route closed for {wire} must not be reopened"
11196            );
11197        }
11198    }
11199
11200    // The fake module receives the queued Request and injects frames through the
11201    // same dispatcher as the socket reader, without a daemon process.
11202    async fn watch_subscribed() -> (
11203        SubcConsumer,
11204        mpsc::Receiver<WriteCommand>,
11205        Subscription,
11206        Frame,
11207    ) {
11208        let (shared, mut rx, handle) = reverse_test_shared(ReverseRequestRegistry::new());
11209        shared.lock_inner().one_shot_routes.insert(
11210            handle.channel,
11211            RouteState {
11212                handle,
11213                sem: Arc::new(Semaphore::new(1)),
11214                watch_sem: None,
11215                opted_in: false,
11216            },
11217        );
11218        let consumer = SubcConsumer { shared };
11219        let subscription = consumer
11220            .subscribe_route(&handle, b"watch".to_vec(), SubscribeOptions::default())
11221            .await
11222            .unwrap();
11223        let request = rx.recv().await.unwrap().frame;
11224        (consumer, rx, subscription, request)
11225    }
11226
11227    fn watch_terminal(request: &Frame, ty: FrameType, body: Vec<u8>) -> Frame {
11228        Frame::build(
11229            ty,
11230            Flags::new(false, Priority::Interactive, false),
11231            request.header.channel,
11232            request.header.epoch,
11233            request.header.corr,
11234            body,
11235        )
11236        .unwrap()
11237    }
11238
11239    fn established_route_errors() -> [(ErrorBody, bool); 3] {
11240        [
11241            (error_codes::STALE_ROUTE_EPOCH, true),
11242            (error_codes::UNKNOWN_CHANNEL, true),
11243            ("no_grant", false),
11244        ]
11245        .map(|(code, route_dead)| {
11246            (
11247                ErrorBody {
11248                    code: code.into(),
11249                    message: "request rejected".into(),
11250                    detail: Some(serde_json::json!({"channel": 5})),
11251                },
11252                route_dead,
11253            )
11254        })
11255    }
11256
11257    fn route_error(request: &Frame, body: &ErrorBody, daemon_origin: bool) -> Frame {
11258        let mut frame =
11259            watch_terminal(request, FrameType::Error, serde_json::to_vec(body).unwrap());
11260        if daemon_origin {
11261            frame.header.flags = frame.header.flags.with_daemon_origin();
11262        }
11263        frame
11264    }
11265
11266    #[tokio::test]
11267    async fn subscription_classifies_established_route_error() {
11268        for (body, route_dead) in established_route_errors() {
11269            let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11270            assert!(
11271                dispatch_frame(
11272                    &consumer.shared,
11273                    1,
11274                    route_error(&request, &body, route_dead)
11275                )
11276                .await
11277            );
11278            let end = subscription.ended().await;
11279            assert_eq!(end.is_route_dead(), route_dead, "{end:?}");
11280            let error = subscription.closed().await.unwrap_err();
11281            assert_eq!(error.is_route_dead(), route_dead, "{error:?}");
11282            if route_dead {
11283                assert_eq!(end, SubscriptionEnd::RouteDead(body.clone()));
11284                assert!(matches!(error, CallError::RouteDead(received) if *received == body));
11285            } else {
11286                assert_eq!(end, SubscriptionEnd::Error(body.clone()));
11287                assert!(matches!(error, CallError::Module(received) if received == body));
11288            }
11289        }
11290
11291        let (shared, _consumer, mut rx, _, _) = reservation_stand_in(1, 1);
11292        let permit = Arc::new(Semaphore::new(1)).acquire_owned().await.unwrap();
11293        let mut subscription = shared
11294            .send_subscription(SubscriptionSend {
11295                expected_handle: None,
11296                channel: 0,
11297                epoch: 0,
11298                body: b"watch".to_vec(),
11299                priority: Priority::Interactive,
11300                admission_class: AdmissionClass::Normal,
11301                event_buffer: 1,
11302                deadline: Instant::now() + Duration::from_secs(1),
11303                permit: RoutePermit::legacy(permit),
11304            })
11305            .await
11306            .unwrap();
11307        let request = rx.recv().await.unwrap().frame;
11308        let [(body, _), ..] = established_route_errors();
11309        assert!(dispatch_frame(&shared, 1, route_error(&request, &body, true)).await);
11310        assert_eq!(
11311            subscription.ended().await,
11312            SubscriptionEnd::Error(body.clone())
11313        );
11314        assert!(
11315            matches!(subscription.closed().await, Err(CallError::Module(received)) if received == body)
11316        );
11317    }
11318
11319    #[tokio::test]
11320    async fn subscription_ended_preserves_response_body_and_closed_stays_ok() {
11321        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11322        let body = vec![0, 255, 128, 1, 10];
11323        assert!(
11324            dispatch_frame(
11325                &consumer.shared,
11326                1,
11327                watch_terminal(&request, FrameType::Response, body.clone())
11328            )
11329            .await
11330        );
11331        subscription.closed().await.unwrap();
11332        assert_eq!(
11333            subscription.ended().await,
11334            SubscriptionEnd::Response(body.clone())
11335        );
11336        subscription.unsubscribe().unwrap();
11337        assert_eq!(subscription.ended().await, SubscriptionEnd::Response(body));
11338        assert_eq!(subscription.events().recv().await, None);
11339    }
11340
11341    #[tokio::test]
11342    async fn subscription_ended_distinguishes_empty_response_from_stream_end() {
11343        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11344        assert!(
11345            dispatch_frame(
11346                &consumer.shared,
11347                1,
11348                watch_terminal(&request, FrameType::Response, Vec::new())
11349            )
11350            .await
11351        );
11352        assert_eq!(
11353            subscription.ended().await,
11354            SubscriptionEnd::Response(Vec::new())
11355        );
11356        subscription.closed().await.unwrap();
11357    }
11358
11359    #[tokio::test]
11360    async fn subscription_ended_reports_stream_end_and_closed_stays_ok() {
11361        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11362        assert!(
11363            dispatch_frame(
11364                &consumer.shared,
11365                1,
11366                watch_terminal(&request, FrameType::StreamEnd, Vec::new())
11367            )
11368            .await
11369        );
11370        assert_eq!(subscription.ended().await, SubscriptionEnd::StreamEnd);
11371        subscription.closed().await.unwrap();
11372    }
11373
11374    #[tokio::test]
11375    async fn subscription_ended_reports_module_error_code_and_detail() {
11376        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11377        let error = ErrorBody {
11378            code: "no_grant".to_string(),
11379            message: "not accepted: no grant".to_string(),
11380            detail: Some(serde_json::json!({"capability": "watch"})),
11381        };
11382        assert!(
11383            dispatch_frame(
11384                &consumer.shared,
11385                1,
11386                watch_terminal(
11387                    &request,
11388                    FrameType::Error,
11389                    serde_json::to_vec(&error).unwrap()
11390                )
11391            )
11392            .await
11393        );
11394        assert_eq!(
11395            subscription.ended().await,
11396            SubscriptionEnd::Error(error.clone())
11397        );
11398        let CallError::Module(closed_error) = subscription.closed().await.unwrap_err() else {
11399            panic!("closed must still return the module error");
11400        };
11401        assert_eq!(closed_error, error);
11402        subscription.unsubscribe().unwrap();
11403        assert_eq!(subscription.ended().await, SubscriptionEnd::Error(error));
11404    }
11405
11406    #[tokio::test]
11407    async fn subscription_ended_reports_unsubscribe_as_cancelled_and_ignores_late_terminal() {
11408        let (consumer, mut rx, mut subscription, request) = watch_subscribed().await;
11409        subscription.unsubscribe().unwrap();
11410        subscription.unsubscribe().unwrap();
11411        subscription.closed().await.unwrap();
11412        assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
11413        let cancel = rx.recv().await.unwrap().frame;
11414        assert_eq!(cancel.header.ty, FrameType::Cancel);
11415        assert_eq!(cancel.header.corr, request.header.corr);
11416        assert!(rx.try_recv().is_err());
11417        assert!(
11418            dispatch_frame(
11419                &consumer.shared,
11420                1,
11421                watch_terminal(&request, FrameType::Response, b"late".to_vec())
11422            )
11423            .await
11424        );
11425        assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
11426    }
11427
11428    #[tokio::test]
11429    async fn subscription_ended_retains_route_close_reason() {
11430        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11431        let push = Frame::build(FrameType::Push, Flags::new(false, Priority::Interactive, false), 0, 0, 0,
11432            serde_json::to_vec(&serde_json::json!({"op": "route.closed", "module_id": "watch", "reason": "capability_denied", "channels": [request.header.channel]})).unwrap()).unwrap();
11433        assert!(dispatch_frame(&consumer.shared, 1, push).await);
11434        assert!(
11435            dispatch_frame(
11436                &consumer.shared,
11437                1,
11438                watch_terminal(&request, FrameType::Goodbye, Vec::new())
11439            )
11440            .await
11441        );
11442        let reason = RouteEndReason::Daemon(RouteCloseReason::CapabilityDenied);
11443        assert_eq!(
11444            subscription.ended().await,
11445            SubscriptionEnd::RouteClosed {
11446                reason: reason.clone()
11447            }
11448        );
11449        assert_eq!(
11450            subscription.closed().await.unwrap_err().close_reason(),
11451            Some(&reason)
11452        );
11453    }
11454
11455    #[tokio::test]
11456    async fn subscription_ended_reports_connection_loss() {
11457        let (consumer, _rx, mut subscription, _request) = watch_subscribed().await;
11458        consumer
11459            .shared
11460            .handle_generation_drop(1, "fake connection lost".to_string());
11461        assert_eq!(subscription.ended().await, SubscriptionEnd::ConnectionLost);
11462        assert!(subscription.closed().await.is_err());
11463    }
11464
11465    #[tokio::test]
11466    async fn subscription_ended_waiter_wakes_on_stream_end() {
11467        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11468        let (end, dispatched) = tokio::join!(subscription.ended(), async {
11469            tokio::task::yield_now().await;
11470            dispatch_frame(
11471                &consumer.shared,
11472                1,
11473                watch_terminal(&request, FrameType::StreamEnd, Vec::new()),
11474            )
11475            .await
11476        });
11477        assert!(dispatched);
11478        assert_eq!(end, SubscriptionEnd::StreamEnd);
11479        subscription.closed().await.unwrap();
11480    }
11481
11482    #[tokio::test]
11483    async fn subscription_ended_reports_backpressure_without_hiding_closed_error() {
11484        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11485        for _ in 0..=DEFAULT_SUBSCRIPTION_EVENT_BUFFER {
11486            assert!(
11487                dispatch_frame(
11488                    &consumer.shared,
11489                    1,
11490                    watch_terminal(&request, FrameType::StreamData, vec![1])
11491                )
11492                .await
11493            );
11494        }
11495        assert_eq!(subscription.ended().await, SubscriptionEnd::Backpressure);
11496        assert!(matches!(
11497            subscription.closed().await,
11498            Err(CallError::SubscriptionBackpressure(_))
11499        ));
11500    }
11501
11502    #[tokio::test]
11503    async fn subscription_ended_reports_client_close_as_route_closed_by_caller() {
11504        let (consumer, _rx, mut subscription, _request) = watch_subscribed().await;
11505        consumer.close().await;
11506        assert_eq!(
11507            subscription.ended().await,
11508            SubscriptionEnd::RouteClosed {
11509                reason: RouteEndReason::ClosedByCaller
11510            }
11511        );
11512        assert!(subscription.closed().await.is_err());
11513    }
11514
11515    #[test]
11516    fn drain_pending_channel_can_skip_subscriptions() {
11517        let mut pending = HashMap::new();
11518        let generation = 7;
11519        let channel = 11;
11520        let handle = RouteHandle::new(channel, 3, generation);
11521        let unary_key = PendingKey {
11522            generation,
11523            channel,
11524            epoch: handle.epoch,
11525            corr: 1,
11526        };
11527        let subscription_key = PendingKey {
11528            generation,
11529            channel,
11530            epoch: handle.epoch,
11531            corr: 2,
11532        };
11533        let (unary_tx, _unary_rx) = oneshot::channel();
11534        pending.insert(unary_key, PendingEntry::unary(unary_tx, false, None, None));
11535
11536        let (events_tx, _events_rx) = mpsc::channel(1);
11537        let (closed_tx, _closed_rx) = oneshot::channel();
11538        let (ended_tx, _ended_rx) = watch::channel(None);
11539        let permit = Arc::new(Semaphore::new(1))
11540            .try_acquire_owned()
11541            .expect("test semaphore permit should be available");
11542        pending.insert(
11543            subscription_key,
11544            PendingEntry::subscription(
11545                events_tx,
11546                closed_tx,
11547                ended_tx,
11548                RoutePermit::legacy(permit),
11549                Priority::Interactive,
11550            ),
11551        );
11552
11553        let drained = drain_pending_handle(&mut pending, handle, false);
11554        assert_eq!(drained.len(), 1);
11555        assert!(pending.contains_key(&subscription_key));
11556
11557        let drained = drain_pending_handle(&mut pending, handle, true);
11558        assert_eq!(drained.len(), 1);
11559        assert!(pending.is_empty());
11560    }
11561
11562    fn response_frame(channel: u16, epoch: u32, corr: u64, body: Vec<u8>) -> Frame {
11563        Frame::build(
11564            FrameType::Response,
11565            Flags::new(false, Priority::Interactive, false),
11566            channel,
11567            epoch,
11568            corr,
11569            body,
11570        )
11571        .unwrap()
11572    }
11573
11574    #[tokio::test]
11575    async fn stale_epoch_ingress_drops_without_settling_matching_corr() {
11576        let shared = Arc::new(reader_skew_tests::legacy_shared(
11577            PathBuf::from("/tmp/does-not-exist"),
11578            ConsumerOptions::default(),
11579        ));
11580        let (writer, _rx) = mpsc::channel(4);
11581        let current = RouteHandle::new(9, 2, 1);
11582        let stale_key = PendingKey {
11583            generation: 1,
11584            channel: 9,
11585            epoch: 1,
11586            corr: 77,
11587        };
11588        let key = PendingKey {
11589            generation: 1,
11590            channel: 9,
11591            epoch: 2,
11592            corr: 77,
11593        };
11594        let (stale_tx, mut stale_response) = oneshot::channel();
11595        let (tx, mut response) = oneshot::channel();
11596        {
11597            let mut inner = shared.lock_inner();
11598            inner.writer = Some(writer);
11599            inner.daemon_ver = "0.39.0".into();
11600            inner.route_epochs.insert(9, current);
11601            inner
11602                .pending
11603                .insert(stale_key, PendingEntry::unary(stale_tx, false, None, None));
11604            inner
11605                .pending
11606                .insert(key, PendingEntry::unary(tx, false, None, None));
11607        }
11608
11609        assert!(dispatch_frame(&shared, 1, response_frame(9, 1, 77, b"stale".to_vec())).await);
11610        assert!(matches!(
11611            response.try_recv(),
11612            Err(oneshot::error::TryRecvError::Empty)
11613        ));
11614        assert!(matches!(
11615            stale_response.try_recv(),
11616            Err(oneshot::error::TryRecvError::Empty)
11617        ));
11618        assert!(shared.lock_inner().pending.contains_key(&stale_key));
11619        assert!(shared.lock_inner().pending.contains_key(&key));
11620        assert_eq!(shared.lock_inner().dropped_route_frames, 1);
11621
11622        assert!(dispatch_frame(&shared, 1, response_frame(9, 2, 77, b"current".to_vec())).await);
11623        let PendingResult::Terminal(PendingTerminal::Response { body, .. }) =
11624            response.await.unwrap()
11625        else {
11626            panic!("current epoch must settle its own pending request");
11627        };
11628        assert_eq!(body, b"current");
11629        assert!(shared.lock_inner().pending.contains_key(&stale_key));
11630    }
11631
11632    #[tokio::test]
11633    async fn route_poll_response_must_echo_expected_handle_before_settling() {
11634        let shared = Arc::new(reader_skew_tests::legacy_shared(
11635            PathBuf::from("/tmp/does-not-exist"),
11636            ConsumerOptions::default(),
11637        ));
11638        let (writer, _rx) = mpsc::channel(4);
11639        let handle = RouteHandle::new(3, 9, 1);
11640        let key = PendingKey {
11641            generation: 1,
11642            channel: 0,
11643            epoch: 0,
11644            corr: 88,
11645        };
11646        let (tx, mut response) = oneshot::channel();
11647        {
11648            let mut inner = shared.lock_inner();
11649            inner.writer = Some(writer);
11650            inner.daemon_ver = "0.39.0".into();
11651            inner.route_epochs.insert(handle.channel, handle);
11652            inner
11653                .pending
11654                .insert(key, PendingEntry::unary(tx, false, Some(handle), None));
11655        }
11656        let wrong = serde_json::to_vec(&ClientControlResponse::RoutePoll {
11657            route_channel: handle.channel,
11658            route_epoch: handle.epoch + 1,
11659            status: Some("wrong".to_string()),
11660            live: Some(true),
11661        })
11662        .unwrap();
11663        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, key.corr, wrong)).await);
11664        assert!(matches!(
11665            response.try_recv(),
11666            Err(oneshot::error::TryRecvError::Empty)
11667        ));
11668        assert!(shared.lock_inner().pending.contains_key(&key));
11669
11670        let correct = serde_json::to_vec(&ClientControlResponse::RoutePoll {
11671            route_channel: handle.channel,
11672            route_epoch: handle.epoch,
11673            status: Some("ready".to_string()),
11674            live: Some(true),
11675        })
11676        .unwrap();
11677        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, key.corr, correct)).await);
11678        assert!(matches!(
11679            response.await.unwrap(),
11680            PendingResult::Terminal(PendingTerminal::Response { .. })
11681        ));
11682    }
11683
11684    #[tokio::test]
11685    async fn stale_connection_handle_emits_no_request_cancel_or_goodbye() {
11686        let shared = Arc::new(reader_skew_tests::legacy_shared(
11687            PathBuf::from("/tmp/does-not-exist"),
11688            ConsumerOptions::default(),
11689        ));
11690        let (writer, mut rx) = mpsc::channel(4);
11691        let stale = RouteHandle::new(4, 1, 1);
11692        let current = RouteHandle::new(4, 1, 2);
11693        {
11694            let mut inner = shared.lock_inner();
11695            inner.generation = 2;
11696            inner.writer = Some(writer);
11697            inner.daemon_ver = "0.39.0".into();
11698            inner.route_epochs.insert(4, current);
11699        }
11700
11701        let err = shared
11702            .send_request(RequestSend {
11703                binary: false,
11704                expected_handle: Some(stale),
11705                channel: stale.channel,
11706                epoch: stale.epoch,
11707                body: b"request".to_vec(),
11708                priority: Priority::Interactive,
11709                admission_class: AdmissionClass::Normal,
11710                deadline: Instant::now() + Duration::from_millis(10),
11711                retain_late_route_open: false,
11712                route_open_reverse_requests: None,
11713            })
11714            .await
11715            .unwrap_err();
11716        assert!(matches!(err, CallError::StaleRouteHandle(handle) if handle == stale));
11717        shared.send_cancel(stale, 8, Priority::Interactive);
11718        assert!(!shared.send_route_goodbye(stale, false));
11719        assert!(
11720            rx.try_recv().is_err(),
11721            "stale operations must not queue frames"
11722        );
11723    }
11724
11725    #[tokio::test]
11726    async fn route_poll_refusal_preserves_daemon_code_message_and_detail() {
11727        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
11728        let handle = RouteHandle::new(3, 9, 1);
11729        shared
11730            .lock_inner()
11731            .route_epochs
11732            .insert(handle.channel, handle);
11733        let poll = consumer.poll_route(&handle, PollKind::Liveness, Duration::from_secs(1));
11734        tokio::pin!(poll);
11735        assert_pending(poll.as_mut()).await;
11736        let request = receiver.try_recv().unwrap();
11737        let refusal = ErrorBody {
11738            code: "unknown_route".into(),
11739            message: "the route is no longer present".into(),
11740            detail: Some(serde_json::json!({ "route_channel": 3, "route_epoch": 9 })),
11741        };
11742        assert!(
11743            dispatch_frame(
11744                &shared,
11745                1,
11746                channel_zero_frame(
11747                    FrameType::Error,
11748                    request.frame.header.corr,
11749                    serde_json::to_vec(&refusal).unwrap(),
11750                ),
11751            )
11752            .await
11753        );
11754        let err = poll.await.unwrap_err();
11755        assert_eq!(err.code(), Some("unknown_route"));
11756        let CallError::Module(body) = err else {
11757            panic!("a delivered refusal must not be classified as a send failure");
11758        };
11759        assert_eq!(body.code, refusal.code);
11760        assert_eq!(body.message, refusal.message);
11761        assert_eq!(body.detail, refusal.detail);
11762    }
11763
11764    #[tokio::test]
11765    async fn late_route_open_queues_goodbye_and_full_queue_closes_connection() {
11766        let shared = Arc::new(reader_skew_tests::legacy_shared(
11767            PathBuf::from("/tmp/does-not-exist"),
11768            ConsumerOptions::default(),
11769        ));
11770        let (writer, mut rx) = mpsc::channel(2);
11771        let key = PendingKey {
11772            generation: 1,
11773            channel: 0,
11774            epoch: 0,
11775            corr: 41,
11776        };
11777        let (tx, response) = oneshot::channel();
11778        drop(response);
11779        {
11780            let mut inner = shared.lock_inner();
11781            inner.writer = Some(writer);
11782            inner.daemon_ver = "0.39.0".into();
11783            inner
11784                .pending
11785                .insert(key, PendingEntry::unary(tx, true, None, None));
11786        }
11787        let body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
11788            request_window: None,
11789            watch_window: None,
11790            route_channel: 12,
11791            route_epoch: 7,
11792        })
11793        .unwrap();
11794        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, 41, body)).await);
11795        let cleanup = rx.recv().await.unwrap().frame;
11796        assert_eq!(cleanup.header.ty, FrameType::Goodbye);
11797        assert_eq!((cleanup.header.channel, cleanup.header.epoch), (12, 7));
11798
11799        let shared = Arc::new(reader_skew_tests::legacy_shared(
11800            PathBuf::from("/tmp/does-not-exist"),
11801            ConsumerOptions {
11802                reconnect_backoff: RetryBackoff {
11803                    max_attempts: 1,
11804                    ..RetryBackoff::default()
11805                },
11806                ..ConsumerOptions::default()
11807            },
11808        ));
11809        let (writer, _rx) = mpsc::channel(1);
11810        let filler = response_frame(0, 0, 1, Vec::new());
11811        writer
11812            .try_send(WriteCommand {
11813                frame: filler,
11814                pending: None,
11815            })
11816            .unwrap();
11817        let key = PendingKey {
11818            generation: 1,
11819            channel: 0,
11820            epoch: 0,
11821            corr: 42,
11822        };
11823        let (tx, response) = oneshot::channel();
11824        drop(response);
11825        {
11826            let mut inner = shared.lock_inner();
11827            inner.writer = Some(writer);
11828            inner.daemon_ver = "0.39.0".into();
11829            inner
11830                .pending
11831                .insert(key, PendingEntry::unary(tx, true, None, None));
11832        }
11833        let body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
11834            request_window: None,
11835            watch_window: None,
11836            route_channel: 13,
11837            route_epoch: 8,
11838        })
11839        .unwrap();
11840        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, 42, body)).await);
11841        assert!(shared.lock_inner().writer.is_none());
11842    }
11843
11844    #[tokio::test]
11845    async fn correlation_allocator_emits_max_once_then_closes_without_reuse() {
11846        let shared = Arc::new(reader_skew_tests::legacy_shared(
11847            PathBuf::from("/tmp/does-not-exist"),
11848            ConsumerOptions {
11849                reconnect_backoff: RetryBackoff {
11850                    max_attempts: 1,
11851                    ..RetryBackoff::default()
11852                },
11853                ..ConsumerOptions::default()
11854            },
11855        ));
11856        let (writer, mut rx) = mpsc::channel(4);
11857        {
11858            let mut inner = shared.lock_inner();
11859            inner.writer = Some(writer);
11860            inner.daemon_ver = "0.39.0".into();
11861            inner.next_corr = Some(u64::MAX);
11862        }
11863        let request_shared = Arc::clone(&shared);
11864        let request = tokio::spawn(async move {
11865            request_shared
11866                .send_request(RequestSend {
11867                    binary: false,
11868                    expected_handle: None,
11869                    channel: 0,
11870                    epoch: 0,
11871                    body: Vec::new(),
11872                    priority: Priority::Interactive,
11873                    admission_class: AdmissionClass::Normal,
11874                    deadline: Instant::now() + Duration::from_secs(1),
11875                    retain_late_route_open: false,
11876                    route_open_reverse_requests: None,
11877                })
11878                .await
11879        });
11880        let command = rx.recv().await.unwrap();
11881        assert_eq!(command.frame.header.corr, u64::MAX);
11882        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, u64::MAX, Vec::new()),).await);
11883        assert!(request.await.unwrap().is_ok());
11884
11885        let exhausted = shared
11886            .send_request(RequestSend {
11887                binary: false,
11888                expected_handle: None,
11889                channel: 0,
11890                epoch: 0,
11891                body: Vec::new(),
11892                priority: Priority::Interactive,
11893                admission_class: AdmissionClass::Normal,
11894                deadline: Instant::now() + Duration::from_millis(10),
11895                retain_late_route_open: false,
11896                route_open_reverse_requests: None,
11897            })
11898            .await
11899            .unwrap_err();
11900        assert!(matches!(exhausted, CallError::NotSent(_)));
11901        assert!(rx.try_recv().is_err());
11902        assert!(shared.lock_inner().writer.is_none());
11903    }
11904
11905    #[tokio::test]
11906    async fn managed_call_deadline_bounds_flow_control_wait() {
11907        let shared = Arc::new(reader_skew_tests::legacy_shared(
11908            PathBuf::from("/tmp/does-not-exist"),
11909            ConsumerOptions::default(),
11910        ));
11911        let (writer, mut rx) = mpsc::channel(4);
11912        let target = RouteTarget::ToolProvider {
11913            module_id: "flow-controlled".to_string(),
11914        };
11915        let identity = BindIdentity::new("test".to_string(), "deadline".to_string());
11916        let consumer_identity = Some(ConsumerIdentity {
11917            module_id: "caller".to_string(),
11918            launch_nonce: "nonce".to_string(),
11919        });
11920        let first_opts = CallOptions {
11921            timeout: Duration::from_secs(1),
11922            consumer_identity: consumer_identity.clone(),
11923            ..CallOptions::default()
11924        };
11925        let second_opts = CallOptions {
11926            timeout: Duration::from_millis(25),
11927            consumer_identity,
11928            ..CallOptions::default()
11929        };
11930        let key = RouteKey::new(
11931            &target,
11932            &identity,
11933            first_opts.consumer_identity.as_ref(),
11934            None,
11935        );
11936        let handle = RouteHandle::new(5, 3, 1);
11937        {
11938            let mut inner = shared.lock_inner();
11939            inner.writer = Some(writer);
11940            inner.daemon_ver = "0.39.0".into();
11941            inner.cache_route(
11942                key,
11943                RouteState {
11944                    handle,
11945                    sem: Arc::new(Semaphore::new(1)),
11946                    watch_sem: None,
11947                    opted_in: false,
11948                },
11949            );
11950        }
11951
11952        let first = tokio::spawn({
11953            let consumer = SubcConsumer {
11954                shared: Arc::clone(&shared),
11955            };
11956            let target = target.clone();
11957            let identity = identity.clone();
11958            async move {
11959                consumer
11960                    .call(target, identity, b"first".to_vec(), first_opts)
11961                    .await
11962            }
11963        });
11964        let first_frame = rx
11965            .recv()
11966            .await
11967            .expect("the first request should enter the fake daemon queue");
11968        assert_eq!(first_frame.frame.header.ty, FrameType::Request);
11969        assert_eq!(first_frame.frame.body, b"first");
11970        assert!(shared.mark_pending_accepted(
11971            first_frame
11972                .pending
11973                .expect("request commands retain their pending key"),
11974        ));
11975
11976        let consumer = SubcConsumer {
11977            shared: Arc::clone(&shared),
11978        };
11979        let result = tokio::time::timeout(
11980            Duration::from_millis(250),
11981            consumer.call(target, identity, b"second".to_vec(), second_opts),
11982        )
11983        .await
11984        .expect("a flow-controlled call must finish at its own deadline")
11985        .unwrap_err();
11986        assert!(matches!(result, CallError::NotSent(_)));
11987        assert!(
11988            rx.try_recv().is_err(),
11989            "the timed-out second request must not reach the fake daemon"
11990        );
11991
11992        first.abort();
11993        let _ = first.await;
11994    }
11995
11996    #[tokio::test]
11997    async fn admitted_route_open_emits_one_frame_without_retrying_daemon_errors() {
11998        let shared = Arc::new(reader_skew_tests::legacy_shared(
11999            PathBuf::from("/tmp/does-not-exist"),
12000            ConsumerOptions {
12001                call_timeout: Duration::from_secs(1),
12002                ..ConsumerOptions::default()
12003            },
12004        ));
12005        let (writer, mut rx) = mpsc::channel(4);
12006        {
12007            let mut inner = shared.lock_inner();
12008            inner.writer = Some(writer);
12009            inner.daemon_ver = "0.39.0".into();
12010        }
12011
12012        let consumer = SubcConsumer {
12013            shared: Arc::clone(&shared),
12014        };
12015        let target = RouteTarget::ToolProvider {
12016            module_id: "admitted-target".to_string(),
12017        };
12018        let identity = BindIdentity::new("test".to_string(), "admitted".to_string());
12019        let task = tokio::spawn(async move {
12020            consumer
12021                .open_route_with_admission_facts(
12022                    target,
12023                    identity,
12024                    serde_json::json!({"schema": 1, "verified_class": "member"}),
12025                )
12026                .await
12027        });
12028
12029        let command = rx.recv().await.expect("one route.open must be queued");
12030        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
12031        let ClientControlRequest::RouteOpen {
12032            admission_facts, ..
12033        } = request
12034        else {
12035            panic!("expected route.open")
12036        };
12037        assert_eq!(
12038            admission_facts,
12039            Some(serde_json::json!({"schema": 1, "verified_class": "member"}))
12040        );
12041
12042        let error_body = serde_json::to_vec(&ErrorBody {
12043            code: "admission_facts_not_permitted".to_string(),
12044            message: "not permitted".to_string(),
12045            detail: None,
12046        })
12047        .unwrap();
12048        assert!(
12049            dispatch_frame(
12050                &shared,
12051                1,
12052                Frame::build(
12053                    FrameType::Error,
12054                    Flags::new(false, Priority::Interactive, false),
12055                    0,
12056                    0,
12057                    command.frame.header.corr,
12058                    error_body,
12059                )
12060                .unwrap(),
12061            )
12062            .await
12063        );
12064        let result = task.await.unwrap();
12065        assert!(matches!(result, Err(CallError::NotSent(_))));
12066        assert!(rx.try_recv().is_err(), "one-shot route.open must not retry");
12067    }
12068
12069    /// Drive one admitted route.open to success on a test writer and return the
12070    /// route.open request that was sent, the resolved handle, and the writer.
12071    async fn open_admitted_route_for_test(
12072        opts: Option<CallOptions>,
12073    ) -> (
12074        Arc<Shared>,
12075        SubcConsumer,
12076        ClientControlRequest,
12077        Result<RouteHandle, CallError>,
12078        mpsc::Receiver<WriteCommand>,
12079    ) {
12080        let shared = writer_test_shared();
12081        let (writer, mut rx) = mpsc::channel(8);
12082        let generation = {
12083            let mut inner = shared.lock_inner();
12084            inner.writer = Some(writer);
12085            inner.daemon_ver = "0.39.0".into();
12086            inner.generation
12087        };
12088        let consumer = SubcConsumer {
12089            shared: Arc::clone(&shared),
12090        };
12091        let target = RouteTarget::ToolProvider {
12092            module_id: "cerebellum".to_string(),
12093        };
12094        let identity = BindIdentity::new("test".to_string(), "admitted".to_string());
12095        let facts = serde_json::json!({"schema": 1, "verified_class": "member"});
12096        // The consumer is returned from the task and kept alive by the caller:
12097        // dropping it closes the connection, after which no frame is dispatched.
12098        let task = tokio::spawn(async move {
12099            let result = match opts {
12100                Some(opts) => {
12101                    consumer
12102                        .open_route_with_admission_facts_and_options(target, identity, facts, opts)
12103                        .await
12104                }
12105                None => {
12106                    consumer
12107                        .open_route_with_admission_facts(target, identity, facts)
12108                        .await
12109                }
12110            };
12111            (consumer, result)
12112        });
12113        let command = rx.recv().await.expect("one route.open must be queued");
12114        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
12115        let response = serde_json::to_vec(&ClientControlResponse::RouteOpen {
12116            request_window: None,
12117            watch_window: None,
12118            route_channel: 21,
12119            route_epoch: 4,
12120        })
12121        .unwrap();
12122        assert!(
12123            dispatch_frame(
12124                &shared,
12125                generation,
12126                Frame::build(
12127                    FrameType::Response,
12128                    Flags::new(false, Priority::Interactive, false),
12129                    0,
12130                    0,
12131                    command.frame.header.corr,
12132                    response,
12133                )
12134                .unwrap(),
12135            )
12136            .await
12137        );
12138        let (consumer, result) = tokio::time::timeout(Duration::from_secs(1), task)
12139            .await
12140            .expect("admitted route.open resolves")
12141            .unwrap();
12142        (shared, consumer, request, result, rx)
12143    }
12144
12145    #[tokio::test]
12146    async fn admitted_route_open_refusal_keeps_the_daemon_code_and_detail() {
12147        let shared = writer_test_shared();
12148        let (writer, mut rx) = mpsc::channel(8);
12149        let generation = {
12150            let mut inner = shared.lock_inner();
12151            inner.writer = Some(writer);
12152            inner.daemon_ver = "0.39.0".into();
12153            inner.generation
12154        };
12155        let consumer = SubcConsumer {
12156            shared: Arc::clone(&shared),
12157        };
12158        let task = tokio::spawn(async move {
12159            let result = consumer
12160                .open_route_with_admission_facts(
12161                    RouteTarget::ToolProvider {
12162                        module_id: "cerebellum".to_string(),
12163                    },
12164                    BindIdentity::new("test".to_string(), "admitted".to_string()),
12165                    serde_json::json!({"schema": 1, "verified_class": "member"}),
12166                )
12167                .await;
12168            (consumer, result)
12169        });
12170        let command = rx.recv().await.expect("one route.open must be queued");
12171        let refusal = ErrorBody {
12172            code: "module_warming".to_string(),
12173            message: "cerebellum is not ready".to_string(),
12174            detail: Some(serde_json::json!({"reason": "declared_not_ready"})),
12175        };
12176        assert!(
12177            dispatch_frame(
12178                &shared,
12179                generation,
12180                Frame::build(
12181                    FrameType::Error,
12182                    Flags::new(false, Priority::Interactive, false),
12183                    0,
12184                    0,
12185                    command.frame.header.corr,
12186                    serde_json::to_vec(&refusal).unwrap(),
12187                )
12188                .unwrap(),
12189            )
12190            .await
12191        );
12192        let (_consumer, result) = tokio::time::timeout(Duration::from_secs(1), task)
12193            .await
12194            .expect("admitted route.open resolves")
12195            .unwrap();
12196        let error = result.expect_err("a refused open is an error");
12197        assert!(
12198            error.is_not_sent(),
12199            "a refused open never reached the module: {error}"
12200        );
12201        let body = error
12202            .route_open_refusal()
12203            .unwrap_or_else(|| panic!("the refusal's code must survive: {error}"));
12204        assert_eq!(body.code, "module_warming");
12205        assert_eq!(
12206            body.detail,
12207            Some(serde_json::json!({"reason": "declared_not_ready"}))
12208        );
12209        assert!(
12210            error.to_string().contains("tool_provider:cerebellum"),
12211            "the error names its target: {error}"
12212        );
12213    }
12214
12215    #[tokio::test]
12216    async fn admitted_route_without_options_opens_and_declares_no_reverse_capabilities() {
12217        let (_shared, _consumer, request, result, _rx) = open_admitted_route_for_test(None).await;
12218        let ClientControlRequest::RouteOpen {
12219            consumer_capabilities,
12220            admission_facts,
12221            ..
12222        } = request
12223        else {
12224            panic!("expected route.open")
12225        };
12226        assert_eq!(consumer_capabilities, None);
12227        assert!(admission_facts.is_some());
12228        let handle = result.expect("admitted route opens");
12229        assert_eq!((handle.channel, handle.epoch), (21, 4));
12230    }
12231
12232    // An admitted route opened with handlers declares their capabilities and
12233    // delivers the provider's reverse requests to them, replying under the
12234    // provider's own correlation id: the browser plane's consent prompts arrive
12235    // as elicitation on exactly this kind of route.
12236    #[tokio::test]
12237    async fn admitted_route_with_options_delivers_elicitation_to_its_handler() {
12238        let opts = CallOptions::default();
12239        let seen = Arc::new(Mutex::new(None));
12240        let seen_by_handler = Arc::clone(&seen);
12241        let reply_body = br#"{"jsonrpc":"2.0","id":3,"result":{"action":"accept"}}"#.to_vec();
12242        let expected_reply = reply_body.clone();
12243        opts.reverse_requests
12244            .on_request("elicitation", move |body, ctx| {
12245                *seen_by_handler
12246                    .lock()
12247                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((body, ctx.corr));
12248                let reply_body = reply_body.clone();
12249                async move { reply_body }
12250            })
12251            .unwrap();
12252
12253        let (shared, _consumer, request, result, mut rx) =
12254            open_admitted_route_for_test(Some(opts)).await;
12255        let ClientControlRequest::RouteOpen {
12256            consumer_capabilities,
12257            admission_facts,
12258            ..
12259        } = request
12260        else {
12261            panic!("expected route.open")
12262        };
12263        assert_eq!(consumer_capabilities, Some(vec!["elicitation".to_string()]));
12264        assert_eq!(
12265            admission_facts,
12266            Some(serde_json::json!({"schema": 1, "verified_class": "member"}))
12267        );
12268        let handle = result.expect("admitted route opens");
12269
12270        let request_body =
12271            br#"{"jsonrpc":"2.0","id":3,"method":"elicitation/create","params":{}}"#.to_vec();
12272        assert!(
12273            dispatch_frame(
12274                &shared,
12275                handle.connection_token(),
12276                reverse_request_frame(handle, 900, request_body.clone()),
12277            )
12278            .await
12279        );
12280        let reply = tokio::time::timeout(Duration::from_secs(1), rx.recv())
12281            .await
12282            .expect("the handler replies")
12283            .unwrap()
12284            .frame;
12285        assert_eq!(reply.header.ty, FrameType::Response);
12286        assert_eq!(reply.header.corr, 900);
12287        assert_eq!(reply.header.channel, 21);
12288        assert_eq!(reply.body, expected_reply);
12289        assert_eq!(
12290            seen.lock()
12291                .unwrap_or_else(|poisoned| poisoned.into_inner())
12292                .clone(),
12293            Some((request_body, 900))
12294        );
12295    }
12296
12297    #[tokio::test]
12298    async fn route_open_waiter_deadline_is_not_sent_without_writing() {
12299        let shared = Arc::new(reader_skew_tests::legacy_shared(
12300            PathBuf::from("/tmp/does-not-exist"),
12301            ConsumerOptions::default(),
12302        ));
12303        let (writer, mut rx) = mpsc::channel(4);
12304        let target = RouteTarget::ToolProvider {
12305            module_id: "single-flight".to_string(),
12306        };
12307        let identity = BindIdentity::new("test".to_string(), "route-open".to_string());
12308        let opts = CallOptions {
12309            timeout: Duration::from_millis(25),
12310            consumer_identity: Some(ConsumerIdentity {
12311                module_id: "caller".to_string(),
12312                launch_nonce: "nonce".to_string(),
12313            }),
12314            ..CallOptions::default()
12315        };
12316        let key = RouteKey::new(&target, &identity, opts.consumer_identity.as_ref(), None);
12317        {
12318            let mut inner = shared.lock_inner();
12319            inner.writer = Some(writer);
12320            inner.daemon_ver = "0.39.0".into();
12321            inner.openings.insert(
12322                key,
12323                Opening {
12324                    waiters: Vec::new(),
12325                    closed: false,
12326                },
12327            );
12328        }
12329
12330        let consumer = SubcConsumer { shared };
12331        let result = tokio::time::timeout(
12332            Duration::from_millis(250),
12333            consumer.open_route(target, identity, opts),
12334        )
12335        .await
12336        .expect("a route.open waiter must finish at its own deadline")
12337        .unwrap_err();
12338        assert!(matches!(result, CallError::NotSent(_)));
12339        assert!(
12340            rx.try_recv().is_err(),
12341            "a timed-out route.open waiter must not write a control frame"
12342        );
12343    }
12344
12345    // A route.open whose control reply never arrives before the deadline has an
12346    // unknown outcome of its own (the daemon may have opened the channel), but
12347    // the managed call's request body was never written. The call and the
12348    // subscription must therefore report NotSent, not OutcomeUnknown: callers
12349    // use that distinction to decide whether a non-idempotent retry is safe.
12350    async fn managed_op_with_unanswered_route_open(subscribe: bool) -> CallError {
12351        let shared = Arc::new(reader_skew_tests::legacy_shared(
12352            PathBuf::from("/tmp/does-not-exist"),
12353            ConsumerOptions::default(),
12354        ));
12355        let (writer, mut rx) = mpsc::channel(4);
12356        {
12357            let mut inner = shared.lock_inner();
12358            inner.writer = Some(writer);
12359            inner.daemon_ver = "0.39.0".into();
12360        }
12361        let consumer = SubcConsumer {
12362            shared: Arc::clone(&shared),
12363        };
12364        let target = RouteTarget::ToolProvider {
12365            module_id: "slow-route-open".to_string(),
12366        };
12367        let identity = BindIdentity::new("test".to_string(), "slow-route-open".to_string());
12368        let task = tokio::spawn(async move {
12369            if subscribe {
12370                consumer
12371                    .subscribe(
12372                        target,
12373                        identity,
12374                        b"{}".to_vec(),
12375                        SubscribeOptions {
12376                            route_open_timeout: Duration::from_millis(200),
12377                            route_retry_deadline: Duration::from_millis(100),
12378                            ..SubscribeOptions::default()
12379                        },
12380                    )
12381                    .await
12382                    .map(|_| ())
12383            } else {
12384                consumer
12385                    .call(
12386                        target,
12387                        identity,
12388                        b"{}".to_vec(),
12389                        CallOptions {
12390                            timeout: Duration::from_millis(200),
12391                            route_retry_deadline: Duration::from_millis(100),
12392                            ..CallOptions::default()
12393                        },
12394                    )
12395                    .await
12396                    .map(|_| ())
12397            }
12398        });
12399
12400        // Play the writer task: accept the route.open onto the wire (so the
12401        // consumer knows the control frame left) and then never answer it,
12402        // which is what a daemon under load looks like from the client.
12403        let command = rx.recv().await.expect("route.open must be queued");
12404        assert_eq!(command.frame.header.channel, 0);
12405        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
12406        assert!(matches!(request, ClientControlRequest::RouteOpen { .. }));
12407        assert!(shared.mark_pending_accepted(command.pending.expect("route.open is tracked")));
12408
12409        let err = tokio::time::timeout(Duration::from_secs(2), task)
12410            .await
12411            .expect("the managed op must settle at its own deadline")
12412            .unwrap()
12413            .expect_err("an unanswered route.open cannot yield a route");
12414        while let Ok(command) = rx.try_recv() {
12415            assert_eq!(
12416                command.frame.header.channel, 0,
12417                "no data-plane frame may be written without an open route"
12418            );
12419        }
12420        err
12421    }
12422
12423    #[tokio::test]
12424    async fn call_whose_route_open_times_out_after_send_is_not_sent() {
12425        let err = managed_op_with_unanswered_route_open(false).await;
12426        assert!(
12427            matches!(err, CallError::NotSent(_)),
12428            "call body never left the client, got {err:?}"
12429        );
12430    }
12431
12432    #[tokio::test]
12433    async fn subscribe_whose_route_open_times_out_after_send_is_not_sent() {
12434        let err = managed_op_with_unanswered_route_open(true).await;
12435        assert!(
12436            matches!(err, CallError::NotSent(_)),
12437            "subscription request never left the client, got {err:?}"
12438        );
12439    }
12440
12441    #[tokio::test]
12442    async fn route_poll_deadline_bounds_writer_capacity() {
12443        let shared = Arc::new(reader_skew_tests::legacy_shared(
12444            PathBuf::from("/tmp/does-not-exist"),
12445            ConsumerOptions::default(),
12446        ));
12447        let (writer, mut rx) = mpsc::channel(1);
12448        let handle = RouteHandle::new(8, 4, 1);
12449        writer
12450            .try_send(WriteCommand {
12451                frame: response_frame(0, 0, 99, Vec::new()),
12452                pending: None,
12453            })
12454            .expect("the fake daemon queue should accept its filler frame");
12455        {
12456            let mut inner = shared.lock_inner();
12457            inner.writer = Some(writer);
12458            inner.daemon_ver = "0.39.0".into();
12459            inner.route_epochs.insert(handle.channel, handle);
12460        }
12461
12462        let consumer = SubcConsumer { shared };
12463        let result = tokio::time::timeout(
12464            Duration::from_millis(250),
12465            consumer.poll_route(&handle, PollKind::Liveness, Duration::from_millis(25)),
12466        )
12467        .await
12468        .expect("a control request must finish at its own deadline")
12469        .unwrap_err();
12470        assert!(matches!(result, CallError::NotSent(_)));
12471        assert_eq!(
12472            rx.recv()
12473                .await
12474                .expect("the filler must still be the only queued frame")
12475                .frame
12476                .header
12477                .corr,
12478            99
12479        );
12480        assert!(
12481            rx.try_recv().is_err(),
12482            "the timed-out control request must not reach the fake daemon"
12483        );
12484    }
12485
12486    #[tokio::test]
12487    async fn subscription_deadline_bounds_writer_capacity() {
12488        let shared = Arc::new(reader_skew_tests::legacy_shared(
12489            PathBuf::from("/tmp/does-not-exist"),
12490            ConsumerOptions::default(),
12491        ));
12492        let (writer, mut rx) = mpsc::channel(1);
12493        let handle = RouteHandle::new(9, 2, 1);
12494        let route_sem = Arc::new(Semaphore::new(1));
12495        writer
12496            .try_send(WriteCommand {
12497                frame: response_frame(0, 0, 100, Vec::new()),
12498                pending: None,
12499            })
12500            .expect("the fake daemon queue should accept its filler frame");
12501        {
12502            let mut inner = shared.lock_inner();
12503            inner.writer = Some(writer);
12504            inner.daemon_ver = "0.39.0".into();
12505            inner.cache_route(
12506                RouteKey::new(
12507                    &RouteTarget::ToolProvider {
12508                        module_id: "subscriptions".to_string(),
12509                    },
12510                    &BindIdentity::new("test".to_string(), "subscription".to_string()),
12511                    None,
12512                    None,
12513                ),
12514                RouteState {
12515                    handle,
12516                    sem: Arc::clone(&route_sem),
12517                    watch_sem: None,
12518                    opted_in: false,
12519                },
12520            );
12521        }
12522
12523        let consumer = SubcConsumer { shared };
12524        let result = tokio::time::timeout(
12525            Duration::from_millis(250),
12526            consumer.subscribe_route(
12527                &handle,
12528                b"subscribe".to_vec(),
12529                SubscribeOptions {
12530                    route_open_timeout: Duration::from_millis(25),
12531                    ..SubscribeOptions::default()
12532                },
12533            ),
12534        )
12535        .await
12536        .expect("a subscription must finish at its route-open deadline");
12537        let result = match result {
12538            Ok(_) => panic!("a subscription blocked before writing must time out"),
12539            Err(err) => err,
12540        };
12541        assert!(matches!(result, CallError::NotSent(_)));
12542        assert_eq!(
12543            rx.recv()
12544                .await
12545                .expect("the filler must still be the only queued frame")
12546                .frame
12547                .header
12548                .corr,
12549            100
12550        );
12551        assert!(
12552            rx.try_recv().is_err(),
12553            "the timed-out subscription must not reach the fake daemon"
12554        );
12555        assert!(
12556            route_sem.try_acquire().is_ok(),
12557            "a pre-write subscription timeout must release its route credit"
12558        );
12559    }
12560
12561    #[test]
12562    fn catalog_list_deserializes_golden_reply_and_ignores_unknown_fields() {
12563        let mut reply: serde_json::Value = serde_json::from_str(include_str!(
12564            "../../subc-control/tests/golden/client_control_response_catalog_list.json"
12565        ))
12566        .expect("the catalog.list golden reply must be valid JSON");
12567        reply["future_top_level"] = serde_json::json!(true);
12568        reply["modules"][0]["future_module_field"] = serde_json::json!("ignored");
12569
12570        let catalog: CatalogList =
12571            serde_json::from_value(reply).expect("catalog.list should tolerate additive fields");
12572        assert_eq!(catalog.generation, 7);
12573        assert_eq!(catalog.modules.len(), 1);
12574        assert!(catalog.subc_ops.iter().any(|op| op == "catalog.list"));
12575
12576        let tools = catalog.modules[0]
12577            .roles
12578            .iter()
12579            .find_map(|role| match role {
12580                subc_protocol::manifest::ProviderRole::ToolProvider { tools, .. } => Some(tools),
12581                _ => None,
12582            })
12583            .expect("the golden module must advertise a tool_provider role");
12584        let tool = tools
12585            .first()
12586            .expect("the golden tool_provider role must advertise a tool");
12587        assert!(!tool.name.is_empty());
12588        assert_eq!(
12589            tool.schema.get("type").and_then(serde_json::Value::as_str),
12590            Some("object")
12591        );
12592        assert!(matches!(
12593            tool.execution_mode,
12594            subc_protocol::manifest::ExecutionMode::Pure
12595        ));
12596    }
12597
12598    #[tokio::test]
12599    async fn catalog_list_sends_an_unfiltered_channel_zero_request() {
12600        let shared = Arc::new(reader_skew_tests::legacy_shared(
12601            PathBuf::from("/tmp/does-not-exist"),
12602            ConsumerOptions::default(),
12603        ));
12604        let (writer, mut rx) = mpsc::channel(1);
12605        shared.lock_inner().writer = Some(writer);
12606        shared.lock_inner().daemon_ver = "0.39.0".into();
12607
12608        let consumer = SubcConsumer {
12609            shared: Arc::clone(&shared),
12610        };
12611        let request = tokio::spawn(async move { consumer.catalog_list().await });
12612        let command = rx
12613            .recv()
12614            .await
12615            .expect("catalog.list must queue a channel-0 request");
12616        assert_eq!(command.frame.header.channel, 0);
12617        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
12618        assert_eq!(body["op"], "catalog.list");
12619        assert!(
12620            body.get("module_id").is_none(),
12621            "catalog.list must request the complete catalog without a module filter"
12622        );
12623
12624        let response = serde_json::to_vec(&ClientControlResponse::CatalogList {
12625            generation: 9,
12626            modules: Vec::new(),
12627            subc_ops: vec!["catalog.list".to_string()],
12628        })
12629        .unwrap();
12630        assert!(
12631            dispatch_frame(
12632                &shared,
12633                1,
12634                response_frame(0, 0, command.frame.header.corr, response),
12635            )
12636            .await
12637        );
12638        let catalog = request.await.unwrap().unwrap();
12639        assert_eq!(catalog.generation, 9);
12640        assert!(catalog.modules.is_empty());
12641    }
12642
12643    #[tokio::test]
12644    async fn spawn_snapshot_sends_a_channel_zero_request_and_returns_the_snapshot() {
12645        let shared = Arc::new(reader_skew_tests::legacy_shared(
12646            PathBuf::from("/tmp/does-not-exist"),
12647            ConsumerOptions::default(),
12648        ));
12649        let (writer, mut rx) = mpsc::channel(1);
12650        shared.lock_inner().writer = Some(writer);
12651        shared.lock_inner().daemon_ver = "0.39.0".into();
12652
12653        let consumer = SubcConsumer {
12654            shared: Arc::clone(&shared),
12655        };
12656        let request = tokio::spawn(async move { consumer.spawn_snapshot().await });
12657        let command = rx
12658            .recv()
12659            .await
12660            .expect("supervisor.spawn_snapshot must queue a channel-0 request");
12661        assert_eq!(command.frame.header.channel, 0);
12662        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
12663        assert_eq!(body["op"], "supervisor.spawn_snapshot");
12664
12665        let snapshot = SpawnSnapshot {
12666            cursor: SpawnCursor {
12667                daemon_incarnation: "incarnation-a".to_string(),
12668                seq: 41,
12669            },
12670            ring_bound: 256,
12671            live: vec![LiveSpawn {
12672                module_id: "participant".to_string(),
12673                spawn_generation: 3,
12674                pid: 4242,
12675                spawned_at_ms: 1_700_000_000_000,
12676            }],
12677        };
12678        let response = serde_json::to_vec(&ClientControlResponse::SupervisorSpawnSnapshot {
12679            snapshot: snapshot.clone(),
12680        })
12681        .unwrap();
12682        assert!(
12683            dispatch_frame(
12684                &shared,
12685                1,
12686                response_frame(0, 0, command.frame.header.corr, response),
12687            )
12688            .await
12689        );
12690        assert_eq!(request.await.unwrap().unwrap(), snapshot);
12691    }
12692
12693    #[tokio::test]
12694    async fn spawn_snapshot_refusal_keeps_the_daemon_code() {
12695        let shared = Arc::new(reader_skew_tests::legacy_shared(
12696            PathBuf::from("/tmp/does-not-exist"),
12697            ConsumerOptions::default(),
12698        ));
12699        let (writer, mut rx) = mpsc::channel(1);
12700        shared.lock_inner().writer = Some(writer);
12701        shared.lock_inner().daemon_ver = "0.39.0".into();
12702
12703        let consumer = SubcConsumer {
12704            shared: Arc::clone(&shared),
12705        };
12706        let request = tokio::spawn(async move { consumer.spawn_snapshot().await });
12707        let command = rx
12708            .recv()
12709            .await
12710            .expect("supervisor.spawn_snapshot must queue a channel-0 request");
12711        let refusal = serde_json::to_vec(&ErrorBody {
12712            code: "op_not_permitted".to_string(),
12713            message: "refused by the test".to_string(),
12714            detail: None,
12715        })
12716        .unwrap();
12717        let frame = Frame::build(
12718            FrameType::Error,
12719            Flags::new(false, Priority::Interactive, false),
12720            0,
12721            0,
12722            command.frame.header.corr,
12723            refusal,
12724        )
12725        .unwrap();
12726        assert!(dispatch_frame(&shared, 1, frame).await);
12727        let error = request.await.unwrap().unwrap_err();
12728        assert_eq!(error.code(), Some("op_not_permitted"));
12729    }
12730
12731    fn spawn_cursor(seq: u64) -> SpawnCursor {
12732        SpawnCursor {
12733            daemon_incarnation: "incarnation-a".to_string(),
12734            seq,
12735        }
12736    }
12737
12738    fn spawn_event(seq: u64, kind: SpawnEventKind, generation: u64) -> SpawnEvent {
12739        SpawnEvent {
12740            cursor: spawn_cursor(seq),
12741            kind,
12742            module_id: "participant".to_string(),
12743            spawn_generation: generation,
12744            pid: 4242,
12745            exit_code: (kind == SpawnEventKind::Exited).then_some(0),
12746            exit_signal: None,
12747        }
12748    }
12749
12750    fn channel_zero_frame(ty: FrameType, corr: u64, body: Vec<u8>) -> Frame {
12751        Frame::build(
12752            ty,
12753            Flags::new(false, Priority::Interactive, false),
12754            0,
12755            0,
12756            corr,
12757            body,
12758        )
12759        .unwrap()
12760    }
12761
12762    fn spawn_error_frame(corr: u64, code: &str, detail: serde_json::Value) -> Frame {
12763        channel_zero_frame(
12764            FrameType::Error,
12765            corr,
12766            serde_json::to_vec(&ErrorBody {
12767                code: code.to_string(),
12768                message: "sent by the test".to_string(),
12769                detail: Some(detail),
12770            })
12771            .unwrap(),
12772        )
12773    }
12774
12775    /// A consumer over the writer-test harness, subscribed from `since`, with the
12776    /// request frame it queued.
12777    async fn spawn_subscribed(
12778        since: Option<SpawnCursor>,
12779    ) -> (
12780        Arc<Shared>,
12781        mpsc::Receiver<WriteCommand>,
12782        SpawnSubscription,
12783        Frame,
12784    ) {
12785        let shared = writer_test_shared();
12786        let (writer, mut rx) = mpsc::channel(8);
12787        shared.lock_inner().writer = Some(writer);
12788        shared.lock_inner().daemon_ver = "0.39.0".into();
12789        let consumer = SubcConsumer {
12790            shared: Arc::clone(&shared),
12791        };
12792        let subscription = consumer
12793            .spawn_subscribe(since)
12794            .await
12795            .expect("supervisor.spawn_subscribe must be sent");
12796        std::mem::forget(consumer);
12797        let command = rx
12798            .recv()
12799            .await
12800            .expect("supervisor.spawn_subscribe must queue a channel-0 request");
12801        (shared, rx, subscription, command.frame)
12802    }
12803
12804    #[tokio::test]
12805    async fn spawn_subscribe_sends_its_cursor_on_channel_zero_and_yields_events_until_stream_end() {
12806        let (shared, _rx, mut subscription, request) =
12807            spawn_subscribed(Some(spawn_cursor(7))).await;
12808        assert_eq!(request.header.channel, 0);
12809        assert_eq!(request.header.ty, FrameType::Request);
12810        let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
12811        assert_eq!(
12812            body,
12813            serde_json::json!({
12814                "op": "supervisor.spawn_subscribe",
12815                "since": {"daemon_incarnation": "incarnation-a", "seq": 7},
12816            })
12817        );
12818
12819        let corr = request.header.corr;
12820        let events = [
12821            spawn_event(8, SpawnEventKind::Exited, 3),
12822            spawn_event(9, SpawnEventKind::Spawned, 4),
12823        ];
12824        for event in &events {
12825            let body = serde_json::to_vec(event).unwrap();
12826            assert!(
12827                dispatch_frame(
12828                    &shared,
12829                    1,
12830                    channel_zero_frame(FrameType::StreamData, corr, body)
12831                )
12832                .await
12833            );
12834        }
12835        assert!(
12836            dispatch_frame(
12837                &shared,
12838                1,
12839                channel_zero_frame(FrameType::StreamEnd, corr, Vec::new())
12840            )
12841            .await
12842        );
12843        assert_eq!(subscription.next().await.unwrap(), Some(events[0].clone()));
12844        assert_eq!(subscription.next().await.unwrap(), Some(events[1].clone()));
12845        assert_eq!(subscription.next().await.unwrap(), None);
12846        assert_eq!(
12847            subscription.next().await.unwrap(),
12848            None,
12849            "a finished stream stays finished"
12850        );
12851    }
12852
12853    #[tokio::test]
12854    async fn spawn_subscribe_without_a_cursor_omits_since() {
12855        let (_shared, _rx, _subscription, request) = spawn_subscribed(None).await;
12856        let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
12857        assert_eq!(
12858            body,
12859            serde_json::json!({"op": "supervisor.spawn_subscribe"})
12860        );
12861    }
12862
12863    #[tokio::test]
12864    async fn spawn_cursor_refusals_surface_as_coded_errors_with_their_detail() {
12865        let (shared, _rx, mut subscription, request) =
12866            spawn_subscribed(Some(spawn_cursor(7))).await;
12867        let frame = spawn_error_frame(
12868            request.header.corr,
12869            "spawn_cursor_incarnation_mismatch",
12870            serde_json::json!({"current_daemon_incarnation": "incarnation-b"}),
12871        );
12872        assert!(dispatch_frame(&shared, 1, frame).await);
12873        let error = subscription.next().await.unwrap_err();
12874        assert_eq!(error.code(), Some("spawn_cursor_incarnation_mismatch"));
12875        let SpawnStreamError::CursorIncarnationMismatch {
12876            current_daemon_incarnation,
12877            body,
12878        } = &error
12879        else {
12880            panic!("expected the incarnation refusal, got {error:?}");
12881        };
12882        assert_eq!(current_daemon_incarnation, "incarnation-b");
12883        assert_eq!(body.code, "spawn_cursor_incarnation_mismatch");
12884        assert_eq!(subscription.next().await.unwrap(), None);
12885
12886        let (shared, _rx, mut subscription, request) =
12887            spawn_subscribed(Some(spawn_cursor(1))).await;
12888        let frame = spawn_error_frame(
12889            request.header.corr,
12890            "spawn_cursor_too_old",
12891            serde_json::json!({"oldest_retained_cursor": spawn_cursor(90)}),
12892        );
12893        assert!(dispatch_frame(&shared, 1, frame).await);
12894        let error = subscription.next().await.unwrap_err();
12895        assert_eq!(error.code(), Some("spawn_cursor_too_old"));
12896        let SpawnStreamError::CursorTooOld {
12897            oldest_retained_cursor,
12898            ..
12899        } = &error
12900        else {
12901            panic!("expected the too-old refusal, got {error:?}");
12902        };
12903        assert_eq!(oldest_retained_cursor, &spawn_cursor(90));
12904    }
12905
12906    #[tokio::test]
12907    async fn a_lagged_spawn_stream_yields_its_queued_events_then_the_lag_error() {
12908        let (shared, _rx, mut subscription, request) =
12909            spawn_subscribed(Some(spawn_cursor(7))).await;
12910        let corr = request.header.corr;
12911        let queued = spawn_event(8, SpawnEventKind::Exited, 3);
12912        assert!(
12913            dispatch_frame(
12914                &shared,
12915                1,
12916                channel_zero_frame(
12917                    FrameType::StreamData,
12918                    corr,
12919                    serde_json::to_vec(&queued).unwrap()
12920                ),
12921            )
12922            .await
12923        );
12924        let frame = spawn_error_frame(
12925            corr,
12926            "spawn_subscriber_lagged",
12927            serde_json::json!({"first_undelivered_cursor": spawn_cursor(9)}),
12928        );
12929        assert!(dispatch_frame(&shared, 1, frame).await);
12930        assert_eq!(subscription.next().await.unwrap(), Some(queued));
12931        let error = subscription.next().await.unwrap_err();
12932        assert_eq!(error.code(), Some("spawn_subscriber_lagged"));
12933        let SpawnStreamError::SubscriberLagged {
12934            first_undelivered_cursor,
12935            ..
12936        } = &error
12937        else {
12938            panic!("expected the lag error, got {error:?}");
12939        };
12940        assert_eq!(first_undelivered_cursor, &spawn_cursor(9));
12941    }
12942
12943    #[tokio::test]
12944    async fn dropping_a_spawn_subscription_sends_a_channel_zero_cancel_for_its_corr() {
12945        let (_shared, mut rx, subscription, request) =
12946            spawn_subscribed(Some(spawn_cursor(7))).await;
12947        drop(subscription);
12948        let cancel = tokio::time::timeout(Duration::from_secs(1), rx.recv())
12949            .await
12950            .expect("dropping the subscription must queue a Cancel")
12951            .expect("the writer stays open");
12952        assert_eq!(cancel.frame.header.ty, FrameType::Cancel);
12953        assert_eq!(cancel.frame.header.channel, 0);
12954        assert_eq!(cancel.frame.header.corr, request.header.corr);
12955    }
12956
12957    #[tokio::test]
12958    async fn reconnect_completion_between_wait_decision_and_registration_wakes_caller() {
12959        let shared = Arc::new(reader_skew_tests::legacy_shared(
12960            PathBuf::from("/tmp/subc-client-rs-reconnect-wakeup"),
12961            ConsumerOptions::default(),
12962        ));
12963        let (sender, _receiver) = mpsc::channel(EGRESS_BUFFER);
12964        {
12965            let mut inner = shared.lock_inner();
12966            inner.reconnect = ReconnectState::Inline {
12967                generation: inner.generation,
12968            };
12969        }
12970        let completing = Arc::clone(&shared);
12971        *shared.before_wait.lock().unwrap() = Some(Box::new(move || {
12972            completing.lock_inner().writer = Some(sender);
12973            completing.lock_inner().daemon_ver = "0.39.0".into();
12974            completing.notify.notify_waiters();
12975        }));
12976
12977        let result = shared
12978            .ensure_connected_for_call(Instant::now() + Duration::from_millis(30))
12979            .await;
12980        assert!(
12981            result.is_ok(),
12982            "connected caller should not time out: {result:?}"
12983        );
12984        assert!(shared.before_wait.lock().unwrap().is_none());
12985    }
12986
12987    #[tokio::test]
12988    async fn catalog_list_deadline_is_not_sent_when_reconnection_stays_down() {
12989        let shared = Arc::new(reader_skew_tests::legacy_shared(
12990            PathBuf::from("/tmp/subc-client-rs-catalog-list-unavailable"),
12991            ConsumerOptions {
12992                call_timeout: Duration::from_millis(25),
12993                reconnect_backoff: RetryBackoff {
12994                    base: Duration::from_millis(1),
12995                    cap: Duration::from_millis(1),
12996                    max_attempts: 100,
12997                },
12998                ..ConsumerOptions::default()
12999            },
13000        ));
13001        let consumer = SubcConsumer { shared };
13002        let result = tokio::time::timeout(Duration::from_millis(250), consumer.catalog_list())
13003            .await
13004            .expect("catalog.list must finish at its configured deadline")
13005            .unwrap_err();
13006        assert!(matches!(result, CallError::NotSent(_)));
13007    }
13008
13009    fn consumer_with_malformed_connection_file(
13010    ) -> (cortexkit_test_support::ScratchDir, SubcConsumer) {
13011        let temp = cortexkit_test_support::ScratchDir::new("consumer-malformed-connection");
13012        let path = temp.path().join("connection.json");
13013        std::fs::write(&path, b"not JSON").unwrap();
13014        #[cfg(unix)]
13015        {
13016            use std::os::unix::fs::PermissionsExt;
13017            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
13018        }
13019        let shared = Arc::new(reader_skew_tests::legacy_shared(
13020            path,
13021            ConsumerOptions {
13022                call_timeout: Duration::from_millis(100),
13023                reconnect_backoff: RetryBackoff {
13024                    base: Duration::from_millis(20),
13025                    cap: Duration::from_millis(40),
13026                    max_attempts: 6,
13027                },
13028                ..ConsumerOptions::default()
13029            },
13030        ));
13031        (temp, SubcConsumer { shared })
13032    }
13033
13034    // A malformed file fails synchronously. Keep the clock running so an unpaced
13035    // retry loop reaches its deadline instead of hanging a paused-time runtime.
13036    #[tokio::test]
13037    async fn catalog_list_backs_off_after_malformed_connection_file_and_close_cancels_it() {
13038        let (_temp, consumer) = consumer_with_malformed_connection_file();
13039        let call = consumer.catalog_list();
13040        tokio::pin!(call);
13041        assert_pending(call.as_mut()).await;
13042        consumer.close().await;
13043        let err = call.await.unwrap_err();
13044        assert!(matches!(err, CallError::NotSent(_)));
13045        assert!(err.to_string().contains("consumer closed"));
13046    }
13047
13048    #[tokio::test]
13049    async fn spawn_snapshot_backs_off_after_malformed_connection_file_and_close_cancels_it() {
13050        let (_temp, consumer) = consumer_with_malformed_connection_file();
13051        let call = consumer.spawn_snapshot();
13052        tokio::pin!(call);
13053        assert_pending(call.as_mut()).await;
13054        consumer.close().await;
13055        let err = call.await.unwrap_err();
13056        assert!(matches!(err, CallError::NotSent(_)));
13057        assert!(err.to_string().contains("consumer closed"));
13058    }
13059}
13060
13061#[cfg(test)]
13062mod launch_nonce_redaction_tests {
13063    use super::*;
13064
13065    const NONCE: &str = "nonce-f00dfeed1234abcd";
13066
13067    #[test]
13068    fn option_types_and_route_keys_never_print_the_nonce() {
13069        let identity = ConsumerIdentity {
13070            module_id: "wernicke".to_string(),
13071            launch_nonce: NONCE.to_string(),
13072        };
13073        let call = CallOptions {
13074            consumer_identity: Some(identity.clone()),
13075            ..CallOptions::default()
13076        };
13077        let key = ConsumerIdentityKey::from(&identity);
13078        for printed in [format!("{call:?}"), format!("{key:?}")] {
13079            assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
13080        }
13081    }
13082}